4
0

ffpb.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965
  1. # -*- coding: utf-8 -*-
  2. from __future__ import print_function
  3. import willie
  4. import datetime
  5. import difflib
  6. from email.utils import mktime_tz
  7. import git
  8. import netaddr
  9. import json
  10. import urllib2
  11. import re
  12. import os
  13. import random
  14. import shelve
  15. import subprocess
  16. import time
  17. import dns.resolver,dns.reversename
  18. import socket
  19. import SocketServer
  20. import threading
  21. msgserver = None
  22. peers_repo = None
  23. monitored_nodes = None
  24. highscores = None
  25. alfred_method = None
  26. alfred_data = None
  27. alfred_update = datetime.datetime(1970,1,1,23,42)
  28. ffpb_resolver = dns.resolver.Resolver ()
  29. ffpb_resolver.nameservers = ['10.132.254.53']
  30. class MsgHandler(SocketServer.BaseRequestHandler):
  31. """Reads line from TCP stream and forwards it to configured IRC channels."""
  32. def handle(self):
  33. data = self.request.recv(2048).strip()
  34. sender = self._resolve_name (self.client_address[0])
  35. bot = self.server.bot
  36. if bot is None:
  37. print("ERROR: No bot in handle() :-(")
  38. return
  39. target = bot.config.core.owner
  40. if bot.config.has_section('ffpb'):
  41. is_public = data.lstrip().lower().startswith("public:")
  42. if is_public and not (bot.config.ffpb.msg_target_public is None):
  43. data = data[7:].lstrip()
  44. target = bot.config.ffpb.msg_target_public
  45. elif not (bot.config.ffpb.msg_target is None):
  46. target = bot.config.ffpb.msg_target
  47. bot.msg(target, "[{0}] {1}".format(sender, str(data)))
  48. def _resolve_name (self, ip):
  49. """Resolves the host name of the given IP address
  50. and strips away the suffix (.infra)?.ffpb"""
  51. if ip.startswith ("127."):
  52. return "localhost"
  53. try:
  54. addr = dns.reversename.from_address (ip)
  55. return re.sub ("(.infra)?.ffpb.", "", str (ffpb_resolver.query (addr, "PTR")[0]))
  56. except dns.resolver.NXDOMAIN:
  57. return ip
  58. class ThreadingTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
  59. pass
  60. def setup(bot):
  61. global msgserver, peers_repo, alfred_method, highscores, monitored_nodes
  62. # signal begin of setup routine
  63. bot.memory['ffpb_in_setup'] = True
  64. # load highscores from disk
  65. highscores = shelve.open('highscoredata', writeback=True)
  66. if not 'nodes' in highscores:
  67. highscores['nodes'] = 0
  68. highscores['nodes_ts'] = time.time()
  69. if not 'clients' in highscores:
  70. highscores['clients'] = 0
  71. highscores['clients_ts'] = time.time()
  72. # load list of monitored nodes and their last status from disk
  73. monitored_nodes = shelve.open('nodes.monitored', writeback=True)
  74. # load list of seen nodes from disk
  75. seen_nodes = shelve.open('nodes.seen', writeback=True)
  76. bot.memory['seen_nodes'] = seen_nodes
  77. # no need to configure anything else if the ffpb config section is missing
  78. if not bot.config.has_section('ffpb'):
  79. bot.memory['ffpb_in_setup'] = False
  80. return
  81. # open the git repository containing the peers files
  82. if not bot.config.ffpb.peers_directory is None:
  83. peers_repo = git.Repo(bot.config.ffpb.peers_directory)
  84. assert peers_repo.bare == False
  85. # if configured, start the messaging server
  86. if int(bot.config.ffpb.msg_enable) == 1:
  87. host = "localhost"
  88. port = 2342
  89. if not bot.config.ffpb.msg_host is None: host = bot.config.ffpb.msg_host
  90. if not bot.config.ffpb.msg_port is None: port = int(bot.config.ffpb.msg_port)
  91. msgserver = ThreadingTCPServer((host,port), MsgHandler)
  92. msgserver.bot = bot
  93. ip, port = msgserver.server_address
  94. print("Messaging server listening on {}:{}".format(ip,port))
  95. msgserver_thread = threading.Thread(target=msgserver.serve_forever)
  96. msgserver_thread.daemon = True
  97. msgserver_thread.start()
  98. # initially fetch ALFRED data
  99. alfred_method = bot.config.ffpb.alfred_method
  100. ffpb_updatealfred(bot)
  101. # signal end of setup routine
  102. bot.memory['ffpb_in_setup'] = False
  103. def shutdown(bot):
  104. global msgserver, highscores, monitored_nodes
  105. # store highscores
  106. if not highscores is None:
  107. highscores.sync()
  108. highscores.close()
  109. highscores = None
  110. # store monitored nodes
  111. if not monitored_nodes is None:
  112. monitored_nodes.sync()
  113. monitored_nodes.close()
  114. monitored_nodes = None
  115. # store seen nodes
  116. if 'seen_nodes' in bot.memory and bot.memory['seen_nodes'] != None:
  117. bot.memory['seen_nodes'].close()
  118. bot.memory['seen_nodes'] = None
  119. del(bot.memory['seen_nodes'])
  120. # shutdown messaging server
  121. if not msgserver is None:
  122. msgserver.shutdown()
  123. print("Closed messaging server.")
  124. msgserver = None
  125. @willie.module.commands("help")
  126. @willie.module.commands("hilfe")
  127. @willie.module.commands("man")
  128. def ffpb_help(bot, trigger):
  129. """Display commony ulsed functions."""
  130. functions = {
  131. "!ping <knoten>": "Prüfe ob der Knoten erreichbar ist.",
  132. "!status": "Aktuellen Status des Netzwerks (insb. Anzahl Knoten und Clients) ausgegeben.",
  133. "!info <knoten>": "Allgemeine Information zu dem Knoten anzeigen.",
  134. "!link <knoten>": "MAC-Adresse und Link zur Status-Seite des Knotens anzeigen.",
  135. "!exec-on-peer <knoten> <kommando>": "Befehl auf dem Knoten ausführen (nur möglich bei eigenen Knoten oder als Admin, in beiden Fällen auch nur wenn der SSH-Key des Bots hinterlegt wurde)",
  136. "!mesh <knoten>": "Zeige Mesh-Partner eines Knotens",
  137. }
  138. param = trigger.group(2)
  139. if param is None:
  140. bot.say("Funktionen: " + str.join(", ", sorted(functions.keys())))
  141. return
  142. if param.startswith("!"): param = param[1:]
  143. for fun in functions.keys():
  144. if fun.startswith("!" + param + " "):
  145. bot.say("Hilfe zu '" + fun + "': " + functions[fun])
  146. return
  147. bot.say("Allgemeine Hilfe gibt's mit !help - ohne Parameter.")
  148. def ffpb_findnode(name):
  149. """helper: try to identify the node the user meant by the given name"""
  150. # no name, no node
  151. if name is None or len(name) == 0:
  152. return None
  153. name = str(name).strip()
  154. names = {}
  155. # try to match MAC
  156. m = re.search("^([0-9a-fA-F][0-9a-fA-F]:){5}[0-9a-fA-F][0-9a-fA-F]$", name)
  157. if (not m is None):
  158. mac = m.group(0).lower()
  159. if mac in alfred_data:
  160. return alfred_data[mac]
  161. # try to find alias MAC in ALFRED data
  162. for nodeid in alfred_data:
  163. node = alfred_data[nodeid]
  164. if "network" in node:
  165. if "mac" in node["network"] and node["network"]["mac"].lower() == mac:
  166. return node
  167. if "mesh_interfaces" in node["network"]:
  168. for mim in node["network"]["mesh_interfaces"]:
  169. if mim.lower() == mac:
  170. return node
  171. return {
  172. 'hostname': '?-' + mac.replace(':','').lower(),
  173. 'network': { 'addresses': [ mac2ipv6(mac, 'fdca:ffee:ff12:132:') ], 'mac': mac, },
  174. 'hardware': { 'model': 'derived-from-mac' },
  175. }
  176. # look through the ALFRED peers
  177. for nodeid in alfred_data:
  178. node = alfred_data[nodeid]
  179. if 'hostname' in node:
  180. h = node['hostname']
  181. if h.lower() == name.lower():
  182. return node
  183. else:
  184. names[h] = nodeid
  185. # not found in ALFRED data -> try peers_repo
  186. if not peers_repo is None:
  187. peer_name = None
  188. peer_mac = None
  189. peer_file = None
  190. for b in peers_repo.heads.master.commit.tree.blobs:
  191. if b.name.lower() == name.lower():
  192. peer_name = b.name
  193. peer_file = b.abspath
  194. break
  195. if (not peer_file is None) and os.path.exists(peer_file):
  196. peerfile = open(peer_file, "r")
  197. for line in peerfile:
  198. if line.startswith("# MAC:"):
  199. peer_mac = line[6:].strip()
  200. peerfile.close()
  201. if not (peer_mac is None):
  202. return {
  203. 'hostname': peer_name,
  204. 'network': { 'addresses': [ mac2ipv6(peer_mac, 'fdca:ffee:ff12:132:') ], 'mac': peer_mac },
  205. 'hardware': { 'model': 'derived-from-vpnkeys' },
  206. }
  207. # do a similar name lookup in the ALFRED data
  208. possibilities = difflib.get_close_matches(name, [ x for x in names ], cutoff=0.75)
  209. print('findnode: Fuzzy matching \'{0}\' got {1} entries: {2}'.format(name, len(possibilities), ', '.join(possibilities)))
  210. if len(possibilities) == 1:
  211. # if we got exactly one candidate that might be it
  212. return alfred_data[names[possibilities[0]]]
  213. # none of the above was able to identify the requested node
  214. return None
  215. def ffpb_findnode_from_botparam(bot, name, ensure_recent_alfreddata = True):
  216. """helper: call ffpb_findnode() and give common answers via bot if nothing has been found"""
  217. if (name is None or len(name) == 0):
  218. if not bot is None: bot.reply("Grün.")
  219. return None
  220. if ensure_recent_alfreddata and alfred_data is None:
  221. if not bot is None: bot.say("Informationen sind ausverkauft, kommen erst morgen wieder rein.")
  222. return None
  223. if ensure_recent_alfreddata and ffpb_alfred_data_outdated():
  224. if not bot is None: bot.say("Ich habe gerade keine aktuellen Informationen, daher sage ich mal lieber nichts zu '" + name + "'.")
  225. return None
  226. node = ffpb_findnode(name)
  227. if node is None:
  228. if not bot is None: bot.say("Kein Plan wer oder was mit '" + name + "' gemeint ist :(")
  229. return node
  230. def mac2ipv6(mac, prefix=None):
  231. """Calculate IPv6 address from given MAC,
  232. optionally replacing the fe80:: prefix with a given one."""
  233. result = str(netaddr.EUI(mac).ipv6_link_local())
  234. if (not prefix is None) and (result.startswith("fe80::")):
  235. result = prefix + result[6:]
  236. return result
  237. @willie.module.interval(30)
  238. def ffpb_updatealfred(bot):
  239. """Aktualisiere ALFRED-Daten"""
  240. global alfred_data, alfred_update
  241. if alfred_method is None or alfred_method == "None":
  242. return
  243. updated = None
  244. if alfred_method == "exec":
  245. rawdata = subprocess.check_output(['alfred-json', '-z', '-r', '158'])
  246. updated = datetime.datetime.now()
  247. elif alfred_method.startswith("http"):
  248. try:
  249. rawdata = urllib2.urlopen(alfred_method)
  250. except:
  251. print("Failed to download ALFRED data.")
  252. return
  253. updated = datetime.datetime.fromtimestamp(mktime_tz(rawdata.info().getdate_tz("Last-Modified")))
  254. else:
  255. print("Unknown ALFRED data method '", alfred_method, "', cannot load new data.", sep="")
  256. alfred_data = None
  257. return
  258. try:
  259. alfred_data = json.load(rawdata)
  260. #print("Fetched new ALFRED data:", len(alfred_data), "entries")
  261. alfred_update = updated
  262. except ValueError as e:
  263. print("Failed to parse ALFRED data: " + str(e))
  264. return
  265. seen_nodes = bot.memory['seen_nodes'] if 'seen_nodes' in bot.memory else None
  266. if not seen_nodes is None:
  267. new = []
  268. for nodeid in alfred_data:
  269. nodeid = str(nodeid)
  270. if not nodeid in seen_nodes:
  271. seen_nodes[nodeid] = updated
  272. new.append((nodeid,alfred_data[nodeid]['hostname']))
  273. print('First time seen: ' + str(nodeid))
  274. if len(new) > 0 and not bot.memory['ffpb_in_setup']:
  275. action_msg = None
  276. if len(new) == 1:
  277. action_msg = random.choice((
  278. 'bemerkt den neuen Knoten {0}',
  279. 'entdeckt {0}',
  280. 'reibt sich die Augen und erblickt einen verpackungsfrischen Knoten {0}',
  281. u'heißt {0} im Mesh willkommen',
  282. 'freut sich, dass {0} aufgetaucht ist',
  283. 'traut seinen Augen kaum. {0} sagt zum ersten Mal: Hallo Freifunk Paderborn',
  284. u'sieht die ersten Herzschläge von {0}',
  285. u'stellt einen großen Pott Heißgetränk zu {0} und fragt ob es hier Meshpartner gibt.',
  286. )).format('\'' + str(new[0][1]) + '\'')
  287. else:
  288. action_msg = random.choice((
  289. 'bemerkt die neuen Knoten {0} und {1}',
  290. 'hat {0} und {1} entdeckt',
  291. 'bewundert {0} sowie {1}',
  292. 'freut sich, dass {0} und {1} nun auch online sind',
  293. u'heißt {0} und {1} im Mesh willkommen',
  294. 'fragt sich ob die noch jungen Herzen von {0} und {1} synchron schlagen',
  295. )).format('\'' + '\', \''.join([ str(x[1]) for x in new[0:-1] ]) + '\'', '\'' + str(new[-1][1]) + '\'')
  296. action_target = bot.config.ffpb.msg_target
  297. bot.msg(action_target, '\x01ACTION %s\x01' % action_msg)
  298. def ffpb_alfred_data_outdated():
  299. timeout = datetime.datetime.now() - datetime.timedelta(minutes=5)
  300. is_outdated = timeout > alfred_update
  301. #print("ALFRED outdated? {0} (timeout={1} vs. lastupdate={2})".format(is_outdated, timeout, alfred_update))
  302. return is_outdated
  303. @willie.module.commands('debug-alfred')
  304. def ffpb_debug_alfred(bot, trigger):
  305. """Show statistics of available ALFRED data."""
  306. if alfred_data is None:
  307. bot.say("Keine ALFRED-Daten vorhanden.")
  308. else:
  309. bot.say("ALFRED Daten: count={0} lastupdate={1}".format(len(alfred_data), alfred_update))
  310. @willie.module.commands('alfred-data')
  311. def ffpb_peerdata(bot, trigger):
  312. """Show ALFRED data of the given node."""
  313. # user must be a bot admin
  314. if (not trigger.admin):
  315. bot.say('I wont leak (possibly) sensitive data to you.')
  316. return
  317. # query must be a PM or as OP in the channel
  318. if (not trigger.is_privmsg) and (not trigger.nick in bot.ops[trigger.sender]):
  319. bot.say('Kein Keks? Keine Daten.')
  320. return
  321. # identify node or bail out
  322. target_name = trigger.group(2)
  323. node = ffpb_findnode_from_botparam(bot, target_name)
  324. if node is None: return
  325. # reply each key in the node's data
  326. for key in node:
  327. if key in [ 'hostname' ]: continue
  328. bot.say("{0}.{1} = {2}".format(node['hostname'], key, str(node[key])))
  329. @willie.module.commands('info')
  330. def ffpb_peerinfo(bot, trigger):
  331. """Show information of the given node."""
  332. # identify node or bail out
  333. target_name = trigger.group(2)
  334. node = ffpb_findnode_from_botparam(bot, target_name)
  335. if node is None: return
  336. # read node information
  337. info_mac = node["network"]["mac"]
  338. info_name = node["hostname"]
  339. info_hw = ""
  340. if "hardware" in node:
  341. if "model" in node["hardware"]:
  342. model = node["hardware"]["model"]
  343. info_hw = " model='" + model + "'"
  344. info_fw = ""
  345. info_update = ""
  346. if "software" in node:
  347. if "firmware" in node["software"]:
  348. fwinfo = str(node["software"]["firmware"]["release"]) if "release" in node["software"]["firmware"] else "unknown"
  349. info_fw = " firmware=" + fwinfo
  350. if "autoupdater" in node["software"]:
  351. autoupdater = node["software"]["autoupdater"]["branch"] if node["software"]["autoupdater"]["enabled"] else "off"
  352. info_update = " (autoupdater="+autoupdater+")"
  353. info_uptime = ""
  354. u = -1
  355. if "statistics" in node and "uptime" in node["statistics"]:
  356. u = int(float(node["statistics"]["uptime"]))
  357. elif 'uptime' in node:
  358. u = int(float(node['uptime']))
  359. if u > 0:
  360. d, r1 = divmod(u, 86400)
  361. h, r2 = divmod(r1, 3600)
  362. m, s = divmod(r2, 60)
  363. if d > 0:
  364. info_uptime = ' up {0}d {1}h'.format(d,h)
  365. elif h > 0:
  366. info_uptime = ' up {0}h {1}m'.format(h,m)
  367. else:
  368. info_uptime = ' up {0}m'.format(m)
  369. bot.say('[{1}]{2}{3}{4}{5}'.format(info_mac, info_name, info_hw, info_fw, info_update, info_uptime))
  370. @willie.module.commands('uptime')
  371. def ffpb_peeruptime(bot, trigger):
  372. """Display the uptime of the given node."""
  373. # identify node or bail out
  374. target_name = trigger.group(2)
  375. node = ffpb_findnode_from_botparam(bot, target_name)
  376. if node is None: return
  377. # get name and raw uptime from node
  378. info_name = node["hostname"]
  379. info_uptime = ''
  380. u_raw = None
  381. if 'statistics' in node and 'uptime' in node['statistics']:
  382. u_raw = node['statistics']['uptime']
  383. elif 'uptime' in node:
  384. u_raw = node['uptime']
  385. # pretty print uptime
  386. if not u_raw is None:
  387. u = int(float(u_raw))
  388. d, r1 = divmod(u, 86400)
  389. h, r2 = divmod(r1, 3600)
  390. m, s = divmod(r2, 60)
  391. if d > 0:
  392. info_uptime += '{0}d '.format(d)
  393. if h > 0:
  394. info_uptime += '{0}h '.format(h)
  395. info_uptime += '{0}m'.format(m)
  396. info_uptime += ' # raw: \'{0}\''.format(u_raw)
  397. else:
  398. info_uptime += '?'
  399. # reply to user
  400. bot.say('uptime(\'{0}\') = {1}'.format(info_name, info_uptime))
  401. @willie.module.commands('link')
  402. def ffpb_peerlink(bot, trigger):
  403. """Display MAC and link to statuspage for the given node."""
  404. # identify node or bail out
  405. target_name = trigger.group(2)
  406. node = ffpb_findnode_from_botparam(bot, target_name)
  407. if node is None: return
  408. # get node's MAC
  409. info_mac = node["network"]["mac"]
  410. info_name = node["hostname"]
  411. # get node's v6 address in the mesh (derived from MAC address)
  412. info_v6 = mac2ipv6(info_mac, 'fdca:ffee:ff12:132:')
  413. # reply to user
  414. bot.say('[{1}] mac {0} -> http://[{2}]/'.format(info_mac, info_name, info_v6))
  415. @willie.module.interval(60)
  416. def ffpb_updatepeers(bot):
  417. """Refresh list of peers and message the diff."""
  418. if peers_repo is None:
  419. print('WARNING: peers_repo is None')
  420. return
  421. old_head = peers_repo.head.commit
  422. peers_repo.remotes.origin.pull()
  423. new_head = peers_repo.head.commit
  424. if new_head != old_head:
  425. print('git pull: from ' + str(old_head) + ' to ' + str(new_head))
  426. added = []
  427. changed = []
  428. renamed = []
  429. deleted = []
  430. for f in old_head.diff(new_head):
  431. if f.new_file:
  432. added.append(f.b_blob.name)
  433. elif f.deleted_file:
  434. deleted.append(f.a_blob.name)
  435. elif f.renamed:
  436. renamed.append([f.rename_from, f.rename_to])
  437. else:
  438. changed.append(f.a_blob.name)
  439. response = "Knoten-Update (VPN +{0} %{1} -{2}): ".format(len(added), len(renamed)+len(changed), len(deleted))
  440. for f in added:
  441. response += " +'{}'".format(f)
  442. for f in changed:
  443. response += " %'{}'".format(f)
  444. for f in renamed:
  445. response += " '{}'->'{}'".format(f[0],f[1])
  446. for f in deleted:
  447. response += " -'{}'".format(f)
  448. bot.msg(bot.config.ffpb.msg_target, response)
  449. def ffpb_fetch_stats(bot, url, memoryid):
  450. """Fetch a ffmap-style nodes.json from the given URL and
  451. store it in the bot's memory."""
  452. response = urllib2.urlopen(url)
  453. data = json.load(response)
  454. nodes_active = 0
  455. nodes_total = 0
  456. clients_count = 0
  457. for node in data['nodes']:
  458. if node['flags']['gateway'] or node['flags']['client']:
  459. continue
  460. nodes_total += 1
  461. if node['flags']['online']:
  462. nodes_active += 1
  463. if 'legacy' in node['flags'] and node['flags']['legacy']:
  464. clients_count -= 1
  465. for link in data['links']:
  466. if link['type'] == 'client':
  467. clients_count += 1
  468. if not memoryid in bot.memory:
  469. bot.memory[memoryid] = { }
  470. stats = bot.memory[memoryid]
  471. stats["fetchtime"] = time.time()
  472. stats["nodes_active"] = nodes_active
  473. stats["nodes_total"] = nodes_total
  474. stats["clients"] = clients_count
  475. return (nodes_active, nodes_total, clients_count)
  476. @willie.module.interval(15)
  477. def ffpb_get_stats(bot):
  478. """Fetch current statistics, if the highscore changes signal this."""
  479. (nodes_active, nodes_total, clients_count) = ffpb_fetch_stats(bot, 'http://map.paderborn.freifunk.net/nodes.json', 'ffpb_stats')
  480. highscore_changed = False
  481. if nodes_active > highscores['nodes']:
  482. highscores['nodes'] = nodes_active
  483. highscores['nodes_ts'] = time.time()
  484. highscore_changed = True
  485. if clients_count > highscores['clients']:
  486. highscores['clients'] = clients_count
  487. highscores['clients_ts'] = time.time()
  488. highscore_changed = True
  489. if highscore_changed:
  490. print('HIGHSCORE changed: {0} nodes ({1}), {2} clients ({3})'.format(highscores['nodes'], highscores['nodes_ts'], highscores['clients'], highscores['clients_ts']))
  491. if not (bot.config.ffpb.msg_target is None):
  492. action_msg = 'notiert sich den neuen Highscore: {0} Knoten ({1}), {2} Clients ({3})'.format(highscores['nodes'], pretty_date(int(highscores['nodes_ts'])), highscores['clients'], pretty_date(int(highscores['clients_ts'])))
  493. action_target = bot.config.ffpb.msg_target
  494. if (not bot.config.ffpb.msg_target_public is None):
  495. action_target = bot.config.ffpb.msg_target_public
  496. bot.msg(action_target, '\x01ACTION %s\x01' % action_msg)
  497. @willie.module.commands('status')
  498. def ffpb_status(bot, trigger):
  499. """State of the network: count of nodes + clients"""
  500. stats = bot.memory['ffpb_stats'] if 'ffpb_stats' in bot.memory else None
  501. if stats is None:
  502. bot.say('Uff, kein Plan wo der Zettel ist. Fragst du später nochmal?')
  503. return
  504. bot.say('Es sind {0} Knoten und ca. {1} Clients online.'.format(stats["nodes_active"], stats["clients"]))
  505. def pretty_date(time=False):
  506. """
  507. Get a datetime object or a int() Epoch timestamp and return a
  508. pretty string like 'an hour ago', 'Yesterday', '3 months ago',
  509. 'just now', etc
  510. """
  511. from datetime import datetime
  512. now = datetime.now()
  513. compare = None
  514. if type(time) is int:
  515. compare = datetime.fromtimestamp(time)
  516. elif type(time) is float:
  517. compare = datetime.fromtimestamp(int(time))
  518. elif isinstance(time,datetime):
  519. compare = time
  520. elif not time:
  521. compare = now
  522. diff = now - compare
  523. second_diff = diff.seconds
  524. day_diff = diff.days
  525. if day_diff < 0:
  526. return ''
  527. if day_diff == 0:
  528. if second_diff < 10:
  529. return "gerade eben"
  530. if second_diff < 60:
  531. return "vor " + str(second_diff) + " Sekunden"
  532. if second_diff < 120:
  533. return "vor einer Minute"
  534. if second_diff < 3600:
  535. return "vor " + str(second_diff / 60) + " Minuten"
  536. if second_diff < 7200:
  537. return "vor einer Stunde"
  538. if second_diff < 86400:
  539. return "vor " + str(second_diff / 3600) + " Stunden"
  540. if day_diff == 1:
  541. return "gestern"
  542. if day_diff < 7:
  543. return "vor " + str(day_diff) + " Tagen"
  544. return "am " + compare.strftime('%d.%m.%Y um %H:%M Uhr')
  545. @willie.module.commands('highscore')
  546. def ffpb_highscore(bot, trigger):
  547. bot.say('Highscore: {0} Knoten ({1}), {2} Clients ({3})'.format(
  548. highscores['nodes'], pretty_date(int(highscores['nodes_ts'])),
  549. highscores['clients'], pretty_date(int(highscores['clients_ts']))))
  550. @willie.module.commands('rollout-status')
  551. def ffpb_rolloutstatus(bot, trigger):
  552. """Display statistic on how many nodes have installed the given firmware version."""
  553. # initialize results dictionary
  554. result = { }
  555. for branch in [ 'stable', 'testing' ]:
  556. result[branch] = None
  557. skipped = 0
  558. # command is restricted to bot-admins via PM or OPS in the channel
  559. if (not (trigger.admin and trigger.is_privmsg)) and (not trigger.nick in bot.ops[trigger.sender]):
  560. bot.say('Geh zur dunklen Seite, die haben Kekse - ohne Keks kein Rollout-Status.')
  561. return
  562. # read expected firmware version from command arguments
  563. expected_release = trigger.group(2)
  564. if expected_release is None or len(expected_release) == 0:
  565. bot.say('Von welcher Firmware denn?')
  566. return
  567. # check each node in ALFRED data
  568. for nodeid in alfred_data:
  569. item = alfred_data[nodeid]
  570. if (not 'software' in item) or (not 'firmware' in item['software']) or (not 'autoupdater' in item['software']):
  571. skipped+=1
  572. continue
  573. release = item['software']['firmware']['release']
  574. branch = item['software']['autoupdater']['branch']
  575. enabled = item['software']['autoupdater']['enabled']
  576. if not branch in result or result[branch] is None:
  577. result[branch] = { 'auto_count': 0, 'auto_not': 0, 'manual_count': 0, 'manual_not': 0, 'total': 0 }
  578. result[branch]['total'] += 1
  579. match = 'count' if release == expected_release else 'not'
  580. mode = 'auto' if enabled else 'manual'
  581. result[branch][mode+'_'+match] += 1
  582. # respond to user
  583. output = "Rollout von '{0}':".format(expected_release)
  584. for branch in result:
  585. auto_count = result[branch]['auto_count']
  586. auto_total = auto_count + result[branch]['auto_not']
  587. manual_count = result[branch]['manual_count']
  588. manual_total = manual_count + result[branch]['manual_not']
  589. bot.say("Rollout von '{0}': {1} = {2}/{3} per Auto-Update, {4}/{5} manuell".format(expected_release, branch, auto_count, auto_total, manual_count, manual_total))
  590. # output count of nodes for which the autoupdater's branch and/or
  591. # firmware version could not be retrieved
  592. if skipped > 0:
  593. bot.say("Rollout von '{0}': {1} Knoten unklar".format(expected_release, skipped))
  594. @willie.module.commands('ping')
  595. def ffpb_ping(bot, trigger=None, target_name=None):
  596. """Ping the given node"""
  597. # identify node or bail out
  598. if target_name is None: target_name = trigger.group(2)
  599. node = ffpb_findnode_from_botparam(bot, target_name, ensure_recent_alfreddata=False)
  600. if node is None: return None
  601. # get the first non-linklocal address from the node
  602. target = [x for x in node["network"]["addresses"] if not x.lower().startswith("fe80:")][0]
  603. target_alias = node["hostname"]
  604. # execute the actual ping and reply the result
  605. print("pinging '{0}' at {1} ...".format(target_name, target))
  606. result = os.system('ping6 -c 2 -W 1 ' + target + ' >/dev/null')
  607. if result == 0:
  608. print("ping to '{0}' succeeded".format(target_name))
  609. if not bot is None: bot.say('Knoten "' + target_alias + '" antwortet \o/')
  610. return True
  611. elif result == 1 or result == 256:
  612. print("ping to '{0}' failed".format(target_name))
  613. if not bot is None: bot.say('Keine Antwort von "' + target_alias + '" :-(')
  614. return False
  615. else:
  616. print("ping to '{0}' broken: result='{1}'".format(target_name, result))
  617. if not bot is None: bot.say('Uh oh, irgendwas ist kaputt. Chef, ping result = ' + str(result) + ' - darf ich das essen?')
  618. return None
  619. @willie.module.interval(3*60)
  620. def ffpb_monitor_ping(bot):
  621. """Ping each node currently under surveillance."""
  622. # determine where-to to send alerts
  623. notify_target = bot.config.core.owner
  624. if (not bot.config.ffpb.msg_target is None):
  625. notify_target = bot.config.ffpb.msg_target
  626. # check each node under surveillance
  627. for node in monitored_nodes:
  628. mon = monitored_nodes[node]
  629. added = mon['added']
  630. last_status = mon['status']
  631. last_check = mon['last_check']
  632. last_success = mon['last_success']
  633. current_status = ffpb_ping(bot=None, target_name=node)
  634. if current_status is None: current_status = False
  635. mon['status'] = current_status
  636. mon['last_check'] = time.time()
  637. if current_status == True: mon['last_success'] = time.time()
  638. print("Monitoring ({0}) {1} (last: {2} at {3})".format(node, current_status, last_status, time.strftime('%Y-%m-%d %H:%M', time.localtime(last_check))))
  639. if last_status != current_status and (last_status or current_status):
  640. if last_check is None:
  641. # erster Check, keine Ausgabe
  642. continue
  643. if current_status == True:
  644. bot.msg(notify_target, 'Monitoring: Knoten \'{0}\' pingt wieder (zuletzt {1})'.format(node, pretty_date(last_success) if not last_success is None else '[nie]'))
  645. else:
  646. bot.msg(notify_target, 'Monitoring: Knoten \'{0}\' DOWN'.format(node))
  647. @willie.module.commands('monitor')
  648. def ffpb_monitor(bot, trigger):
  649. """Monitoring capability of the bot, try subcommands add, del, info and list."""
  650. # command is restricted to bot admins
  651. if not trigger.admin:
  652. bot.say('Ich ping hier nicht für jeden durch die Weltgeschichte.')
  653. return
  654. # ensure the user gave arguments (group 2 is the concatenation of all following groups)
  655. if trigger.group(2) is None or len(trigger.group(2)) == 0:
  656. bot.say('Das Monitoring sagt du hast doofe Ohren.')
  657. return
  658. # read additional arguments
  659. cmd = trigger.group(3)
  660. node = trigger.group(4)
  661. if not node is None: node = str(node)
  662. # subcommand 'add': add a node to monitoring
  663. if cmd == "add":
  664. if node in monitored_nodes:
  665. bot.say('Knoten \'{0}\' wird bereits gemonitored.'.format(node))
  666. return
  667. monitored_nodes[node] = {
  668. 'added': trigger.sender,
  669. 'status': None,
  670. 'last_check': None,
  671. 'last_success': None,
  672. }
  673. bot.say('Knoten \'{0}\' wird jetzt ganz genau beobachtet.'.format(node))
  674. return
  675. # subcommand 'del': remote a node from monitoring
  676. if cmd == "del":
  677. if not node in monitored_nodes:
  678. bot.say('Knoten \'{0}\' war gar nicht im Monitoring?!?'.format(node))
  679. return
  680. del monitored_nodes[node]
  681. bot.say('Okidoki, \'{0}\' lasse ich jetzt links liegen.'.format(node))
  682. return
  683. # subcommand 'info': monitoring status of a node
  684. if cmd == "info":
  685. if node in monitored_nodes:
  686. info = monitored_nodes[node]
  687. bot.say('Knoten \'{0}\' wurde zuletzt {1} gepingt (Ergebnis: {2})'.format(node, pretty_date(info['last_check']) if not info['last_check'] is None else "^W noch nie", info['status']))
  688. else:
  689. bot.say('Knoten \'{0}\' ist nicht im Monitoring.'.format(node))
  690. return
  691. # subcommand 'list': enumerate all monitored nodes
  692. if cmd == "list":
  693. nodes = ""
  694. for node in monitored_nodes:
  695. nodes = nodes + " " + node
  696. bot.say('Monitoring aktiv für:' + nodes)
  697. return
  698. # subcommand 'help': give some hints what the user can do
  699. if cmd == "help":
  700. bot.say('Entweder "!monitor list" oder "!monitor {add|del|info} <node>"')
  701. return
  702. # no valid subcommand given: complain
  703. bot.say('Mit "' + str(cmd) + '" kann ich nix anfangen, probier doch mal "!monitor help".')
  704. @willie.module.commands('providers')
  705. def ffpb_providers(bot, trigger):
  706. """Fetch the top 5 providers from BATCAVE."""
  707. providers = json.load(urllib2.urlopen('http://[fdca:ffee:ff12:a255::253]:8888/providers?format=json'))
  708. providers.sort(key=lambda x: x['count'], reverse=True)
  709. bot.say('Unsere Top 5 Provider: ' + ', '.join(['{0} ({1:.0f}%)'.format(x['name'], x['percentage']) for x in providers[:5]]))
  710. @willie.module.commands('mesh')
  711. def ffpb_nodemesh(bot, trigger):
  712. """Display mesh partners of the given node."""
  713. # identify node or bail out
  714. target_name = trigger.group(2)
  715. node = ffpb_findnode_from_botparam(bot, target_name, ensure_recent_alfreddata=False)
  716. if node is None: return None
  717. # derive node's id
  718. nodeid = node['node_id'] if 'node_id' in node else None
  719. if nodeid is None: nodeid = node['network']['mac'].replace(':','') if 'network' in node and 'mac' in node['network'] else None
  720. if nodeid is None:
  721. bot.say('Mist, ich habe gerade den Zettel verlegt auf dem die Node-ID von \'{0}\' steht, bitte frag später noch einmal.'.format(node['hostname'] if 'hostname' in node else target_name))
  722. return
  723. # query BATCAVE for node's neighbours (result is a list of MAC addresses)
  724. cave_result = json.load(urllib2.urlopen('http://[fdca:ffee:ff12:a255::253]:8888/node/{0}/neighbours'.format(nodeid)))
  725. # query BATCAVE for neighbour's names
  726. d = '&'.join([ str(n) for n in cave_result ])
  727. req = urllib2.urlopen('http://[fdca:ffee:ff12:a255::253]:8888/idmac2name', d)
  728. # filter out duplicate names
  729. neighbours = set()
  730. for n in req:
  731. ident,name = n.strip().split('=')
  732. neighbours.add(name)
  733. neighbours = [ x for x in neighbours ]
  734. # respond to the user
  735. if len(neighbours) == 0:
  736. bot.say(u'{0} hat keinen Mesh-Partner *schnüff*'.format(node['hostname']))
  737. elif len(neighbours) == 1:
  738. bot.say(u'{0} mesht mit \'{1}\''.format(node['hostname'], neighbours[0]))
  739. else:
  740. bot.say('{0} mesht mit \'{1}\' und \'{2}\''.format(node['hostname'], '\', \''.join(neighbours[:-1]), neighbours[-1]))
  741. @willie.module.commands('exec-on-peer')
  742. def ffpb_remoteexec(bot, trigger):
  743. """Remote execution on the given node"""
  744. bot_params = trigger.group(2).split(' ',1)
  745. if len(bot_params) != 2:
  746. bot.say('Wenn du nicht sagst wo mach ich remote execution bei dir!')
  747. bot.say('Tipp: !exec-on-peer <peer> <cmd>')
  748. return
  749. target_name = bot_params[0]
  750. target_cmd = bot_params[1]
  751. # remote execution may only be triggered by bot admins
  752. if not trigger.admin:
  753. bot.say('I can haz sudo?')
  754. return
  755. # make sure remote execution is done in public
  756. if trigger.is_privmsg:
  757. bot.say('Bitte per Channel.')
  758. return
  759. # double-safety: user must be op in the channel, too (hoping for NickServ authentication)
  760. if not trigger.nick in bot.ops[trigger.sender]:
  761. bot.say('Geh weg.')
  762. return
  763. # identify requested node or bail out
  764. node = ffpb_findnode_from_botparam(bot, target_name, ensure_recent_alfreddata=False)
  765. if node is None: return
  766. # use the node's first non-linklocal address
  767. target = [x for x in node["network"]["addresses"] if not x.lower().startswith("fe80:")][0]
  768. target_alias = node["hostname"]
  769. # assemble SSH command
  770. cmd = 'ssh -6 -l root ' + target + ' -- "' + target_cmd + '"'
  771. print("REMOTE EXEC = " + cmd)
  772. try:
  773. # call SSH
  774. result = subprocess.check_output(['ssh', '-6n', '-l', 'root', '-o', 'BatchMode=yes', '-o','StrictHostKeyChecking=no', target, target_cmd], stderr=subprocess.STDOUT, shell=False)
  775. # fetch results and sent at most 8 of them as response
  776. lines = str(result).splitlines()
  777. if len(lines) == 0:
  778. bot.say('exec-on-peer(' + target_alias + '): No output')
  779. return
  780. msg = 'exec-on-peer(' + target_alias + '): ' + str(len(lines)) + ' Zeilen'
  781. if len(lines) > 8:
  782. msg += ' (zeige max. 8)'
  783. bot.say(msg + ':')
  784. for line in lines[0:8]:
  785. bot.say(line)
  786. except subprocess.CalledProcessError as e:
  787. bot.say('Fehler '+str(e.returncode)+' bei exec-on-peer('+target_alias+'): ' + e.output)