24212 发表于 2016-2-23 09:18:58

python实战系列之MySQL主从状态监控

1. 需求说明
由于openstack底层中MySQL使用了主从AB复制,为了监控数据库的主从状态信息,需要对MySQL的主从状态进行监控,从而保障数据库底层正常运行,为openstack提供更好的功能。本文对数据库执行监控,具体内容参考下面。
2. 程序内容

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#!/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 %(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())






页: [1]
查看完整版本: python实战系列之MySQL主从状态监控