batcave.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. from __future__ import print_function
  4. import argparse
  5. import daemon
  6. import logging
  7. import sys
  8. import time
  9. import threading
  10. from ffstatus import \
  11. merge_alfred_batman, \
  12. ApiServer, \
  13. AlfredParser, BatmanParser, \
  14. DashingClient, GraphitePush, \
  15. FileStorage, RedisStorage
  16. from ffstatus.exceptions import SanityCheckError
  17. BATCAVE = 'Batman/Alfred Transmission Collection, Aggregation & Value Engine'
  18. DEFAULT_INTERVAL = 15
  19. def get_args():
  20. """Parse commandline arguments."""
  21. parser = argparse.ArgumentParser(description=BATCAVE)
  22. parser.add_argument('--logfile',
  23. help='path for log file')
  24. parser.add_argument('--interval', type=int, default=DEFAULT_INTERVAL,
  25. help='data poll interval')
  26. parser.add_argument('-v', '--verbose', action='store_true',
  27. help='increase output verbosity')
  28. parser.add_argument('-d', '--no-detach', action='store_true',
  29. help='Don\'t detach (daemonize) ourself')
  30. parser.add_argument('-n', '--no-send', action='store_true',
  31. help='Fetch data but don\'t send it')
  32. parser.add_argument('-A', '--alfred-json',
  33. help='executable path for alfred-json')
  34. parser.add_argument('-B', '--batadv-vis',
  35. help='executable path for batadv-vis')
  36. parser.add_argument('-G', '--graphite-host',
  37. help='Graphite host')
  38. parser.add_argument('--graphite-port', type=int, default=2003,
  39. help='Graphite port')
  40. parser.add_argument('--dashing-url',
  41. help='Dashing URL')
  42. parser.add_argument('--dashing-token',
  43. help='Dashing\'s secret update token')
  44. parser.add_argument('--api-bind-host', default='',
  45. help='API-Server Hostname')
  46. parser.add_argument('--api-bind-port', type=int, default=8888,
  47. help='API-Server Port')
  48. parser.add_argument('-S', '--storage-dir', default='.',
  49. help='Path where to store data')
  50. return parser.parse_args()
  51. def prepare_logging(args):
  52. """Configures Python's logging according to args."""
  53. logger = logging.getLogger()
  54. logger.setLevel(logging.DEBUG if args.verbose else logging.INFO)
  55. fmt = logging.Formatter(
  56. '%(asctime)s [%(levelname)s] %(message)s',
  57. '%Y-%m-%d %H:%M:%S')
  58. if not args.logfile is None:
  59. file_handler = logging.FileHandler(args.logfile)
  60. file_handler.setFormatter(fmt)
  61. logger.addHandler(file_handler)
  62. if args.no_detach:
  63. console_handler = logging.StreamHandler(sys.stdout)
  64. console_handler.setFormatter(fmt)
  65. logger.addHandler(console_handler)
  66. return logger
  67. def main():
  68. args = get_args()
  69. if args.interval < 5:
  70. print('A poll interval lower than 5s is not supported.')
  71. sys.exit(1)
  72. shall_daemonize = not args.no_detach
  73. logger = prepare_logging(args)
  74. logger.info('Starting up')
  75. storage = FileStorage(args.storage_dir)
  76. storage.open()
  77. logger.info('Storage: ' + str(storage))
  78. alfred = AlfredParser()
  79. batman = BatmanParser()
  80. dashing = None
  81. if args.dashing_url is not None:
  82. dashing = DashingClient(args.dashing_url, args.dashing_token)
  83. graphite = None
  84. if args.graphite_host is not None:
  85. graphite = GraphitePush(args.graphite_host, args.graphite_port)
  86. if args.no_send:
  87. if graphite is not None:
  88. graphite.dont_send = True
  89. if not args.alfred_json is None:
  90. alfred.alfred_json = args.alfred_json
  91. if not args.batadv_vis is None:
  92. batman.batadv_vis = args.batadv_vis
  93. logger.debug('Configured A.L.F.R.E.D. source: %s', alfred)
  94. logger.debug('Configured B.A.T.M.A.N. source: %s', batman)
  95. logger.debug('Configured Dashing: %s', dashing)
  96. logger.debug('Configured Graphite: %s', graphite)
  97. # execute sanitycheck() where possible
  98. for i in [('AlfredParser', alfred), ('BatmanParser', batman)]:
  99. try:
  100. i[1].sanitycheck()
  101. except SanityCheckError as err:
  102. logger.critical(i[0] + '.sanitycheck() failed: ' + str(err))
  103. print('FAILED SANITY CHECK: ' + str(err))
  104. sys.exit(1)
  105. server = ApiServer((args.api_bind_host, args.api_bind_port), storage)
  106. server_thread = threading.Thread(target=server.serve_forever)
  107. server_thread.daemon = True # exit thread when main thread terminates
  108. server_thread.start()
  109. logger.info('Started server: ' + str(server))
  110. if shall_daemonize:
  111. streams = [handler.stream for handler in logger.handlers
  112. if isinstance(handler, logging.FileHandler)]
  113. daemon_context = daemon.DaemonContext(
  114. files_preserve=streams,
  115. )
  116. daemon_context.open()
  117. while True:
  118. try:
  119. now = int(time.time())
  120. logger.debug('Step 1/3: Fetching data ...')
  121. alfreddata = alfred.fetch()
  122. batmandata = batman.fetch()
  123. newdata = merge_alfred_batman(alfreddata, batmandata)
  124. logger.debug(
  125. 'Fetched data: %d ALFRED with %d BATMAN makes %d total',
  126. len(alfreddata), len(batmandata), len(newdata))
  127. logger.debug('Step 2/3: Pushing update data ...')
  128. if graphite is not None:
  129. graphitedata = graphite.push(newdata, timestamp=now)
  130. logger.info(
  131. 'Sent %d lines to Graphite.',
  132. graphitedata.count('\n')+1)
  133. if dashing is not None:
  134. dashing.push(newdata)
  135. logger.debug('Step 3/3: Merging current data ...')
  136. storage.merge_new_data(newdata)
  137. storage.save()
  138. logger.debug('I have data for %d nodes.', storage.status['nodes'])
  139. except Exception as err:
  140. import traceback
  141. logger.error(str(err) + "\n" + traceback.format_exc())
  142. logger.debug('Sleeping for {0} seconds'.format(args.interval))
  143. time.sleep(args.interval)
  144. storage.close()
  145. logger.info('Shut down.')
  146. if __name__ == '__main__':
  147. main()