batcave.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  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. parser.add_argument('-S', '--storage-dir', default='.', help='Path where to store data')
  27. args = parser.parse_args()
  28. if args.interval < 5:
  29. print('A poll interval lower than 5s is not supported.')
  30. sys.exit(1)
  31. shall_daemonize = not args.no_detach
  32. logger = logging.getLogger()
  33. logger.setLevel(logging.DEBUG if args.verbose else logging.INFO)
  34. if not args.logfile is None:
  35. fh = logging.FileHandler(args.logfile)
  36. fh.setFormatter(logging.Formatter('%(asctime)s [%(levelname)s] %(message)s', '%Y-%m-%d %H:%M:%S'))
  37. logger.addHandler(fh)
  38. if args.no_detach:
  39. ch = logging.StreamHandler(sys.stdout)
  40. ch.setFormatter(logging.Formatter('%(asctime)s [%(levelname)s] %(message)s', '%Y-%m-%d %H:%M:%S'))
  41. logger.addHandler(ch)
  42. logger.info('Starting up')
  43. storage = Storage(args.storage_dir)
  44. logger.info('Storage: ' + str(storage))
  45. a = AlfredParser()
  46. b = BatmanParser()
  47. d = DashingClient(args.dashing_url, args.dashing_token) if not args.dashing_url is None else None
  48. g = GraphitePush(args.graphite_host, args.graphite_port) if not args.graphite_host is None else None
  49. if args.no_send:
  50. if not g is None: g.dont_send = True
  51. if not args.alfred_json is None: a.alfred_json = args.alfred_json
  52. if not args.batadv_vis is None: b.batadv_vis = args.batadv_vis
  53. logger.debug('Configured A.L.F.R.E.D. source: ' + str(a))
  54. logger.debug('Configured B.A.T.M.A.N. source: ' + str(b))
  55. logger.debug('Configured Dashing: ' + str(d))
  56. logger.debug('Configured Graphite: ' + str(g))
  57. for i in [ ('AlfredParser', a), ('BatmanParser', b) ]:
  58. try:
  59. i[1].sanitycheck()
  60. except Exception as err:
  61. logger.critical(i[0] + '.sanitycheck() failed: ' + str(err))
  62. print('FAILED SANITY CHECK: ' + str(err))
  63. sys.exit(1)
  64. server = ApiServer((args.api_bind_host, args.api_bind_port), storage)
  65. server_thread = threading.Thread(target=server.serve_forever)
  66. server_thread.daemon = True # exit thread when main thread terminates
  67. server_thread.start()
  68. logger.info('Started server: ' + str(server))
  69. if shall_daemonize:
  70. daemon_context = daemon.DaemonContext(
  71. files_preserve = [ fh.stream ],
  72. )
  73. daemon_context.open()
  74. while True:
  75. try:
  76. ts = int(time.time())
  77. logger.debug('Step 1/3: Fetching data ...')
  78. alfreddata = a.fetch()
  79. batmandata = b.fetch()
  80. newdata = merge_alfred_batman(alfreddata, batmandata)
  81. logger.info('Fetched data: {0} ALFRED with {1} BATMAN makes {2} total'.format(len(alfreddata), len(batmandata), len(newdata)))
  82. logger.debug('Step 2/3: Pushing update data ...')
  83. if not g is None:
  84. graphitedata = g.push(newdata, ts=ts)
  85. logger.info('Sent ' + str(graphitedata.count('\n')+1) + ' lines to Graphite.')
  86. if not d is None:
  87. d.push(newdata)
  88. logger.debug('Step 3/3: Merging current data ...')
  89. storage.data = dict_merge(storage.data, newdata)
  90. logger.info('I have data for ' + str(len(storage.data)) + ' nodes.')
  91. storage.save()
  92. except Exception as err:
  93. logger.error(str(err))
  94. logger.debug('Sleeping for {0} seconds'.format(args.interval))
  95. time.sleep(args.interval)
  96. storage.close()
  97. logger.info('Shut down.')