ffpb.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747
  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 shelve
  14. import subprocess
  15. import time
  16. import dns.resolver,dns.reversename
  17. import socket
  18. import SocketServer
  19. import threading
  20. msgserver = None
  21. peers_repo = None
  22. monitored_nodes = None
  23. highscores = None
  24. alfred_method = None
  25. alfred_data = None
  26. alfred_update = datetime.datetime(1970,1,1,23,42)
  27. ffpb_resolver = dns.resolver.Resolver ()
  28. ffpb_resolver.nameservers = ['10.132.254.53']
  29. class MsgHandler(SocketServer.BaseRequestHandler):
  30. def handle(self):
  31. data = self.request.recv(2048).strip()
  32. sender = self._resolve_name (self.client_address[0])
  33. bot = self.server.bot
  34. if bot is None:
  35. print("ERROR: No bot in handle() :-(")
  36. return
  37. target = bot.config.core.owner
  38. if bot.config.has_section('ffpb'):
  39. is_public = data.lstrip().lower().startswith("public:")
  40. if is_public and not (bot.config.ffpb.msg_target_public is None):
  41. data = data[7:].lstrip()
  42. target = bot.config.ffpb.msg_target_public
  43. elif not (bot.config.ffpb.msg_target is None):
  44. target = bot.config.ffpb.msg_target
  45. bot.msg(target, "[{0}] {1}".format(sender, str(data)))
  46. def _resolve_name (self, ip):
  47. if ip.startswith ("127."):
  48. return "localhost"
  49. try:
  50. addr = dns.reversename.from_address (ip)
  51. return re.sub ("(.infra)?.ffpb.", "", str (ffpb_resolver.query (addr, "PTR")[0]))
  52. except dns.resolver.NXDOMAIN:
  53. return ip
  54. class ThreadingTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
  55. pass
  56. def setup(bot):
  57. global msgserver, peers_repo, alfred_method, highscores, monitored_nodes
  58. highscores = shelve.open('highscoredata', writeback=True)
  59. if not 'nodes' in highscores:
  60. highscores['nodes'] = 0
  61. highscores['nodes_ts'] = time.time()
  62. if not 'clients' in highscores:
  63. highscores['clients'] = 0
  64. highscores['clients_ts'] = time.time()
  65. monitored_nodes = shelve.open('monitorednodes', writeback=True)
  66. if not bot.config.has_section('ffpb'):
  67. return
  68. if not bot.config.ffpb.peers_directory is None:
  69. peers_repo = git.Repo(bot.config.ffpb.peers_directory)
  70. assert peers_repo.bare == False
  71. if int(bot.config.ffpb.msg_enable) == 1:
  72. host = "localhost"
  73. port = 2342
  74. if not bot.config.ffpb.msg_host is None: host = bot.config.ffpb.msg_host
  75. if not bot.config.ffpb.msg_port is None: port = int(bot.config.ffpb.msg_port)
  76. msgserver = ThreadingTCPServer((host,port), MsgHandler)
  77. msgserver.bot = bot
  78. ip, port = msgserver.server_address
  79. print("Messaging server listening on {}:{}".format(ip,port))
  80. msgserver_thread = threading.Thread(target=msgserver.serve_forever)
  81. msgserver_thread.daemon = True
  82. msgserver_thread.start()
  83. alfred_method = bot.config.ffpb.alfred_method
  84. ffpb_updatealfred(bot)
  85. def shutdown(bot):
  86. global msgserver, highscores, monitored_nodes
  87. if not highscores is None:
  88. highscores.sync()
  89. highscores.close()
  90. highscores = None
  91. if not monitored_nodes is None:
  92. monitored_nodes.sync()
  93. monitored_nodes.close()
  94. monitored_nodes = None
  95. if not msgserver is None:
  96. msgserver.shutdown()
  97. print("Closed messaging server.")
  98. msgserver = None
  99. @willie.module.commands("help")
  100. @willie.module.commands("hilfe")
  101. @willie.module.commands("man")
  102. def ffpb_help(bot, trigger):
  103. functions = {
  104. "!ping <knoten>": "Prüfe ob der Knoten erreichbar ist.",
  105. "!status": "Aktuellen Status des Netzwerks (insb. Anzahl Knoten und Clients) ausgegeben.",
  106. "!info <knoten>": "Allgemeine Information zu dem Knoten anzeigen.",
  107. "!link <knoten>": "MAC-Adresse und Link zur Status-Seite des Knotens anzeigen.",
  108. "!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)",
  109. }
  110. param = trigger.group(2)
  111. if param is None:
  112. bot.say("Funktionen: " + str.join(", ", sorted(functions.keys())))
  113. return
  114. if param.startswith("!"): param = param[1:]
  115. for fun in functions.keys():
  116. if fun.startswith("!" + param + " "):
  117. bot.say("Hilfe zu '" + fun + "': " + functions[fun])
  118. return
  119. bot.say("Allgemeine Hilfe gibt's mit !help - ohne Parameter.")
  120. def ffpb_findnode(name):
  121. if name is None or len(name) == 0:
  122. return None
  123. name = str(name).strip()
  124. names = {}
  125. # try to match MAC
  126. m = re.search("^([0-9a-fA-F][0-9a-fA-F]:){5}[0-9a-fA-F][0-9a-fA-F]$", name)
  127. if (not m is None):
  128. mac = m.group(0).lower()
  129. if mac in alfred_data:
  130. return alfred_data[mac]
  131. # try to find alias MAC
  132. for nodeid in alfred_data:
  133. node = alfred_data[nodeid]
  134. if "network" in node:
  135. if "mac" in node["network"] and node["network"]["mac"].lower() == mac:
  136. return node
  137. if "mesh_interfaces" in node["network"]:
  138. for mim in node["network"]["mesh_interfaces"]:
  139. if mim.lower() == mac:
  140. return node
  141. # look through the ALFRED peers
  142. for nodeid in alfred_data:
  143. node = alfred_data[nodeid]
  144. if 'hostname' in node:
  145. h = node['hostname']
  146. if h.lower() == name.lower():
  147. return node
  148. else:
  149. names[h] = nodeid
  150. # still not found -> try peers_repo
  151. if not peers_repo is None:
  152. peer_name = None
  153. peer_mac = None
  154. peer_file = None
  155. for b in peers_repo.heads.master.commit.tree.blobs:
  156. if b.name.lower() == name.lower():
  157. peer_name = b.name
  158. peer_file = b.abspath
  159. break
  160. if (not peer_file is None) and os.path.exists(peer_file):
  161. peerfile = open(peer_file, "r")
  162. for line in peerfile:
  163. if line.startswith("# MAC:"):
  164. peer_mac = line[6:].strip()
  165. peerfile.close()
  166. if not (peer_mac is None):
  167. return { "hostname": peer_name, "network": { "addresses": [ mac2ipv6(peer_mac, "fdca:ffee:ff12:132:") ], "mac": peer_mac } }
  168. # do a similar name lookup in the ALFRED data
  169. possibilities = difflib.get_close_matches(name, [ x for x in names ], cutoff=0.8)
  170. print('findnode: Fuzzy matching \'{0}\' got {1} entries: {2}'.format(name, len(possibilities), ', '.join(possibilities)))
  171. if len(possibilities) == 1:
  172. # if we got exactly one candidate that might be it
  173. return alfred_data[names[possibilities[0]]]
  174. return None
  175. def ffpb_findnode_from_botparam(bot, name, ensure_recent_alfreddata = True):
  176. if (name is None or len(name) == 0):
  177. bot.reply("Grün.")
  178. return None
  179. if ensure_recent_alfreddata and alfred_data is None:
  180. bot.say("Informationen sind ausverkauft, kommen erst morgen wieder rein.")
  181. return None
  182. if ensure_recent_alfreddata and ffpb_alfred_data_outdated():
  183. bot.say("Ich habe gerade keine aktuellen Informationen, daher sage ich mal lieber nichts zu '" + name + "'.")
  184. return None
  185. node = ffpb_findnode(name)
  186. if node is None:
  187. bot.say("Kein Plan wer oder was mit '" + name + "' gemeint ist :(")
  188. return node
  189. def mac2ipv6(mac, prefix=None):
  190. result = str(netaddr.EUI(mac).ipv6_link_local())
  191. if (not prefix is None) and (result.startswith("fe80::")):
  192. result = prefix + result[6:]
  193. return result
  194. @willie.module.interval(30)
  195. def ffpb_updatealfred(bot):
  196. """Aktualisiere ALFRED-Daten"""
  197. global alfred_data, alfred_update
  198. if alfred_method is None or alfred_method == "None":
  199. return
  200. updated = None
  201. if alfred_method == "exec":
  202. rawdata = subprocess.check_output(['alfred-json', '-z', '-r', '158'])
  203. updated = datetime.datetime.now()
  204. elif alfred_method.startswith("http"):
  205. try:
  206. rawdata = urllib2.urlopen(alfred_method)
  207. except:
  208. print("Failed to download ALFRED data.")
  209. return
  210. updated = datetime.datetime.fromtimestamp(mktime_tz(rawdata.info().getdate_tz("Last-Modified")))
  211. else:
  212. print("Unknown ALFRED data method '", alfred_method, "', cannot load new data.", sep="")
  213. alfred_data = None
  214. return
  215. try:
  216. alfred_data = json.load(rawdata)
  217. #print("Fetched new ALFRED data:", len(alfred_data), "entries")
  218. alfred_update = updated
  219. except ValueError as e:
  220. print("Failed to parse ALFRED data: " + str(e))
  221. return
  222. def ffpb_alfred_data_outdated():
  223. timeout = datetime.datetime.now() - datetime.timedelta(minutes=5)
  224. is_outdated = timeout > alfred_update
  225. #print("ALFRED outdated? {0} (timeout={1} vs. lastupdate={2})".format(is_outdated, timeout, alfred_update))
  226. return is_outdated
  227. @willie.module.commands('debug-alfred')
  228. def ffpb_debug_alfred(bot, trigger):
  229. if alfred_data is None:
  230. bot.say("Keine ALFRED-Daten vorhanden.")
  231. else:
  232. bot.say("ALFRED Daten: count={0} lastupdate={1}".format(len(alfred_data), alfred_update))
  233. @willie.module.commands('alfred-data')
  234. def ffpb_peerdata(bot, trigger):
  235. if (not trigger.admin):
  236. bot.say('I wont leak (possibly) sensitive data to you.')
  237. return
  238. if (not trigger.is_privmsg) and (not trigger.nick in bot.ops[trigger.sender]):
  239. bot.say('Kein Keks? Keine Daten.')
  240. return
  241. target_name = trigger.group(2)
  242. node = ffpb_findnode_from_botparam(bot, target_name)
  243. if node is None: return
  244. for key in node:
  245. if key in [ 'hostname' ]: continue
  246. bot.say("{0}.{1} = {2}".format(node['hostname'], key, str(node[key])))
  247. @willie.module.commands('info')
  248. def ffpb_peerinfo(bot, trigger):
  249. target_name = trigger.group(2)
  250. node = ffpb_findnode_from_botparam(bot, target_name)
  251. if node is None: return
  252. info_mac = node["network"]["mac"]
  253. info_name = node["hostname"]
  254. info_hw = ""
  255. if "hardware" in node:
  256. if "model" in node["hardware"]:
  257. model = node["hardware"]["model"]
  258. info_hw = " model='" + model + "'"
  259. info_fw = ""
  260. info_update = ""
  261. if "software" in node:
  262. if "firmware" in node["software"]:
  263. fwinfo = str(node["software"]["firmware"]["release"]) if "release" in node["software"]["firmware"] else "unknown"
  264. info_fw = " firmware=" + fwinfo
  265. if "autoupdater" in node["software"]:
  266. autoupdater = node["software"]["autoupdater"]["branch"] if node["software"]["autoupdater"]["enabled"] else "off"
  267. info_update = " (autoupdater="+autoupdater+")"
  268. info_uptime = ""
  269. u = -1
  270. if "statistics" in node and "uptime" in node["statistics"]:
  271. u = int(float(node["statistics"]["uptime"]))
  272. elif 'uptime' in node:
  273. u = int(float(node['uptime']))
  274. if u > 0:
  275. d, r1 = divmod(u, 86400)
  276. h, r2 = divmod(r1, 3600)
  277. m, s = divmod(r2, 60)
  278. if d > 0:
  279. info_uptime = ' up {0}d {1}h'.format(d,h)
  280. elif h > 0:
  281. info_uptime = ' up {0}h {1}m'.format(h,m)
  282. else:
  283. info_uptime = ' up {0}m'.format(m)
  284. bot.say('[{1}]{2}{3}{4}{5}'.format(info_mac, info_name, info_hw, info_fw, info_update, info_uptime))
  285. @willie.module.commands('uptime')
  286. def ffpb_peeruptime(bot, trigger):
  287. target_name = trigger.group(2)
  288. node = ffpb_findnode_from_botparam(bot, target_name)
  289. if node is None: return
  290. info_name = node["hostname"]
  291. info_uptime = ''
  292. u_raw = None
  293. if 'statistics' in node and 'uptime' in node['statistics']:
  294. u_raw = node['statistics']['uptime']
  295. elif 'uptime' in node:
  296. u_raw = node['uptime']
  297. if not u_raw is None:
  298. u = int(float(u_raw))
  299. d, r1 = divmod(u, 86400)
  300. h, r2 = divmod(r1, 3600)
  301. m, s = divmod(r2, 60)
  302. if d > 0:
  303. info_uptime += '{0}d '.format(d)
  304. if h > 0:
  305. info_uptime += '{0}h '.format(h)
  306. info_uptime += '{0}m'.format(m)
  307. info_uptime += ' # raw: \'{0}\''.format(u_raw)
  308. else:
  309. info_uptime += '?'
  310. bot.say('uptime(\'{0}\') = {1}'.format(info_name, info_uptime))
  311. @willie.module.commands('link')
  312. def ffpb_peerlink(bot, trigger):
  313. target_name = trigger.group(2)
  314. node = ffpb_findnode_from_botparam(bot, target_name)
  315. if node is None: return
  316. info_mac = node["network"]["mac"]
  317. info_name = node["hostname"]
  318. info_v6 = mac2ipv6(info_mac, 'fdca:ffee:ff12:132:')
  319. bot.say('[{1}] mac {0} -> http://[{2}]/'.format(info_mac, info_name, info_v6))
  320. @willie.module.interval(60)
  321. def ffpb_updatepeers(bot):
  322. """Aktualisiere die Knotenliste und melde das Diff"""
  323. if peers_repo is None:
  324. print('WARNING: peers_repo is None')
  325. return
  326. old_head = peers_repo.head.commit
  327. peers_repo.remotes.origin.pull()
  328. new_head = peers_repo.head.commit
  329. if new_head != old_head:
  330. print('git pull: from ' + str(old_head) + ' to ' + str(new_head))
  331. added = []
  332. changed = []
  333. renamed = []
  334. deleted = []
  335. for f in old_head.diff(new_head):
  336. if f.new_file:
  337. added.append(f.b_blob.name)
  338. elif f.deleted_file:
  339. deleted.append(f.a_blob.name)
  340. elif f.renamed:
  341. renamed.append([f.rename_from, f.rename_to])
  342. else:
  343. changed.append(f.a_blob.name)
  344. response = "Knoten-Update (VPN +{0} %{1} -{2}): ".format(len(added), len(renamed)+len(changed), len(deleted))
  345. for f in added:
  346. response += " +'{}'".format(f)
  347. for f in changed:
  348. response += " %'{}'".format(f)
  349. for f in renamed:
  350. response += " '{}'->'{}'".format(f[0],f[1])
  351. for f in deleted:
  352. response += " -'{}'".format(f)
  353. bot.msg(bot.config.ffpb.msg_target, response)
  354. def ffpb_fetch_stats(bot, url, memoryid):
  355. response = urllib2.urlopen(url)
  356. data = json.load(response)
  357. nodes_active = 0
  358. nodes_total = 0
  359. clients_count = 0
  360. for node in data['nodes']:
  361. if node['flags']['gateway'] or node['flags']['client']:
  362. continue
  363. nodes_total += 1
  364. if node['flags']['online']:
  365. nodes_active += 1
  366. if 'legacy' in node['flags'] and node['flags']['legacy']:
  367. clients_count -= 1
  368. for link in data['links']:
  369. if link['type'] == 'client':
  370. clients_count += 1
  371. if not memoryid in bot.memory:
  372. bot.memory[memoryid] = { }
  373. stats = bot.memory[memoryid]
  374. stats["fetchtime"] = time.time()
  375. stats["nodes_active"] = nodes_active
  376. stats["nodes_total"] = nodes_total
  377. stats["clients"] = clients_count
  378. return (nodes_active, nodes_total, clients_count)
  379. @willie.module.interval(15)
  380. def ffpb_get_stats(bot):
  381. (nodes_active, nodes_total, clients_count) = ffpb_fetch_stats(bot, 'http://map.paderborn.freifunk.net/nodes.json', 'ffpb_stats')
  382. highscore_changed = False
  383. if nodes_active > highscores['nodes']:
  384. highscores['nodes'] = nodes_active
  385. highscores['nodes_ts'] = time.time()
  386. highscore_changed = True
  387. if clients_count > highscores['clients']:
  388. highscores['clients'] = clients_count
  389. highscores['clients_ts'] = time.time()
  390. highscore_changed = True
  391. if highscore_changed:
  392. print('HIGHSCORE changed: {0} nodes ({1}), {2} clients ({3})'.format(highscores['nodes'], highscores['nodes_ts'], highscores['clients'], highscores['clients_ts']))
  393. if not (bot.config.ffpb.msg_target is None):
  394. 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'])))
  395. action_target = bot.config.ffpb.msg_target
  396. if (not bot.config.ffpb.msg_target_public is None):
  397. action_target = bot.config.ffpb.msg_target_public
  398. bot.msg(action_target, '\x01ACTION %s\x01' % action_msg)
  399. @willie.module.commands('status')
  400. def ffpb_status(bot, trigger):
  401. """Status des FFPB-Netzes: Anzahl (aktiver) Knoten + Clients"""
  402. stats = bot.memory['ffpb_stats'] if 'ffpb_stats' in bot.memory else None
  403. if stats is None:
  404. bot.say('Uff, kein Plan wo der Zettel ist. Fragst du später nochmal?')
  405. return
  406. bot.say('Es sind {0} Knoten und ca. {1} Clients online.'.format(stats["nodes_active"], stats["clients"]))
  407. def pretty_date(time=False):
  408. """
  409. Get a datetime object or a int() Epoch timestamp and return a
  410. pretty string like 'an hour ago', 'Yesterday', '3 months ago',
  411. 'just now', etc
  412. """
  413. from datetime import datetime
  414. now = datetime.now()
  415. compare = None
  416. if type(time) is int:
  417. compare = datetime.fromtimestamp(time)
  418. elif type(time) is float:
  419. compare = datetime.fromtimestamp(int(time))
  420. elif isinstance(time,datetime):
  421. compare = time
  422. elif not time:
  423. compare = now
  424. diff = now - compare
  425. second_diff = diff.seconds
  426. day_diff = diff.days
  427. if day_diff < 0:
  428. return ''
  429. if day_diff == 0:
  430. if second_diff < 10:
  431. return "gerade eben"
  432. if second_diff < 60:
  433. return "vor " + str(second_diff) + " Sekunden"
  434. if second_diff < 120:
  435. return "vor einer Minute"
  436. if second_diff < 3600:
  437. return "vor " + str(second_diff / 60) + " Minuten"
  438. if second_diff < 7200:
  439. return "vor einer Stunde"
  440. if second_diff < 86400:
  441. return "vor " + str(second_diff / 3600) + " Stunden"
  442. if day_diff == 1:
  443. return "gestern"
  444. if day_diff < 7:
  445. return "vor " + str(day_diff) + " Tagen"
  446. return "am " + compare.strftime('%d.%m.%Y um %H:%M Uhr')
  447. @willie.module.commands('highscore')
  448. def ffpb_highscore(bot, trigger):
  449. bot.say('Highscore: {0} Knoten ({1}), {2} Clients ({3})'.format(
  450. highscores['nodes'], pretty_date(int(highscores['nodes_ts'])),
  451. highscores['clients'], pretty_date(int(highscores['clients_ts']))))
  452. @willie.module.commands('rollout-status')
  453. def ffpb_rolloutstatus(bot, trigger):
  454. result = { }
  455. for branch in [ 'stable', 'testing' ]:
  456. result[branch] = None
  457. skipped = 0
  458. if (not (trigger.admin and trigger.is_privmsg)) and (not trigger.nick in bot.ops[trigger.sender]):
  459. bot.say('Geh zur dunklen Seite, die haben Kekse - ohne Keks kein Rollout-Status.')
  460. return
  461. expected_release = trigger.group(2)
  462. if expected_release is None or len(expected_release) == 0:
  463. bot.say('Von welcher Firmware denn?')
  464. return
  465. for nodeid in alfred_data:
  466. item = alfred_data[nodeid]
  467. if (not 'software' in item) or (not 'firmware' in item['software']) or (not 'autoupdater' in item['software']):
  468. skipped+=1
  469. continue
  470. release = item['software']['firmware']['release']
  471. branch = item['software']['autoupdater']['branch']
  472. enabled = item['software']['autoupdater']['enabled']
  473. if not branch in result or result[branch] is None:
  474. result[branch] = { 'auto_count': 0, 'auto_not': 0, 'manual_count': 0, 'manual_not': 0, 'total': 0 }
  475. result[branch]['total'] += 1
  476. match = 'count' if release == expected_release else 'not'
  477. mode = 'auto' if enabled else 'manual'
  478. result[branch][mode+'_'+match] += 1
  479. output = "Rollout von '{0}':".format(expected_release)
  480. for branch in result:
  481. auto_count = result[branch]['auto_count']
  482. auto_total = auto_count + result[branch]['auto_not']
  483. manual_count = result[branch]['manual_count']
  484. manual_total = manual_count + result[branch]['manual_not']
  485. 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))
  486. if skipped > 0:
  487. bot.say("Rollout von '{0}': {1} Knoten unklar".format(expected_release, skipped))
  488. @willie.module.commands('ping')
  489. def ffpb_ping(bot, trigger=None, target_name=None):
  490. """Ping FFPB-Knoten"""
  491. if target_name is None: target_name = trigger.group(2)
  492. node = ffpb_findnode_from_botparam(bot, target_name, ensure_recent_alfreddata=False)
  493. if node is None: return None
  494. target = [x for x in node["network"]["addresses"] if not x.lower().startswith("fe80:")][0]
  495. target_alias = node["hostname"]
  496. print("pinging '{0}' at {1} ...".format(target_name, target))
  497. result = os.system('ping6 -c 2 -W 1 ' + target + ' >/dev/null')
  498. if result == 0:
  499. print("ping to '{0}' succeeded".format(target_name))
  500. if not bot is None: bot.say('Knoten "' + target_alias + '" antwortet \o/')
  501. return True
  502. elif result == 1 or result == 256:
  503. print("ping to '{0}' failed".format(target_name))
  504. if not bot is None: bot.say('Keine Antwort von "' + target_alias + '" :-(')
  505. return False
  506. else:
  507. print("ping to '{0}' broken: result='{1}'".format(target_name, result))
  508. if not bot is None: bot.say('Uh oh, irgendwas ist kaputt. Chef, ping result = ' + str(result) + ' - darf ich das essen?')
  509. return None
  510. @willie.module.interval(3*60)
  511. def ffpb_monitor_ping(bot):
  512. notify_target = bot.config.core.owner
  513. if (not bot.config.ffpb.msg_target is None):
  514. notify_target = bot.config.ffpb.msg_target
  515. for node in monitored_nodes:
  516. added = monitored_nodes[node][0]
  517. last_status = monitored_nodes[node][1]
  518. last_check = monitored_nodes[node][2]
  519. current_status = ffpb_ping(bot=None, target_name=node)
  520. monitored_nodes[node] = ( added, current_status, time.time() )
  521. 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))))
  522. if last_status != current_status and (last_status or current_status):
  523. if last_check is None:
  524. # erster Check, keine Ausgabe
  525. continue
  526. if current_status == True:
  527. bot.msg(notify_target, 'Monitoring: Knoten \'{0}\' pingt wieder (zuletzt {1})'.format(node, pretty_date(last_check)))
  528. else:
  529. bot.msg(notify_target, 'Monitoring: Knoten \'{0}\' DOWN'.format(node))
  530. @willie.module.commands('monitor')
  531. def ffpb_monitor(bot, trigger):
  532. if not trigger.admin:
  533. bot.say('Ich ping hier nicht für jeden durch die Weltgeschichte.')
  534. return
  535. if trigger.group(2) is None or len(trigger.group(2)) == 0:
  536. bot.say('Das Monitoring sagt du hast doofe Ohren.')
  537. return
  538. cmd = trigger.group(3)
  539. node = trigger.group(4)
  540. if not node is None: node = str(node)
  541. if cmd == "add":
  542. if node in monitored_nodes:
  543. bot.say('Knoten \'{0}\' wird bereits gemonitored.'.format(node))
  544. return
  545. monitored_nodes[node] = ( trigger.sender, None, None )
  546. bot.say('Knoten \'{0}\' wird jetzt ganz genau beobachtet.'.format(node))
  547. return
  548. if cmd == "del":
  549. if not node in monitored_nodes:
  550. bot.say('Knoten \'{0}\' war gar nicht im Monitoring?!?'.format(node))
  551. return
  552. del monitored_nodes[node]
  553. bot.say('Okidoki, \'{0}\' war mir sowieso egal.'.format(node))
  554. return
  555. if cmd == "info":
  556. if node in monitored_nodes:
  557. info = monitored_nodes[node]
  558. bot.say('Knoten \'{0}\' wurde zuletzt {1} gepingt (Ergebnis: {2}) - der Auftrag kam von {3}'.format(node, pretty_date(info[2]) if not info[2] is None else "^W noch nie", info[1], info[0]))
  559. else:
  560. bot.say('Knoten \'{0}\' ist nicht im Monitoring.'.format(node))
  561. return
  562. if cmd == "list":
  563. nodes = ""
  564. for node in monitored_nodes:
  565. nodes = nodes + " " + node
  566. bot.say('Monitoring aktiv für:' + nodes)
  567. return
  568. if cmd == "help":
  569. bot.say('Entweder "!monitor list" oder "!monitor {add|del|info} <node>"')
  570. return
  571. bot.say('Mit "' + str(cmd) + '" kann ich nix anfangen, probier doch mal "!monitor help".')
  572. @willie.module.commands('exec-on-peer')
  573. def ffpb_remoteexec(bot, trigger):
  574. """Remote Execution fuer FFPB_Knoten"""
  575. bot_params = trigger.group(2).split(' ',1)
  576. if len(bot_params) != 2:
  577. bot.say('Wenn du nicht sagst wo mach ich remote execution bei dir!')
  578. bot.say('Tipp: !exec-on-peer <peer> <cmd>')
  579. return
  580. target_name = bot_params[0]
  581. target_cmd = bot_params[1]
  582. if not trigger.admin:
  583. bot.say('I can haz sudo?')
  584. return
  585. if trigger.is_privmsg:
  586. bot.say('Bitte per Channel.')
  587. return
  588. if not trigger.nick in bot.ops[trigger.sender]:
  589. bot.say('Geh weg.')
  590. return
  591. node = ffpb_findnode_from_botparam(bot, target_name, ensure_recent_alfreddata=False)
  592. if node is None: return
  593. target = [x for x in node["network"]["addresses"] if not x.lower().startswith("fe80:")][0]
  594. target_alias = node["hostname"]
  595. cmd = 'ssh -6 -l root ' + target + ' -- "' + target_cmd + '"'
  596. print("REMOTE EXEC = " + cmd)
  597. try:
  598. result = subprocess.check_output(['ssh', '-6n', '-l', 'root', '-o', 'BatchMode=yes', '-o','StrictHostKeyChecking=no', target, target_cmd], stderr=subprocess.STDOUT, shell=False)
  599. lines = str(result).splitlines()
  600. if len(lines) == 0:
  601. bot.say('exec-on-peer(' + target_alias + '): No output')
  602. return
  603. msg = 'exec-on-peer(' + target_alias + '): ' + str(len(lines)) + ' Zeilen'
  604. if len(lines) > 8:
  605. msg += ' (zeige max. 8)'
  606. bot.say(msg + ':')
  607. for line in lines[0:8]:
  608. bot.say(line)
  609. except subprocess.CalledProcessError as e:
  610. bot.say('Fehler '+str(e.returncode)+' bei exec-on-peer('+target_alias+'): ' + e.output)