def mysql_monitor(on_db_changed): global cur, conn global HOST, PORT, USERNAME, PASSWORD, DATABASE, CHARSET, RETRY_TIME try: conn = MySQLdb.connect(host=HOST, user=USERNAME, passwd=PASSWORD, db=DATABASE, port=PORT, charset=CHARSET) RETRY_TIME = 5 cur = conn.cursor() pre = get_records(cur) while not STOP: changed = False time.sleep(MONITOR_TIME) conn.commit() last = get_records(cur) for i in monitor_charts: result = get_result(i, last[i]['head'], pre[i]['rs'], last[i]['rs']) if result['result'] == 2: print i + ": Length don't same ,please niu check~\n" if result['result'] == 1: changed = True on_db_changed(format_result(i, set(pre[i]['rs']), set(last[i]['rs'])), result) if not changed: print get_time() + ' No change' else: pre = copy.deepcopy(last) except MySQLdb.Error, e: print "Mysql Error %d: %s" % (e.args[0], e.args[1])
def get_result(chart, head, pre, last): result = {"result": 0, "time": get_time(), "chart": chart, "head": head, "old": [], "new": []} pset, lset = set(pre), set(last) if len(pset) != len(pre) or len(lset) != len(last): result["result"] = 2 result["comment"] = "Length don't same ,please niu check" return result old, new = list(pset - lset), list(lset - pset) if len(old) == 0 and len(new) == 0: result["comment"] = "No Record Change" return result result["result"], result["old"], result["new"] = 1, old, new if len(old) == 0: result["comment"] = "Add " + str(len(new)) + " Records" elif len(new) == 0: result["comment"] = "Delete " + str(len(old)) + " Records" else: result["comment"] = "Old: " + str(len(old)) + " New: " + str(len(new)) + " " return result