batcave.py 4.1 KB

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