1. 需求說明python
因爲openstack底層中MySQL使用了主從AB複製,爲了監控數據庫的主從狀態信息,須要對MySQL的主從狀態進行監控,從而保障數據庫底層正常運行,爲openstack提供更好的功能。本文對數據庫執行監控,具體內容參考下面。數據庫
2. 程序內容app
#!/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())