batcave.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. #!/usr/bin/python
  2. from __future__ import print_function
  3. import argparse
  4. from copy import deepcopy
  5. import daemon
  6. import logging
  7. import sys
  8. import time
  9. import threading
  10. from ffstatus import *
  11. DEFAULT_INTERVAL = 15
  12. parser = argparse.ArgumentParser(description='Batman/Alfred Transmission Collection, Aggregation & Value Engine')
  13. parser.add_argument('--logfile', help='path for log file')
  14. parser.add_argument('--interval', type=int, default=DEFAULT_INTERVAL, help='data poll interval')
  15. parser.add_argument('-d', '--no-detach', action='store_true', help='Don\'t detach (daemonize) ourself')
  16. parser.add_argument('-n', '--no-send', action='store_true', help='Fetch data but don\'t send it')
  17. parser.add_argument('-A', '--alfred-json', help='executable path for alfred-json')
  18. parser.add_argument('-B', '--batadv-vis', help='executable path for batadv-vis')
  19. parser.add_argument('-G', '--graphite-host', help='Graphite host')
  20. parser.add_argument('--graphite-port', type=int, default=2003, help='Graphite port')
  21. parser.add_argument('--dashing-url', help='Dashing URL')
  22. parser.add_argument('--dashing-token', help='Dashing\'s secret update token')
  23. parser.add_argument('--api-bind-host', default='::', help='API-Server Hostname')
  24. parser.add_argument('--api-bind-port', type=int, default=8888, help='API-Server Port')
  25. args = parser.parse_args()
  26. if args.interval < 5:
  27. print('A poll interval lower than 5s is not supported.')
  28. sys.exit(1)
  29. shall_daemonize = not args.no_detach
  30. logger = logging.getLogger()
  31. logger.setLevel(logging.DEBUG)
  32. if not args.logfile is None:
  33. fh = logging.FileHandler(args.logfile)
  34. fh.setFormatter(logging.Formatter('%(asctime)s [%(levelname)s] %(message)s', '%Y-%m-%d %H:%M:%S'))
  35. logger.addHandler(fh)
  36. if args.no_detach:
  37. ch = logging.StreamHandler(sys.stdout)
  38. ch.setFormatter(logging.Formatter('%(asctime)s [%(levelname)s] %(message)s', '%Y-%m-%d %H:%M:%S'))
  39. logger.addHandler(ch)
  40. logger.info('Starting up')
  41. storage = Storage()
  42. a = AlfredParser()
  43. b = BatmanParser()
  44. d = DashingClient(args.dashing_url, args.dashing_token) if not args.dashing_url is None else None
  45. g = GraphitePush(args.graphite_host, args.graphite_port) if not args.graphite_host is None else None
  46. if args.no_send:
  47. if not g is None: g.dont_send = True
  48. if not args.alfred_json is None: a.alfred_json = args.alfred_json
  49. if not args.batadv_vis is None: b.batadv_vis = args.batadv_vis
  50. logger.debug('Configured A.L.F.R.E.D. source: ' + str(a))
  51. logger.debug('Configured B.A.T.M.A.N. source: ' + str(b))
  52. logger.debug('Configured Dashing: ' + str(d))
  53. logger.debug('Configured Graphite: ' + str(g))
  54. for i in [ ('AlfredParser', a), ('BatmanParser', b) ]:
  55. try:
  56. i[1].sanitycheck()
  57. except Exception as err:
  58. logger.critical(i[0] + '.sanitycheck() failed: ' + str(err))
  59. print('FAILED SANITY CHECK: ' + str(err))
  60. sys.exit(1)
  61. server = ApiServer((args.api_bind_host, args.api_bind_port), storage)
  62. server_thread = threading.Thread(target=server.serve_forever)
  63. server_thread.daemon = True # exit thread when main thread terminates
  64. server_thread.start()
  65. logger.info('Started server: ' + str(server))
  66. if shall_daemonize:
  67. daemon_context = daemon.DaemonContext(
  68. files_preserve = [ fh.stream ],
  69. )
  70. daemon_context.open()
  71. while True:
  72. try:
  73. ts = int(time.time())
  74. logger.debug('Step 1/3: Fetching data ...')
  75. alfreddata = a.fetch()
  76. batmandata = b.fetch()
  77. newdata = merge_alfred_batman(alfreddata, batmandata)
  78. logger.info('Fetched data: {0} ALFRED with {1} BATMAN makes {2} total'.format(len(alfreddata), len(batmandata), len(newdata)))
  79. logger.debug('Step 2/3: Pushing update data ...')
  80. if not g is None:
  81. graphitedata = g.push(newdata, ts=ts)
  82. logger.info('Sent ' + str(graphitedata.count('\n')+1) + ' lines to Graphite.')
  83. if not d is None:
  84. d.push(newdata)
  85. logger.debug('Step 3/3: Merging current data ...')
  86. storage.data = dict_merge(storage.data, newdata)
  87. logger.info('I have data for ' + str(len(storage.data)) + ' nodes.')
  88. except Exception as err:
  89. logger.error(str(err))
  90. logger.debug('Sleeping for {0} seconds'.format(args.interval))
  91. time.sleep(args.interval)
  92. logger.info('Shut down.')