batman.py 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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, batadv_dump=None):
  32. """Fetches the current data from batadv-vis."""
  33. data = {}
  34. timestamp = int(time.time())
  35. # call batadv-vis and parse output as JSON
  36. rawdata = subprocess.check_output([self.batadv_vis, '-f', 'jsondoc'])
  37. batmandata = json.loads(rawdata)
  38. # dump raw data into file if requested
  39. if batadv_dump is not None:
  40. dumpfile = io.open(batadv_dump, 'w')
  41. dumpfile.write(rawdata)
  42. dumpfile.close()
  43. # parse raw data, convert all MAC into nodeid
  44. for item in batmandata['vis']:
  45. itemid = ffstatus.mac2id(item['primary'])
  46. aliases = []
  47. if 'secondary' in item:
  48. for mac in item['secondary']:
  49. aliases.append(ffstatus.mac2id(mac))
  50. neighbours = {}
  51. if 'neighbors' in item:
  52. for neighbour in item['neighbors']:
  53. #if neighbour['router'] != item['primary']:
  54. # print('node {0}\'s neighbor {1} has unexpected router {2}'.format(itemid, neighbour['neighbor'], neighbour['router']))
  55. metric = float(neighbour['metric'])
  56. neighbours[neighbour['neighbor']] = metric
  57. # construct dict entry as expected by BATCAVE
  58. data[itemid] = {
  59. 'aliases': aliases,
  60. 'neighbours': neighbours,
  61. 'clients': [x for x in item.get('clients', [])],
  62. '__UPDATED__': {'batadv': timestamp},
  63. '__RAW__': {'batadv': {itemid: item}},
  64. }
  65. return data
  66. # standalone test mode
  67. if __name__ == "__main__":
  68. parser = BatmanParser()
  69. try:
  70. parser.sanitycheck()
  71. except SanityCheckError as err:
  72. print('SANITY-CHECK failed:', str(err))
  73. import sys
  74. sys.exit(1)
  75. bdata = parser.fetch()
  76. print(json.dumps(bdata))