This is a reply to the blog post Poor man’s MySQL replication monitoring. Haidong Ji had a few problems using MySQLdb (could use the ‘dict’ cursor) and apparently he doesn’t want to much dependencies. I agree that using the mysql client tool is a nice alternative if you don’t want to use any 3rd party Python modules. And the MySQL client tools are usually and should be installed with the server.
However, since MySQL Connector/Python only needs itself and Python, dependencies are reduced to a minimum. Here you’ll find a refactored version of Haidong’s version (can of course be made much more sophisticated) using the connector:
import sys from socket import gethostname import smtplib import mysql.connector emailSubject = "Replication problem on slave %s" emailTo = "firstname.lastname@example.org" emailFrom = "email@example.com" def runCmd(cmd): cnx = mysql.connector.connect(user='root', unix_socket='/path/to/mysql.sock') cur = cnx.cursor(buffered=True) cur.execute(cmd) columns = tuple( [d.decode('utf8') for d in cur.description] ) row = cur.fetchone() if row is None: raise StandardError("MySQL Server not configured as Slave") result = dict(zip(columns, row)) cur.close() cnx.close() return result try: slave_status = runCmd("SHOW SLAVE STATUS") except mysql.connector.Error, e: print >> sys.stderr, "There was a MySQL error:", e sys.exit(1) except StandardError, e: print >> sys.stderr, "There was an error:", e sys.exit(1) if (slave_status['Slave_IO_Running'] == 'Yes' and slave_status['Slave_SQL_Running'] == 'Yes' and slave_status['Last_Errno'] == 0): print "Cool" else: emailBody = [ "From: %s" % emailFrom, "To: %s" % emailTo, "Subject: %s" % (emailSubject % gethostname()), "", '\n'.join([ k + ' : ' + str(v) for k,v in slave_status.iteritems()]), "\r\n", ] server = smtplib.SMTP("localhost") server.sendmail(emailFrom, [emailTo], '\r\n'.join(emailBody)) server.quit()