batman.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. from __future__ import print_function
  4. import io
  5. import json
  6. import string
  7. import subprocess
  8. import time
  9. import ffstatus
  10. from .exceptions import SanityCheckError
  11. class BatmanParser:
  12. batadv_vis = 'batadv-vis'
  13. mactranslation = string.maketrans('2367abef', '014589cd')
  14. def __str__(self):
  15. return 'BatmanParser \'{0}\''.format(self.batadv_vis)
  16. def sanitycheck(self):
  17. """Checks that batadv-vis is executable and gives sane output."""
  18. testdata = None
  19. try:
  20. cmd = [self.batadv_vis, '-f', 'jsondoc']
  21. testdata = subprocess.check_output(cmd)
  22. except Exception as err:
  23. raise SanityCheckError(
  24. self, "batadv-vis not found or incompatible", err)
  25. try:
  26. json.loads(testdata)
  27. except Exception as err:
  28. raise SanityCheckError(
  29. self, "batadv-vis does not return valid JSON data", err)
  30. return True
  31. def fetch(self):
  32. """Fetches the current data from batadv-vis."""
  33. data = {}
  34. timestamp = int(time.time())
  35. # call batadv-vis and parse output as unicode JSON
  36. rawdata = subprocess.check_output([self.batadv_vis, '-f', 'jsondoc'])
  37. rawdata = unicode(rawdata, encoding='latin1', errors='replace')
  38. batmandata = json.loads(rawdata)
  39. # parse raw data, convert all MAC into nodeid
  40. for item in batmandata['vis']:
  41. itemid = ffstatus.mac2id(item['primary'])
  42. aliases = []
  43. if 'secondary' in item:
  44. for mac in item['secondary']:
  45. aliases.append(ffstatus.mac2id(mac))
  46. neighbours = {}
  47. if 'neighbors' in item:
  48. for neighbour in item['neighbors']:
  49. #if neighbour['router'] != item['primary']:
  50. # print('node {0}\'s neighbor {1} has unexpected router {2}'.format(itemid, neighbour['neighbor'], neighbour['router']))
  51. metric = float(neighbour['metric'])
  52. neighbours[neighbour['neighbor']] = metric
  53. # construct dict entry as expected by BATCAVE
  54. data[itemid] = {
  55. 'aliases': aliases,
  56. 'neighbours': neighbours,
  57. 'clients': [x for x in item.get('clients', [])],
  58. '__UPDATED__': {'batadv': timestamp},
  59. '__RAW__': {'batadv': {itemid: item}},
  60. }
  61. return data
  62. # standalone test mode
  63. if __name__ == "__main__":
  64. parser = BatmanParser()
  65. try:
  66. parser.sanitycheck()
  67. except SanityCheckError as err:
  68. print('SANITY-CHECK failed:', str(err))
  69. import sys
  70. sys.exit(1)
  71. bdata = parser.fetch()
  72. print(json.dumps(bdata))