標籤:python mysql主從複製
1. 需求說明
由於openstack底層中MySQL使用了主從AB複製,為了監控資料庫的主從狀態資訊,需要對MySQL的主從狀態進行監控,從而保障資料庫底層正常運行,為openstack提供更好的功能。本文對資料庫執行監控,具體內容參考下面。
2. 程式內容
#!/usr/bin/env python#_*_ coding:utf8 _*_#author:happyliu#用於監控MySQL主從複製狀態import osimport sysimport os.pathimport urllibimport urllib2import MySQLdbimport loggingauth_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 statusdef 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)