__init__.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. from copy import deepcopy
  4. import json
  5. import logging
  6. import time
  7. import urllib2
  8. from .alfred import AlfredParser
  9. from .batman import BatmanParser
  10. from .dashing import DashingClient
  11. from .graphite import GraphitePush
  12. from .server import ApiServer
  13. from .filestorage import FileStorage
  14. from .redisstorage import RedisStorage
  15. __all__ = [
  16. 'AlfredParser', 'BatmanParser',
  17. 'DashingClient', 'GraphitePush',
  18. 'FileStorage', 'ApiServer',
  19. 'RedisStorage',
  20. 'dict_merge', 'merge_alfred_batman',
  21. 'resolve_ipblock', 'mac2id',
  22. ]
  23. logger = logging.getLogger('ffstatus')
  24. def mac2id(mac):
  25. return mac.lower().replace(':', '')
  26. def dict_merge(a, b, overwrite_lists=True):
  27. '''recursively merges dict's. not just simple a['key'] = b['key'], if
  28. both a and bhave a key who's value is a dict then dict_merge is called
  29. on both values and the result stored in the returned dictionary.'''
  30. if not isinstance(b, dict):
  31. return b
  32. result = deepcopy(a)
  33. for k, v in b.iteritems():
  34. if k in result:
  35. if isinstance(result[k], dict):
  36. result[k] = dict_merge(result[k], v)
  37. continue
  38. if isinstance(result[k], list):
  39. if overwrite_lists:
  40. result[k] = [deepcopy(x) for x in v]
  41. else:
  42. result[k] = [deepcopy(x) for x in v if x not in result[k]]
  43. continue
  44. result[k] = deepcopy(v)
  45. return result
  46. def merge_alfred_batman(alfreddata, batmandata):
  47. merged = {}
  48. # lookup dict to map MACs to node ids
  49. batlookup = {}
  50. # list of (yet un-)handled BATMAN nodes
  51. unhandled_batnodes = set()
  52. # fill above variables from BATMAN data
  53. for nodeid in batmandata:
  54. batlookup[nodeid] = nodeid
  55. unhandled_batnodes.add(str(nodeid))
  56. for bda in batmandata[nodeid]['aliases']:
  57. batlookup[bda] = nodeid
  58. # iterate over ALFRED data
  59. for nodeid in alfreddata:
  60. nodeinfo = dict_merge({}, alfreddata[nodeid])
  61. candidates = set()
  62. candidates.add(nodeid)
  63. if 'mac' in nodeinfo:
  64. candidates.add(mac2id(nodeinfo['mac']))
  65. if 'macs' in nodeinfo:
  66. for mac in nodeinfo['macs']:
  67. candidates.add(mac2id(mac))
  68. if 'network' in nodeinfo:
  69. net = nodeinfo['network']
  70. if 'mac' in net:
  71. candidates.add(mac2id(net['mac']))
  72. if 'mesh_interfaces' in net:
  73. for mac in net['mesh_interfaces']:
  74. candidates.add(mac2id(mac))
  75. if not 'neighbours' in nodeinfo:
  76. nodeinfo['neighbours'] = {}
  77. for candidate_raw in candidates:
  78. candidate = batlookup.get(candidate_raw, candidate_raw)
  79. if candidate in batmandata:
  80. nodeinfo = dict_merge(nodeinfo, batmandata[candidate])
  81. if candidate in unhandled_batnodes:
  82. unhandled_batnodes.remove(str(candidate))
  83. merged[nodeid] = nodeinfo
  84. # handle BATMAN nodes which aren't in ALFRED
  85. for nodeid in unhandled_batnodes:
  86. logger.debug("unhandled BATMAN node '%s'", nodeid)
  87. nodeinfo = dict_merge({}, batmandata[nodeid])
  88. if not 'node_id' in nodeinfo:
  89. nodeinfo['node_id'] = nodeid
  90. merged[nodeid] = nodeinfo
  91. return merged
  92. no_ipblock_resolves_until = None
  93. def resolve_ipblock(ipaddr):
  94. """Resolve the given IP address to its inetnum entry at RIPE."""
  95. global no_ipblock_resolves_until
  96. if no_ipblock_resolves_until is not None:
  97. if no_ipblock_resolves_until < time.time():
  98. no_ipblock_resolves_until = None
  99. else:
  100. logger.info('IP-Block-Resolving suspended for %d seconds. ' +
  101. 'Won\'t resolve \'%s\' now.',
  102. int(no_ipblock_resolves_until-time.time()), ipaddr)
  103. return None
  104. url = 'http://rest.db.ripe.net/search.json?query-string=' + str(ipaddr)
  105. try:
  106. response = json.load(urllib2.urlopen(url))
  107. assert isinstance(response, dict)
  108. obj = [x for x in response['objects']['object'] if x['type'] in ['inetnum', 'inet6num']][0]
  109. attrib = obj['attributes']['attribute']
  110. netname = '\n'.join([x['value'] for x in attrib if x['name'] == 'netname'])
  111. netblock = '\n'.join([x['value'] for x in attrib if x['name'] in ['inetnum', 'inet6num']])
  112. desc = '\n'.join([x['value'] for x in attrib if x['name'] == 'descr'])
  113. return {
  114. 'name': netname,
  115. 'block': netblock,
  116. 'description': desc,
  117. }
  118. except urllib2.URLError as err:
  119. output = err.read()
  120. logger.error('Error "%s" querying ip \'%s\' from RIPE API: %s',
  121. err, ipaddr, output)
  122. if 'Retry-After' in err.headers:
  123. retry = int(err.headers['Retry-After'])
  124. logger.warn(
  125. 'I won\'t resolve IPs for %d seconds as requested by RIPE API' +
  126. ' (header=\'%s\').',
  127. retry, err.header['Retry-After'])
  128. no_ipblock_resolves_until = \
  129. time.time() + int(err.headers['Retry-After'])
  130. else:
  131. logger.warn('I won\'t resolve IPs for the next hour ' +
  132. '(API didn\'t give better hint).')
  133. no_ipblock_resolves_until = time.time() + 3600