Due to the need to saltstack all the action of the Storage collection, online collection script MySQL connection will be disconnected due to timeout, causing the daemon to be prompted during the next data acquisition:
Traceback (most recent call last): File "./salt_event_to_mysql.py", line-up, in <module> ret[' success '], Json.du MPs (ret))) file "build/bdist.linux-x86_64/egg/mysqldb/cursors.py", line 173, in execute file "build/bdist.linux-x86_64 /egg/mysqldb/connections.py ", line-defaulterrorhandler_mysql_exceptions, in. Operationalerror: (2006, ' MySQL server has gone away ')
After exit, the workaround is to use a similar mysql_ping () method to do a detection before each data storage, wake up the connection, the following is the complete code:
#!/bin/env python#coding=utf8# import python libsimport json# import salt modulesimport salt.configimport salt.utils.event# Import third party Libsimport mysqldb__opts__ = salt.config.client_config ('/etc/salt/master ') # Create Mysql connectconn = mysqldb.connect (host=__opts__[' MySQL ' [' Host '], user=__opts__[' MySQL ') [' User '], passwd=__opts__[' mysql ' [' Pass '], db=__opts__[' MySQL '] [' db '], port=__opts__[' MySQL '] [ ' Port ']) cursor = conn.cursor () # listen salt master event systemevent = salt.utils.event.masterevent (__opts__[' Sock_dir ') for eachevent in event.iter_events (full =true): ### #保持连接的部分 ########### if conn is none: conn = mysqldb.connect (host=__opts__[' MySQL ' [' Host ') ], user=__opts__[' MySQL '] [' User '], passwd=__opts__[' mysql ' [' Pass '], db=__opts__[' MySQL '] [' db '], port=__opts__[' MySQL '] [ ' Port ']) cursor = conn.cursor () else: conn.ping (True) ############ ############### ret = eachevent[' data '] if "salt/job/" in eachevent[' tag ']: # return event if ret.has_key (' id ') and ret.has_key (' return '): # Igonre saltutil.find_job event if ret[' fun '] == ' Saltutil.find_job": continue if ret[' fun '] == ' Test.ping ": continue sql = ' INSERT INTO ' Salt_returns ' (' fun ', ' Jid ', ' return ', ' id ', ' success ', ' Full_ret ' ) VALUES (%s, %s, %s, %s, %s, %s) " cursor.execute (sql, (ret[' fun '], ret[' Jid '], json.dumps (ret[' return '), ret[' id '], ret[' Success '], json.dumps (ret))) cursor.execute ("COMMIT") # other event else: pass
Keep MySQL connected under Python and avoid the "MySQL server has gone away" method