alfred.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. from __future__ import print_function
  4. import io
  5. import json
  6. import subprocess
  7. import time
  8. from .exceptions import SanityCheckError
  9. class AlfredParser:
  10. alfred_json = 'alfred-json'
  11. alfred_datatypes = [('static', 158), ('dynamic', 159)]
  12. def __str__(self):
  13. types = ['{1}=>{0}'.format(x[0], x[1]) for x in self.alfred_datatypes]
  14. return 'AlfredParser \'{0}\' {1}'.format(
  15. self.alfred_json,
  16. str.join(' ', types),
  17. )
  18. def sanitycheck(self):
  19. """
  20. Checks that the necessary tool 'alfred-json' is callable
  21. and outputs syntactically correct JSON data.
  22. """
  23. testdata = None
  24. try:
  25. first_datatype = int(self.alfred_datatypes[0][1])
  26. cmd = [self.alfred_json, '-z', '-r', str(first_datatype)]
  27. testdata = subprocess.check_output(cmd)
  28. except Exception as err:
  29. raise SanityCheckError(
  30. self, "alfred-json not found or incompatible", err)
  31. try:
  32. json.loads(testdata)
  33. except Exception as err:
  34. raise SanityCheckError(
  35. self, "alfred-json does not return valid JSON data", err)
  36. return True
  37. def fetch(self, alfred_dump=None):
  38. """Fetches the current data from alfred-json."""
  39. data = {}
  40. timestamp = int(time.time())
  41. alfreddata = {}
  42. for datatype in self.alfred_datatypes:
  43. cmd = [self.alfred_json, '-z', '-r', str(int(datatype[1]))]
  44. rawdata = subprocess.check_output(cmd)
  45. newdata = json.loads(rawdata)
  46. for item in newdata:
  47. if not item in alfreddata:
  48. alfreddata[item] = {}
  49. alfreddata[item][datatype[0]] = newdata[item]
  50. if alfred_dump is not None:
  51. jsondata = json.dumps(alfreddata, ensure_ascii=False)
  52. dumpfile = io.open(alfred_dump, 'w')
  53. dumpfile.write(jsondata)
  54. dumpfile.close()
  55. for alfredid in alfreddata:
  56. alfredinfo = alfreddata[alfredid]
  57. if 'node_id' in alfredinfo['static']:
  58. myid = alfredinfo['static']['node_id']
  59. else:
  60. alfredid.lower().replace(':', '')
  61. nodeinfo = {
  62. 'hostname': None,
  63. 'mac': None,
  64. 'software': {},
  65. 'statistics': {},
  66. '__UPDATED__': {'alfred': timestamp},
  67. '__RAW__': {'alfred': alfredinfo},
  68. }
  69. data[myid] = nodeinfo
  70. nodestatic = alfredinfo['static']
  71. if 'hostname' in nodestatic:
  72. nodeinfo['hostname'] = nodestatic['hostname']
  73. if 'network' in nodestatic:
  74. if 'mac' in nodestatic['network']:
  75. nodeinfo['mac'] = nodestatic['network']['mac']
  76. if 'mesh_interfaces' in nodestatic['network']:
  77. macs = [x for x in nodestatic['network']['mesh_interfaces']]
  78. nodeinfo['macs'] = macs
  79. else:
  80. nodeinfo['macs'] = []
  81. if 'software' in nodestatic:
  82. software = nodestatic['software']
  83. nodeinfo['software']['firmware'] = \
  84. software.get('firmware', {}).get('release')
  85. autoupdater = software.get('autoupdater', {})
  86. autoupdater_enabled = autoupdater.get('enabled', False)
  87. nodeinfo['software']['autoupdater'] = \
  88. autoupdater.get('branch') if autoupdater_enabled else 'off'
  89. nodedyn = alfredinfo.get('dynamic',
  90. nodestatic.get('statistics', {}))
  91. if 'uptime' in nodedyn:
  92. nodeinfo['uptime'] = int(float(nodedyn['uptime']))
  93. if 'gateway' in nodedyn:
  94. nodeinfo['gateway'] = nodedyn['gateway']
  95. traffic = nodedyn["traffic"] if "traffic" in nodedyn else None
  96. if traffic is not None:
  97. if not 'traffic' in nodeinfo['statistics']:
  98. nodeinfo['statistics']['traffic'] = {}
  99. item = nodeinfo['statistics']['traffic']
  100. item['rxbytes'] = int(traffic["rx"]["bytes"])
  101. item['txbytes'] = int(traffic["tx"]["bytes"])
  102. return data
  103. if __name__ == "__main__":
  104. parser = AlfredParser()
  105. try:
  106. parser.sanitycheck()
  107. except SanityCheckError as err:
  108. print('SANITY-CHECK failed:', str(err))
  109. import sys
  110. sys.exit(1)
  111. adata = parser.fetch()
  112. print(json.dumps(adata))