python实战系列之MySQL主从状态监控(09)
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python实战系列之MySQL主从状态监控(09)相关的知识,希望对你有一定的参考价值。
1. 需求说明
由于openstack底层中mysql使用了主从AB复制,为了监控数据库的主从状态信息,需要对MySQL的主从状态进行监控,从而保障数据库底层正常运行,为openstack提供更好的功能。本文对数据库执行监控,具体内容参考下面。
2. 程序内容
#!/usr/bin/env python #_*_ coding:utf8 _*_ #author:happyliu #用于监控MySQL主从复制状态 import os import sys import os.path import urllib import urllib2 import MySQLdb import logging auth_credentials = {‘host‘:‘localhost‘, ‘port‘:3306, ‘user‘:‘root‘,‘passwd‘:‘password‘} ‘‘‘ 记录日志 ‘‘‘ logging.basicConfig( filename = ‘/var/log/openstack_MySQL_replication_monitor.log‘, filemode = ‘a‘, format = ‘%(asctime)s %(filename)s[line:%(lineno)d] %(funcName)s %(levelname)s %(message)s‘, datefmt=‘%a, %d %b %Y %H:%M:%S‘, level = logging.INFO ) def monitor_MySQL_replication(): ‘‘‘ 用于监控MySQL主从复制状态,异常则告警 ‘‘‘ status = True try: conn = MySQLdb.connect(**auth_credentials) cursor = conn.cursor(cursorclass=MySQLdb.cursors.DictCursor) cursor.execute(‘SHOW SLAVE STATUS;‘) result = cursor.fetchone() if result[‘Slave_IO_Running‘] == "Yes" and result[‘Slave_SQL_Running‘] == "Yes": logging.info(‘MySQL master/slave replication status is successfully‘) else: logging.error(‘MySQL Master/Slave replication fail,Please check it‘) status = False except Exception as e: logging.error(e) status = False return status def send_warnings(receiver,content,title): ‘‘‘ 发送RTX告警给业务负责人 ‘‘‘ rtx_url = "http://www.example.com:11770/sendRtxByPost" data = { "appId" :6, "appKey" :‘password‘, "userName" :receiver, "title" :title, "content" :content } postdata = urllib.urlencode(data) req = urllib2.Request(rtx_url,postdata) return urllib2.urlopen(req) def get_hostname(): ‘‘‘ 获取Linux系统的主机名 ‘‘‘ return os.environ[‘HOSTNAME‘] def clean_log(): ‘‘‘ 清理日志文件,当文件的大于100M时,则清理该文件,防止日志占用过多空间 ‘‘‘ log_file = ‘/var/log/openstack_MySQL_replication_monitor.log‘ size = os.path.getsize(log_file) / (1024 * 1024) if size >= 100: os.remove(log_file) logging.info(‘%s have been remove‘ % (log_file)) if __name__ == "__main__": clean_log() warn_receiver = "happy;" if monitor_MySQL_replication(): send_warnings(receiver=warn_receiver,content=‘云平台MySQL主从复制状态失败,请检查数据库状态‘,title=get_hostname())
本文出自 “Happy实验室” 博客,谢绝转载!
以上是关于python实战系列之MySQL主从状态监控(09)的主要内容,如果未能解决你的问题,请参考以下文章