前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >MySQL主从、字典死锁、连接数的Python监控脚本

MySQL主从、字典死锁、连接数的Python监控脚本

作者头像
张戈
发布2018-03-21 14:42:39
1.7K0
发布2018-03-21 14:42:39
举报
文章被收录于专栏:张戈的专栏

最近,公司的系统在天津增加了不少异地容灾,其中就有异地双主 MySQL。由于容灾环境一般只会在出现较大的网络故障或故障演习的时候用到,所以,容灾系统的可用性就只能靠监控了。

对于互联网这种赶鸭式的发展模式,很多公司都没有完善的自动化运维系统。所以,很多时候还得靠自己写脚本。

脚本越写越多,就容易出现混乱、分散难管理的窘状。所以,这次就写了一个 MySQL 的集中监控脚本,后续有新的监控加入也可以非常方便的拓展。

Python 脚本:

代码语言:javascript
复制
#!/usr/bin/python
# MySQL主从集中监控脚本
# 请在MySQL上执行如下语句,将跑脚本的机器授权一个db_monitor账号。
# grant SHOW VIEW,REPLICATION CLIENT,SHOW DATABASES,PROCESS on *.* to db_monitor@'192.168.1.10';
import MySQLdb
import os
import datetime

# 发送一个字符串告警,公司特有告警系统,可以改成其他监控方式,比如短信或邮件
def report_alarm(attr, err_msg):
    os.system('/usr/local/agenttools/agent/agentRepStr %s "%s" >/dev/null' % (attr, err_msg))

# 上报一个数值型告警,也是特有告警系统
def send_repnum(attr, num):
    os.system('/usr/local/agenttools/agent/agentRepNum %s "%s" >/dev/null' % (attr ,num) )

def monitor(db_host):
    try:
        cxn=MySQLdb.connect(db_host, 'db_monitor', '', db='mysql')   
    except MySQLdb.Error, e:  
        try:  
            sqlError =  "Error %d:%s" % (e.args[0], e.args[1])  
        except IndexError:  
            sqlError = "MySQL Error:%s" % str(e)
        report_alarm(36320, sqlError)
    
    #get mysql version
    cur=cxn.cursor()
    cur.execute('select version()')
    for item in cur.fetchall():
        if '5.0.' in item[0]:
            mysql_version = 'low'
        else:
            mysql_version = 'high'
    #show slave status
    cur=cxn.cursor()
    cur.execute('show slave status')
    for item in cur.fetchall():
        replicate_error = item[19]
        if mysql_version == 'low':
            seconds_behind_master = item[-1]
        else:
            seconds_behind_master = item[32]
    #show processlist
    cur=cxn.cursor()        
    cur.execute('show processlist')
    connect_num = len(cur.fetchall()) 
    meta_lock_num = cur.fetchall().count("meta lock")
    cxn.close() 
    return replicate_error,seconds_behind_master,connect_num,meta_lock_num

print datetime.datetime.now()

for host in open('%s/hosts.list'% os.path.dirname(os.path.realpath(__file__))):
    host = host.strip('\n')
    replicate_error = ''
    seconds_behind_master = 0
    connect_num = 0
    meta_lock_num = 0
    replicate_error,seconds_behind_master,connect_num,meta_lock_num = monitor(host)
    try:
        Seconds_behind_master = int(seconds_behind_master)
    except:
        Seconds_behind_master = seconds_behind_master
    print '==============================='
    print 'Infomation of %s' % host
    print "The Num of metalock   : %s" % meta_lock_num
    print "The Num of connection : %s" % connect_num
    # 上报当前连接数
    send = send_repnum(36713, connect_num)
    # 上报字典锁数量
    send = send_repnum(36715, meta_lock_num)
    if len(replicate_error) > 0:
        print replicate_error
        # 如果主从同步出现问题,就发送告警
        report_alarm(36320, '%s: Replicate error' % host)
    elif Seconds_behind_master > 600:
        print "Seconds behid master: %s" % Seconds_behind_master
        # 如果主从延迟超过600s,就发送告警
        report_alarm(36320, '%s: Seconds behind master ge 600' % host)
    #else:
    #   print host + " is OK!"
print '==============================='

用法很简单,只要在脚本同目录新增一个文本文件 hosts.list,一行一个 IP,然后需要在 IP 对应的 MySQL 身上新增一个 db_monitor 账号,用于监控机远程登录 MySQL(见脚本注释部分语句):

MySQL主从、字典死锁、连接数的Python监控脚本
MySQL主从、字典死锁、连接数的Python监控脚本

其他特性:

①、脚本支持 5.0 和 5.5+ MySQL 版本的 Second behid master 监控,因为新老版本这个参数的位置不一样(鹅厂很多开源软件是非常陈旧的。。。);

②、支持 MySQL 连接失败的监控;

③、支持 MySQL 主从复制的延迟和错误监控

④、支持 MySQL 的连接数和字典锁数监控

⑤、更多监控可以参考继续添加.....

好了,就这么多了,算是给自己一个备忘。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2016年07月31日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
云数据库 SQL Server
腾讯云数据库 SQL Server (TencentDB for SQL Server)是业界最常用的商用数据库之一,对基于 Windows 架构的应用程序具有完美的支持。TencentDB for SQL Server 拥有微软正版授权,可持续为用户提供最新的功能,避免未授权使用软件的风险。具有即开即用、稳定可靠、安全运行、弹性扩缩等特点。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档