PageRenderTime 48ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/poller-service.py

https://gitlab.com/exectek/librenms
Python | 306 lines | 279 code | 7 blank | 20 comment | 7 complexity | 8407ef15c9d4bb214ac63c5964dc0e26 MD5 | raw file
Possible License(s): GPL-2.0, GPL-3.0
  1. #! /usr/bin/env python
  2. """
  3. poller-service A service to wrap SNMP polling. It will poll up to $threads devices at a time, and will not re-poll
  4. devices that have been polled within the last $poll_frequency seconds. It will prioritize devices based
  5. on the last time polled. If resources are sufficient, this service should poll every device every
  6. $poll_frequency seconds, but should gracefully degrade if resources are inefficient, polling devices as
  7. frequently as possible. This service is based on Job Snijders' poller-wrapper.py.
  8. Author: Clint Armstrong <clint@clintarmstrong.net>
  9. Date: July 2015
  10. License: BSD 2-Clause
  11. Copyright (c) 2015, Clint Armstrong
  12. All rights reserved.
  13. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
  14. 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  15. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
  16. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  17. """
  18. import json
  19. import os
  20. import subprocess
  21. import sys
  22. import threading
  23. import time
  24. import MySQLdb
  25. import logging
  26. import logging.handlers
  27. from datetime import datetime, timedelta
  28. log = logging.getLogger('poller-service')
  29. log.setLevel(logging.DEBUG)
  30. formatter = logging.Formatter('poller-service: %(message)s')
  31. handler = logging.handlers.SysLogHandler(address='/dev/log')
  32. handler.setFormatter(formatter)
  33. log.addHandler(handler)
  34. install_dir = os.path.dirname(os.path.realpath(__file__))
  35. config_file = install_dir + '/config.php'
  36. log.info('INFO: Starting poller-service')
  37. def get_config_data():
  38. config_cmd = ['/usr/bin/env', 'php', '%s/config_to_json.php' % install_dir]
  39. try:
  40. proc = subprocess.Popen(config_cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE)
  41. except:
  42. log.critical("ERROR: Could not execute: %s" % config_cmd)
  43. sys.exit(2)
  44. return proc.communicate()[0].decode()
  45. try:
  46. with open(config_file) as f:
  47. pass
  48. except IOError as e:
  49. log.critical("ERROR: Oh dear... %s does not seem readable" % config_file)
  50. sys.exit(2)
  51. try:
  52. config = json.loads(get_config_data())
  53. except:
  54. log.critical("ERROR: Could not load or parse configuration, are PATHs correct?")
  55. sys.exit(2)
  56. try:
  57. loglevel = int(config['poller_service_loglevel'])
  58. except KeyError:
  59. loglevel = 20
  60. except ValueError:
  61. loglevel = logging.getLevelName(config['poller_service_loglevel'])
  62. try:
  63. log.setLevel(loglevel)
  64. except ValueError:
  65. log.warning('ERROR: {0} is not a valid log level. If using python 3.4.0-3.4.1 you must specify loglevel by number'.format(str(loglevel)))
  66. log.setLevel(20)
  67. poller_path = config['install_dir'] + '/poller.php'
  68. discover_path = config['install_dir'] + '/discovery.php'
  69. db_username = config['db_user']
  70. db_password = config['db_pass']
  71. if config['db_host'][:5].lower() == 'unix:':
  72. db_server = config['db_host']
  73. db_port = 0
  74. elif ':' in config['db_host']:
  75. db_server = config['db_host'].rsplit(':')[0]
  76. db_port = int(config['db_host'].rsplit(':')[1])
  77. else:
  78. db_server = config['db_host']
  79. db_port = 0
  80. db_dbname = config['db_name']
  81. try:
  82. amount_of_workers = int(config['poller_service_workers'])
  83. if amount_of_workers == 0:
  84. amount_of_workers = 16
  85. except KeyError:
  86. amount_of_workers = 16
  87. try:
  88. poll_frequency = int(config['poller_service_poll_frequency'])
  89. if poll_frequency == 0:
  90. poll_frequency = 300
  91. except KeyError:
  92. poll_frequency = 300
  93. try:
  94. discover_frequency = int(config['poller_service_discover_frequency'])
  95. if discover_frequency == 0:
  96. discover_frequency = 21600
  97. except KeyError:
  98. discover_frequency = 21600
  99. try:
  100. down_retry = int(config['poller_service_down_retry'])
  101. if down_retry == 0:
  102. down_retry = 60
  103. except KeyError:
  104. down_retry = 60
  105. try:
  106. if db_port == 0:
  107. db = MySQLdb.connect(host=db_server, user=db_username, passwd=db_password, db=db_dbname)
  108. else:
  109. db = MySQLdb.connect(host=db_server, port=db_port, user=db_username, passwd=db_password, db=db_dbname)
  110. db.autocommit(True)
  111. cursor = db.cursor()
  112. except:
  113. log.critical("ERROR: Could not connect to MySQL database!")
  114. sys.exit(2)
  115. def poll_worker(device_id, action):
  116. try:
  117. start_time = time.time()
  118. path = poller_path
  119. if action == 'discovery':
  120. path = discover_path
  121. command = "/usr/bin/env php %s -h %s >> /dev/null 2>&1" % (path, device_id)
  122. subprocess.check_call(command, shell=True)
  123. elapsed_time = int(time.time() - start_time)
  124. if elapsed_time < 300:
  125. log.debug("DEBUG: worker finished %s of device %s in %s seconds" % (action, device_id, elapsed_time))
  126. else:
  127. log.warning("WARNING: worker finished %s of device %s in %s seconds" % (action, device_id, elapsed_time))
  128. except (KeyboardInterrupt, SystemExit):
  129. raise
  130. except:
  131. pass
  132. def lockFree(lock):
  133. global cursor
  134. query = "SELECT IS_FREE_LOCK('{0}')".format(lock)
  135. cursor.execute(query)
  136. return cursor.fetchall()[0][0] == 1
  137. def getLock(lock):
  138. global cursor
  139. query = "SELECT GET_LOCK('{0}', 0)".format(lock)
  140. cursor.execute(query)
  141. return cursor.fetchall()[0][0] == 1
  142. def releaseLock(lock):
  143. global cursor
  144. query = "SELECT RELEASE_LOCK('{0}')".format(lock)
  145. cursor.execute(query)
  146. return cursor.fetchall()[0][0] == 1
  147. def sleep_until(timestamp):
  148. now = datetime.now()
  149. if timestamp > now:
  150. sleeptime = (timestamp - now).seconds
  151. else:
  152. sleeptime = 0
  153. time.sleep(sleeptime)
  154. poller_group = ('and poller_group IN({0}) '
  155. .format(str(config['distributed_poller_group'])) if 'distributed_poller_group' in config else '')
  156. # Add last_polled and last_polled_timetaken so we can sort by the time the last poll started, with the goal
  157. # of having each device complete a poll within the given time range.
  158. dev_query = ('SELECT device_id, status, '
  159. 'CAST( '
  160. ' DATE_ADD( '
  161. ' DATE_SUB( '
  162. ' last_polled, '
  163. ' INTERVAL last_polled_timetaken SECOND '
  164. ' ), '
  165. ' INTERVAL {0} SECOND) '
  166. ' AS DATETIME(0) '
  167. ') AS next_poll, '
  168. 'CAST( '
  169. ' DATE_ADD( '
  170. ' DATE_SUB( '
  171. ' last_discovered, '
  172. ' INTERVAL last_discovered_timetaken SECOND '
  173. ' ), '
  174. ' INTERVAL {1} SECOND) '
  175. ' AS DATETIME(0) '
  176. ') as next_discovery '
  177. 'FROM devices WHERE '
  178. 'disabled = 0 '
  179. 'AND IS_FREE_LOCK(CONCAT("polling.", device_id)) '
  180. 'AND IS_FREE_LOCK(CONCAT("queued.", device_id)) '
  181. 'AND ( last_poll_attempted < DATE_SUB(NOW(), INTERVAL {2} SECOND ) '
  182. ' OR last_poll_attempted IS NULL ) '
  183. '{3} '
  184. 'ORDER BY next_poll asc '
  185. 'LIMIT 5 ').format(poll_frequency,
  186. discover_frequency,
  187. down_retry,
  188. poller_group)
  189. threads = 0
  190. next_update = datetime.now() + timedelta(minutes=1)
  191. devices_scanned = 0
  192. while True:
  193. cur_threads = threading.active_count()
  194. if cur_threads != threads:
  195. threads = cur_threads
  196. log.debug('DEBUG: {0} threads currently active'.format(threads))
  197. if next_update < datetime.now():
  198. seconds_taken = (datetime.now() - (next_update - timedelta(minutes=1))).seconds
  199. update_query = ('INSERT INTO pollers(poller_name, '
  200. ' last_polled, '
  201. ' devices, '
  202. ' time_taken) '
  203. ' values("{0}", NOW(), "{1}", "{2}") '
  204. 'ON DUPLICATE KEY UPDATE '
  205. ' last_polled=values(last_polled), '
  206. ' devices=values(devices), '
  207. ' time_taken=values(time_taken) ').format(config['distributed_poller_name'].strip(),
  208. devices_scanned,
  209. seconds_taken)
  210. try:
  211. cursor.execute(update_query)
  212. except:
  213. log.critical('ERROR: MySQL query error. Is your schema up to date?')
  214. sys.exit(2)
  215. cursor.fetchall()
  216. log.info('INFO: {0} devices scanned in the last minute'.format(devices_scanned))
  217. devices_scanned = 0
  218. next_update = datetime.now() + timedelta(minutes=1)
  219. while threading.active_count() >= amount_of_workers or not lockFree('schema_update'):
  220. time.sleep(.5)
  221. try:
  222. cursor.execute(dev_query)
  223. except:
  224. log.critical('ERROR: MySQL query error. Is your schema up to date?')
  225. sys.exit(2)
  226. devices = cursor.fetchall()
  227. for device_id, status, next_poll, next_discovery in devices:
  228. # add queue lock, so we lock the next device against any other pollers
  229. # if this fails, the device is locked by another poller already
  230. if not getLock('queued.{0}'.format(device_id)):
  231. continue
  232. if not lockFree('polling.{0}'.format(device_id)):
  233. releaseLock('queued.{0}'.format(device_id))
  234. continue
  235. if next_poll and next_poll > datetime.now():
  236. log.debug('DEBUG: Sleeping until {0} before polling {1}'.format(next_poll, device_id))
  237. sleep_until(next_poll)
  238. action = 'poll'
  239. if (not next_discovery or next_discovery < datetime.now()) and status == 1:
  240. action = 'discovery'
  241. log.debug('DEBUG: Starting {0} of device {1}'.format(action, device_id))
  242. devices_scanned += 1
  243. cursor.execute('UPDATE devices SET last_poll_attempted = NOW() WHERE device_id = {0}'.format(device_id))
  244. cursor.fetchall()
  245. t = threading.Thread(target=poll_worker, args=[device_id, action])
  246. t.start()
  247. # If we made it this far, break out of the loop and query again.
  248. break
  249. # This point is only reached if the query is empty, so sleep half a second before querying again.
  250. time.sleep(.5)
  251. # Make sure we're not holding any device queue locks in this connection before querying again
  252. # by locking a different string.
  253. getLock('unlock.{0}'.format(config['distributed_poller_name']))