batcave.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  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('-C', '--batctl',
  37. help='executable path for batctl')
  38. parser.add_argument('-G', '--graphite-host',
  39. help='Graphite host')
  40. parser.add_argument('--graphite-port', type=int, default=2003,
  41. help='Graphite port')
  42. parser.add_argument('--dashing-url',
  43. help='Dashing URL')
  44. parser.add_argument('--dashing-token',
  45. help='Dashing\'s secret update token')
  46. parser.add_argument('--api-bind-host', default='',
  47. help='API-Server Hostname')
  48. parser.add_argument('--api-bind-port', type=int, default=8888,
  49. help='API-Server Port')
  50. parser.add_argument('-S', '--storage', default='.',
  51. help='Path where to store data or ' +
  52. '"redis:[<host>[:<port>[:<password>]]]')
  53. return parser.parse_args()
  54. def prepare_logging(args):
  55. """Configures Python's logging according to args."""
  56. logger = logging.getLogger()
  57. logger.setLevel(logging.DEBUG if args.verbose else logging.INFO)
  58. fmt = logging.Formatter(
  59. '%(asctime)s [%(levelname)s] %(message)s',
  60. '%Y-%m-%d %H:%M:%S')
  61. if not args.logfile is None:
  62. file_handler = logging.FileHandler(args.logfile)
  63. file_handler.setFormatter(fmt)
  64. logger.addHandler(file_handler)
  65. if args.no_detach:
  66. console_handler = logging.StreamHandler(sys.stdout)
  67. console_handler.setFormatter(fmt)
  68. logger.addHandler(console_handler)
  69. return logger
  70. def main():
  71. args = get_args()
  72. if args.interval < 5:
  73. print('A poll interval lower than 5s is not supported.')
  74. sys.exit(1)
  75. shall_daemonize = not args.no_detach
  76. logger = prepare_logging(args)
  77. logger.info('Starting up')
  78. storage = None
  79. storage_target = args.storage
  80. if storage_target.startswith('redis:'):
  81. redis_opts = storage_target.split(':')
  82. redis_host = redis_opts[1] if len(redis_opts) > 1 else 'localhost'
  83. redis_port = int(redis_opts[2]) if len(redis_opts) > 2 else 6379
  84. redis_pass = redis_opts[3] if len(redis_opts) > 3 else None
  85. storage = RedisStorage(redis_host, redis_port, redis_pass)
  86. else:
  87. storage = FileStorage(args.storage)
  88. storage.open()
  89. logger.info('Storage: ' + str(storage))
  90. alfred = AlfredParser()
  91. batman = BatmanParser()
  92. dashing = None
  93. if args.dashing_url is not None:
  94. dashing = DashingClient(args.dashing_url, args.dashing_token)
  95. graphite = None
  96. if args.graphite_host is not None:
  97. graphite = GraphitePush(args.graphite_host, args.graphite_port)
  98. if args.no_send:
  99. if graphite is not None:
  100. graphite.dont_send = True
  101. if not args.alfred_json is None:
  102. alfred.alfred_json = args.alfred_json
  103. if not args.batadv_vis is None:
  104. batman.batadv_vis = args.batadv_vis
  105. if not args.batctl is None:
  106. batman.batctl = args.batctl
  107. logger.debug('Configured A.L.F.R.E.D. source: %s', alfred)
  108. logger.debug('Configured B.A.T.M.A.N. source: %s', batman)
  109. logger.debug('Configured Dashing: %s', dashing)
  110. logger.debug('Configured Graphite: %s', graphite)
  111. # execute sanitycheck() where possible
  112. for i in [('AlfredParser', alfred), ('BatmanParser', batman)]:
  113. try:
  114. i[1].sanitycheck()
  115. except SanityCheckError as err:
  116. logger.critical(i[0] + '.sanitycheck() failed: ' + str(err))
  117. print('FAILED SANITY CHECK: ' + str(err))
  118. sys.exit(1)
  119. server = ApiServer((args.api_bind_host, args.api_bind_port), storage)
  120. server_thread = threading.Thread(target=server.serve_forever)
  121. server_thread.daemon = True # exit thread when main thread terminates
  122. server_thread.start()
  123. logger.info('Started server: ' + str(server))
  124. if shall_daemonize:
  125. streams = [handler.stream for handler in logger.handlers
  126. if isinstance(handler, logging.FileHandler)]
  127. daemon_context = daemon.DaemonContext(
  128. files_preserve=streams,
  129. )
  130. daemon_context.open()
  131. while True:
  132. try:
  133. now = int(time.time())
  134. logger.debug('Step 1/3: Fetching data ...')
  135. alfreddata = alfred.fetch()
  136. batmandata = batman.fetch()
  137. newdata = merge_alfred_batman(alfreddata, batmandata)
  138. logger.debug(
  139. 'Fetched data: %d ALFRED with %d BATMAN makes %d total',
  140. len(alfreddata), len(batmandata), len(newdata))
  141. logger.debug('Step 2/3: Pushing update data ...')
  142. if graphite is not None:
  143. graphitedata = graphite.push(newdata, timestamp=now)
  144. logger.info(
  145. 'Sent %d lines to Graphite.',
  146. graphitedata.count('\n')+1)
  147. if dashing is not None:
  148. dashing.push(newdata)
  149. logger.debug('Step 3/3: Merging current data ...')
  150. storage.merge_new_data(newdata)
  151. storage.save()
  152. logger.debug('I have data for %d nodes.', storage.status['nodes'])
  153. except Exception as err:
  154. import traceback
  155. logger.error(str(err) + "\n" + traceback.format_exc())
  156. logger.debug('Sleeping for {0} seconds'.format(args.interval))
  157. time.sleep(args.interval)
  158. storage.close()
  159. logger.info('Shut down.')
  160. if __name__ == '__main__':
  161. main()