batcave.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  1. #!/usr/bin/python
  2. from __future__ import print_function
  3. import argparse
  4. import daemon
  5. import logging
  6. import sys
  7. import time
  8. import threading
  9. from ffstatus import *
  10. DEFAULT_INTERVAL = 15
  11. parser = argparse.ArgumentParser(description='Batman/Alfred Transmission Collection, Aggregation & Value Engine')
  12. parser.add_argument('--logfile', help='path for log file')
  13. parser.add_argument('--interval', type=int, default=DEFAULT_INTERVAL, help='data poll interval')
  14. parser.add_argument('-v', '--verbose', action='store_true', help='increase output verbosity')
  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. parser.add_argument('-S', '--storage-dir', default='.', help='Path where to store data')
  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(args.storage_dir)
  43. logger.info('Storage: ' + str(storage))
  44. a = AlfredParser()
  45. b = BatmanParser()
  46. d = DashingClient(args.dashing_url, args.dashing_token) if not args.dashing_url is None else None
  47. g = GraphitePush(args.graphite_host, args.graphite_port) if not args.graphite_host is None else None
  48. if args.no_send:
  49. if not g is None: g.dont_send = True
  50. if not args.alfred_json is None: a.alfred_json = args.alfred_json
  51. if not args.batadv_vis is None: b.batadv_vis = args.batadv_vis
  52. logger.debug('Configured A.L.F.R.E.D. source: ' + str(a))
  53. logger.debug('Configured B.A.T.M.A.N. source: ' + str(b))
  54. logger.debug('Configured Dashing: ' + str(d))
  55. logger.debug('Configured Graphite: ' + str(g))
  56. for i in [ ('AlfredParser', a), ('BatmanParser', b) ]:
  57. try:
  58. i[1].sanitycheck()
  59. except Exception as err:
  60. logger.critical(i[0] + '.sanitycheck() failed: ' + str(err))
  61. print('FAILED SANITY CHECK: ' + str(err))
  62. sys.exit(1)
  63. server = ApiServer((args.api_bind_host, args.api_bind_port), storage)
  64. server_thread = threading.Thread(target=server.serve_forever)
  65. server_thread.daemon = True # exit thread when main thread terminates
  66. server_thread.start()
  67. logger.info('Started server: ' + str(server))
  68. if shall_daemonize:
  69. daemon_context = daemon.DaemonContext(
  70. files_preserve = [ fh.stream ],
  71. )
  72. daemon_context.open()
  73. while True:
  74. try:
  75. ts = int(time.time())
  76. logger.debug('Step 1/3: Fetching data ...')
  77. alfreddata = a.fetch()
  78. batmandata = b.fetch()
  79. newdata = merge_alfred_batman(alfreddata, batmandata)
  80. logger.debug('Fetched data: {0} ALFRED with {1} BATMAN makes {2} total'.format(len(alfreddata), len(batmandata), len(newdata)))
  81. logger.debug('Step 2/3: Pushing update data ...')
  82. if not g is None:
  83. graphitedata = g.push(newdata, ts=ts)
  84. logger.info('Sent ' + str(graphitedata.count('\n')+1) + ' lines to Graphite.')
  85. if not d is None:
  86. d.push(newdata)
  87. logger.debug('Step 3/3: Merging current data ...')
  88. temp = dict_merge(storage.data, {})
  89. for x in temp:
  90. if not x in newdata: continue
  91. temp[x]['aliases'] = []
  92. temp[x]['clients'] = []
  93. temp[x]['neighbours'] = []
  94. if not '__RAW__' in temp[x]:
  95. temp[x]['__RAW__'] = { }
  96. if '__RAW__' in newdata[x]:
  97. for key in newdata[x]['__RAW__']:
  98. if key in temp[x]['__RAW__']:
  99. del(temp[x]['__RAW__'][key])
  100. storage.data = dict_merge(temp, newdata)
  101. # sanitize each item's data
  102. for itemid in storage.data:
  103. if itemid.startswith('__'): continue
  104. item = storage.data[itemid]
  105. # remove node's MACs from clients list
  106. clients = [ x for x in item['clients'] ] if 'clients' in item else []
  107. if 'mac' in item and item['mac'] in clients: clients.remove(item['mac'])
  108. if 'macs' in item:
  109. for x in item['macs']:
  110. if x in clients: clients.remove(x)
  111. storage.data[itemid]['clientcount'] = len(clients)
  112. logger.debug('I have data for ' + str(len(storage.data)) + ' nodes.')
  113. storage.save()
  114. except Exception as err:
  115. logger.error(str(err))
  116. logger.debug('Sleeping for {0} seconds'.format(args.interval))
  117. time.sleep(args.interval)
  118. storage.close()
  119. logger.info('Shut down.')