ffpb_netstatus.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. # -*- coding: utf-8 -*-
  2. from __future__ import print_function
  3. import willie
  4. import json
  5. import shelve
  6. import time
  7. import urllib2
  8. from ffpb import ffpb_fetch_stats, get_alfred_data, pretty_date
  9. highscores = None
  10. def setup(bot):
  11. """Called by willie upon loading this plugin."""
  12. global highscores
  13. # load highscores from disk
  14. highscores = shelve.open('highscoredata', writeback=True)
  15. if not 'nodes' in highscores:
  16. highscores['nodes'] = 0
  17. highscores['nodes_ts'] = time.time()
  18. if not 'clients' in highscores:
  19. highscores['clients'] = 0
  20. highscores['clients_ts'] = time.time()
  21. def shutdown(bot):
  22. """Called by willie upon loading this plugin."""
  23. global highscores
  24. # store highscores
  25. if not highscores is None:
  26. highscores.sync()
  27. highscores.close()
  28. highscores = None
  29. @willie.module.interval(15)
  30. def ffpb_get_stats(bot):
  31. """Fetch current statistics, if the highscore changes signal this."""
  32. (nodes_active, nodes_total, clients_count) = \
  33. ffpb_fetch_stats(bot, 'http://map.paderborn.freifunk.net/nodes.json', 'ffpb_stats')
  34. highscore_changed = False
  35. if nodes_active > highscores['nodes']:
  36. highscores['nodes'] = nodes_active
  37. highscores['nodes_ts'] = time.time()
  38. highscore_changed = True
  39. if clients_count > highscores['clients']:
  40. highscores['clients'] = clients_count
  41. highscores['clients_ts'] = time.time()
  42. highscore_changed = True
  43. if highscore_changed:
  44. print('HIGHSCORE changed: {0} nodes ({1}), {2} clients ({3})'.format(
  45. highscores['nodes'],
  46. highscores['nodes_ts'],
  47. highscores['clients'],
  48. highscores['clients_ts'],
  49. ))
  50. if not bot.config.ffpb.msg_target is None:
  51. action_msg = 'notiert sich den neuen Highscore: {0} Knoten ({1}), {2} Clients ({3})'
  52. action_target = bot.config.ffpb.msg_target
  53. if not bot.config.ffpb.msg_target_public is None:
  54. action_target = bot.config.ffpb.msg_target_public
  55. bot.msg(action_target, '\x01ACTION %s\x01' % action_msg.format(
  56. highscores['nodes'], pretty_date(int(highscores['nodes_ts'])),
  57. highscores['clients'], pretty_date(int(highscores['clients_ts'])),
  58. ))
  59. @willie.module.commands('status')
  60. def ffpb_status(bot, trigger):
  61. """State of the network: count of nodes + clients"""
  62. stats = bot.memory['ffpb_stats'] if 'ffpb_stats' in bot.memory else None
  63. if stats is None:
  64. bot.say('Uff, kein Plan wo der Zettel ist. Fragst du später nochmal?')
  65. return
  66. bot.say('Es sind {0} Knoten und ca. {1} Clients online.'.format(
  67. stats["nodes_active"], stats["clients"]))
  68. @willie.module.commands('batcave-status')
  69. def ffpb_batcave_status(bot, trigger):
  70. """State as given by BATCAVE."""
  71. status = json.loads(urllib2.urlopen('http://[fdca:ffee:ff12:a255::253]:8888/status').read())
  72. bot.say('Status: ' + str(json.dumps(status))[1:-1])
  73. @willie.module.commands('highscore')
  74. def ffpb_highscore(bot, trigger):
  75. """Print current highscores (nodes + clients)."""
  76. bot.say('Highscore: {0} Knoten ({1}), {2} Clients ({3})'.format(
  77. highscores['nodes'], pretty_date(int(highscores['nodes_ts'])),
  78. highscores['clients'], pretty_date(int(highscores['clients_ts']))))
  79. @willie.module.commands('rollout-status')
  80. def ffpb_rolloutstatus(bot, trigger):
  81. """Display statistic on how many nodes have installed the given firmware version."""
  82. # initialize results dictionary
  83. result = {}
  84. skipped = 0
  85. # inform users about changed command parameters
  86. if not trigger.group(2) is None:
  87. bot.reply('Dieses Kommando nimmt keinen Parameter mehr an.')
  88. return
  89. # get ALFRED data (and ensure it is current)
  90. alfred_data = get_alfred_data(bot, True)
  91. if alfred_data is None:
  92. bot.say('Ich habe irgendein Memo verpasst, sorry - bitte später nochmal fragen.')
  93. return
  94. # check each node in ALFRED data
  95. for nodeid in alfred_data:
  96. item = alfred_data[nodeid]
  97. if (not 'software' in item) or (not 'firmware' in item['software']) or (not 'autoupdater' in item['software']):
  98. skipped += 1
  99. continue
  100. release = item['software']['firmware']['release']
  101. branch = item['software']['autoupdater']['branch']
  102. enabled = item['software']['autoupdater']['enabled']
  103. if not release in result or result[release] is None:
  104. result[release] = {'stable': None, 'testing': None,}
  105. if not branch in result[release] or result[release][branch] is None:
  106. result[release][branch] = {'auto': 0, 'manual': 0, 'total': 0,}
  107. result[release][branch]['total'] += 1
  108. mode = 'auto' if enabled else 'manual'
  109. result[release][branch][mode] += 1
  110. # respond to user
  111. releases = sorted([x for x in result])
  112. for release in releases:
  113. output = 'Rollout von \'{0}\':'.format(release)
  114. branches = sorted([x for x in result[release]])
  115. first = True
  116. for branch in branches:
  117. item = result[release][branch]
  118. if item is None:
  119. continue
  120. if not first:
  121. output += ','
  122. first = False
  123. total = item['total']
  124. auto_count = item['auto']
  125. manual_count = item['manual']
  126. output += ' {2} {0}'.format(branch, total, auto_count, manual_count)
  127. if manual_count > 0:
  128. output += ' (+{3} manuell)'.format(branch, total, auto_count, manual_count)
  129. bot.say(output)
  130. # output count of nodes for which the autoupdater's branch and/or
  131. # firmware version could not be retrieved
  132. if skipped > 0:
  133. bot.say('plus {0} Knoten deren Status gerade nicht abfragbar war'.format(skipped))
  134. @willie.module.commands('providers')
  135. def ffpb_providers(bot, trigger):
  136. """Fetch the top 5 providers from BATCAVE."""
  137. providers = json.load(urllib2.urlopen('http://[fdca:ffee:ff12:a255::253]:8888/providers?format=json'))
  138. providers.sort(key=lambda x: x['count'], reverse=True)
  139. top5 = providers[:5]
  140. top5 = ['{0} ({1:.0f}%)'.format(x['name'], x['percentage']) for x in top5]
  141. bot.say('Unsere Top 5 Provider: ' + ', '.join(top5))