basestorage.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. from __future__ import print_function, unicode_literals
  4. import logging
  5. import re
  6. import time
  7. import ffstatus
  8. from .exceptions import VpnKeyFormatError
  9. def sanitize_node(data, include_raw_data=False):
  10. """
  11. Filters potentially harmful entries from the node's data.
  12. """
  13. export = ffstatus.dict_merge({}, data)
  14. # remove fields from output: __RAW__
  15. if '__RAW__' in export and not include_raw_data:
  16. del export['__RAW__']
  17. return export
  18. class BaseStorage(object):
  19. """
  20. Provides operations on the storage data.
  21. This class gets subclassed to actually write the data
  22. to a file, database, whatever.
  23. """
  24. DATAKEY_VPN = '__VPN__'
  25. FIELDKEY_UPDATED = '__UPDATED__'
  26. metric_handler = None
  27. def open(self):
  28. """
  29. When overridden in a subclass,
  30. opens the persistent storage.
  31. """
  32. pass
  33. def save(self):
  34. """
  35. When overriden in a subclass,
  36. stores the data to a persistent storage.
  37. """
  38. pass
  39. def close(self):
  40. """
  41. When overridden in a subclass,
  42. closes the persistent storage.
  43. """
  44. pass
  45. @property
  46. def status(self):
  47. """Gets status information on the storage."""
  48. nodes = 0
  49. nodes_active = 0
  50. gateways = 0
  51. gateways_active = 0
  52. sum_clients = 0
  53. clients = set()
  54. for node in self.get_nodes():
  55. nodetype = node.get('type', 'node')
  56. if nodetype == 'gateway':
  57. gateways += 1
  58. if self.get_nodestatus(node=node) == 'active':
  59. gateways_active += 1
  60. continue
  61. nodes += 1
  62. nodemacs = [x for x in node.get('macs', [])]
  63. if 'mac' in node:
  64. nodemacs.append(node['mac'])
  65. if self.get_nodestatus(node=node) == 'active':
  66. nodes_active += 1
  67. sum_clients += node.get('clientcount', 0)
  68. for client in node.get('clients', []):
  69. if client in nodemacs:
  70. continue
  71. clients.add(client)
  72. return {
  73. 'clients_sum': sum_clients,
  74. 'clients_unique': len(clients),
  75. 'gateways': gateways,
  76. 'gateways_active': gateways_active,
  77. 'nodes': nodes,
  78. 'nodes_active': nodes_active,
  79. 'now': int(time.time()),
  80. }
  81. def __merge_alias_node(self, item, alias):
  82. # start by using standard dict_merge()
  83. update = ffstatus.dict_merge(item, alias, overwrite_lists=False)
  84. # extract some fields for further inspection
  85. update_macs = update.get('macs', []) or []
  86. # field 'node_id': keep original value
  87. update['node_id'] = item['node_id']
  88. # field 'mac': keep original value
  89. if 'mac' in item:
  90. update['mac'] = item['mac']
  91. if 'mac' in alias:
  92. update_macs.append(alias['mac'])
  93. # field 'macs': get rid of duplicates and primary mac
  94. primary_mac = update.get('mac')
  95. macs = []
  96. for x in update_macs:
  97. if x != primary_mac and x not in macs:
  98. macs.append(x)
  99. update['macs'] = update_macs = macs
  100. # field 'type': keep special node type
  101. item_type = item.get('type', 'node')
  102. if item_type != 'node' and update.get('type', 'node') == 'node':
  103. update['type'] = item_type
  104. return update
  105. def __send_metric(self, key, value, ts=None):
  106. if ts is None:
  107. ts = time.time()
  108. func = self.metric_handler
  109. if func is None or not callable(func):
  110. # no handler -> do nothing
  111. return
  112. func(self, key, value, ts)
  113. def merge_new_data(self, newdata):
  114. """Updates data in the storage by merging the new data."""
  115. if newdata is None or not isinstance(newdata, dict):
  116. raise ValueError("Expected a dict as new data.")
  117. # keep a list of aliased nodes so they can be removed from the result
  118. aliased_nodes = {}
  119. # start merge on a copy of the current data
  120. current = {}
  121. for node in self.get_nodes():
  122. item_id = node['node_id']
  123. current[item_id] = ffstatus.dict_merge(node, {})
  124. current[item_id]['aliases'] = []
  125. current[item_id]['clients'] = []
  126. current[item_id]['neighbours'] = {}
  127. current[item_id]['type'] = 'node'
  128. if not item_id in newdata:
  129. continue
  130. if not '__RAW__' in current[item_id]:
  131. current[item_id]['__RAW__'] = {}
  132. if '__RAW__' in newdata[item_id]:
  133. for key in newdata[item_id]['__RAW__']:
  134. if key in current[item_id]['__RAW__']:
  135. del current[item_id]['__RAW__'][key]
  136. # merge the dictionaries
  137. updated = {}
  138. for itemid in newdata:
  139. if not itemid in current:
  140. # new element which did not exist in storage before, that's easy
  141. updated[itemid] = newdata[itemid]
  142. else:
  143. # merge the old and new element
  144. update = ffstatus.dict_merge(current[itemid], newdata[itemid])
  145. updated[itemid] = update
  146. for alias_id in updated[itemid].get('aliases', []):
  147. if alias_id in aliased_nodes:
  148. aliased_nodes[alias_id].append(itemid)
  149. else:
  150. aliased_nodes[alias_id] = [itemid]
  151. # merge aliased nodes
  152. for alias_id in aliased_nodes:
  153. if len(aliased_nodes[alias_id]) != 1:
  154. logging.warn("Node '%s' is aliased by multiple nodes: %s",
  155. alias_id, aliased_nodes[alias_id])
  156. continue
  157. # target's id is the single entry of the alias list
  158. item_id = aliased_nodes[alias_id][0]
  159. if alias_id == item_id:
  160. # the node has itself as alias -> remove the alias entry
  161. if alias_id in updated and 'aliases' in updated[alias_id]:
  162. updated[alias_id]['aliases'].remove(alias_id)
  163. logging.debug("Removed self-alias of '%s'.", alias_id)
  164. continue
  165. # look for alias node
  166. alias = updated.get(alias_id, current.get(alias_id))
  167. if alias is None:
  168. # no alias node present already, as we're trying to achieve here
  169. continue
  170. # look for target node
  171. item = updated.get(item_id, current.get(item_id))
  172. if item is None:
  173. logging.warn("Alias node '%s' is missing its target '%s.",
  174. alias_id, item_id)
  175. continue
  176. # ensure both target and alias node have 'node_id' field set
  177. if not 'node_id' in item:
  178. item['node_id'] = item_id
  179. alias['node_id'] = alias_id
  180. # merge data
  181. update = self.__merge_alias_node(item, alias)
  182. updated[item_id] = update
  183. logging.debug("Merged alias '%s' into '%s'.", alias_id, item_id)
  184. # mark alias node for deletion
  185. updated[alias_id] = None
  186. # sanitize each item's data
  187. for itemid in updated:
  188. if itemid.startswith('__'):
  189. continue
  190. item = updated[itemid]
  191. # delete node if requested
  192. if item is None:
  193. self.set_node_data(itemid, None)
  194. continue
  195. # ensure 'node_id' is set
  196. if not 'node_id' in item:
  197. item['node_id'] = itemid
  198. # remove node's MACs from clients list
  199. clients = [x for x in item.get('clients', [])]
  200. if 'mac' in item and item['mac'] in clients:
  201. clients.remove(item['mac'])
  202. for mac in item.get('macs', []):
  203. if mac in clients:
  204. clients.remove(mac)
  205. # set clientcount
  206. item['clientcount'] = len(clients)
  207. # finally, set each new data
  208. self.set_node_data(itemid, item)
  209. def get_nodes(self, sortby=None, include_raw_data=False):
  210. """Gets a list of all known nodes."""
  211. nodes = self.get_all_nodes_raw()
  212. sorted_ids = [x for x in nodes]
  213. if sortby is not None:
  214. if sortby == 'name':
  215. sortkey = lambda x: nodes[x]['hostname'].lower()
  216. sorted_ids = sorted(sorted_ids, key=sortkey)
  217. elif sortby == 'id':
  218. sorted_ids = sorted(sorted_ids)
  219. result = []
  220. for nodeid in sorted_ids:
  221. if nodeid.startswith('__'):
  222. continue
  223. node = sanitize_node(nodes[nodeid], include_raw_data)
  224. result.append(node)
  225. return result
  226. def find_node(self, rawid, include_raw_data=False, search_aliases=True):
  227. """
  228. Fetch node data by given id.
  229. If necessary, look through node aliases.
  230. """
  231. # try direct match, first
  232. node = self.get_node(rawid)
  233. if node is not None:
  234. return sanitize_node(node, include_raw_data=include_raw_data)
  235. # look through all nodes
  236. found = None
  237. nodes = self.get_all_nodes_raw()
  238. for nodeid in nodes:
  239. node = nodes[nodeid]
  240. # if we have a direct hit, return it immediately
  241. if nodeid == rawid:
  242. return sanitize_node(node, include_raw_data=include_raw_data)
  243. # search through aliases
  244. if search_aliases and rawid in node.get('aliases', []):
  245. found = node
  246. # return found node
  247. if not found is None:
  248. return sanitize_node(found, include_raw_data=include_raw_data)
  249. else:
  250. return None
  251. def find_node_by_mac(self, mac):
  252. """Fetch node data by given MAC address."""
  253. needle = mac.lower()
  254. # iterate over all nodes
  255. for node in self.get_nodes():
  256. # check node's primary MAC
  257. if 'mac' in node and needle == node['mac'].lower():
  258. return sanitize_node(node)
  259. # check alias MACs
  260. if 'macs' in node:
  261. haystack = [x.lower() for x in node['macs']]
  262. if mac in haystack:
  263. return sanitize_node(node)
  264. # MAC address not found
  265. return None
  266. def get_nodestatus(self, rawid=None, node=None):
  267. """Determine node's status."""
  268. # search node by the given id
  269. if node is None and not rawid is None:
  270. node = self.find_node(rawid)
  271. # handle unknown nodes
  272. if node is None:
  273. return None
  274. # check that the last batadv update is noted in the data
  275. updated = node.get(self.FIELDKEY_UPDATED, None)
  276. if updated is None:
  277. return 'unknown'
  278. u = updated.get('batadv', updated.get('batctl'))
  279. if u is None:
  280. return 'unknown'
  281. # make decision based on time of last batadv update
  282. diff = time.time() - u
  283. if diff < 150:
  284. return 'active'
  285. elif diff < 300:
  286. return 'stale'
  287. else:
  288. return 'offline'
  289. def set_node_data(self, key, data):
  290. """
  291. Overwrite data for the node with the given key.
  292. Specifying 'None' as data effectively means deleting the key.
  293. """
  294. raise NotImplementedError("set_node_data was not overridden")
  295. def check_vpn_key(self, key):
  296. if key is None or re.match(r'^[a-fA-F0-9]+$', key) is None:
  297. raise VpnKeyFormatError(key)
  298. def get_vpn_keys(self):
  299. """Gets a list of VPN keys."""
  300. raise NotImplementedError("get_vpn_keys was not overriden")
  301. def get_vpn_item(self, key, create=False):
  302. self.check_vpn_key(key)
  303. raise NotImplementedError("store_vpn_item was not overriden")
  304. def store_vpn_item(self, key, data):
  305. raise NotImplementedError("store_vpn_item was not overriden")
  306. def resolve_vpn_remotes(self):
  307. """Iterates all remotes and resolves IP blocks not yet resolved."""
  308. vpn = self.get_vpn_keys()
  309. init_vpn_cache = {}
  310. for key in vpn:
  311. entry = self.get_vpn_item(key)
  312. entry_modified = False
  313. for mode in entry:
  314. if not isinstance(entry[mode], dict):
  315. continue
  316. for gateway in entry[mode]:
  317. if not isinstance(entry[mode][gateway], dict):
  318. continue
  319. item = entry[mode][gateway]
  320. if 'remote' in item and not 'remote_raw' in item:
  321. item['remote_raw'] = item['remote']
  322. resolved = None
  323. if item['remote'] in init_vpn_cache:
  324. resolved = init_vpn_cache[item['remote']]
  325. else:
  326. resolved = ffstatus.resolve_ipblock(item['remote'])
  327. init_vpn_cache[item['remote']] = resolved
  328. if resolved is not None:
  329. logging.info(
  330. 'Resolved VPN entry \'%s\' to net \'%s\'.',
  331. item['remote'],
  332. resolved['name'],
  333. )
  334. if resolved is not None:
  335. item['remote'] = resolved
  336. entry_modified = True
  337. if entry_modified:
  338. self.store_vpn_item(key, entry)
  339. def get_vpn_gateways(self):
  340. gateways = set()
  341. vpn = self.get_vpn_keys()
  342. for key in vpn:
  343. entry = self.get_vpn_item(key)
  344. for conntype in entry:
  345. for gateway in entry[conntype]:
  346. gateways.add(gateway)
  347. return sorted(gateways)
  348. def get_vpn_connections(self):
  349. conntypes = ['active', 'last']
  350. result = []
  351. vpnkeys = self.get_vpn_keys()
  352. for key in vpnkeys:
  353. vpn_entry = self.get_vpn_item(key)
  354. if not isinstance(vpn_entry, dict):
  355. continue
  356. item = {
  357. 'key': key,
  358. 'count': {},
  359. 'remote': {},
  360. }
  361. names = set()
  362. for conntype in conntypes:
  363. item['count'][conntype] = 0
  364. item['remote'][conntype] = {}
  365. if conntype in vpn_entry:
  366. for gateway in vpn_entry[conntype]:
  367. if 'remote' in vpn_entry[conntype][gateway]:
  368. remote = vpn_entry[conntype][gateway]['remote']
  369. if remote is None or remote == '':
  370. continue
  371. item['count'][conntype] += 1
  372. item['remote'][conntype][gateway] = remote
  373. if 'peer' in vpn_entry[conntype][gateway]:
  374. names.add(vpn_entry[conntype][gateway]['peer'])
  375. item['names'] = sorted(names)
  376. item['online'] = item['count']['active'] > 0
  377. result.append(item)
  378. return result
  379. def log_vpn_connect(self, key, peername, remote, gateway, timestamp):
  380. item = self.get_vpn_item(key, create=True)
  381. # resolve remote addr to its netblock
  382. remote_raw = remote
  383. remote_resolved = None
  384. if remote is not None:
  385. remote_resolved = ffstatus.resolve_ipblock(remote)
  386. if remote_resolved is not None:
  387. logging.debug('Resolved IP \'{0}\' to block \'{1}\'.'.format(
  388. remote, remote_resolved['name'],
  389. ))
  390. remote = remote_resolved
  391. # store connection info
  392. item['active'][gateway] = {
  393. 'establish': timestamp,
  394. 'peer': peername,
  395. 'remote': remote,
  396. 'remote_raw': remote_raw,
  397. }
  398. self.store_vpn_item(key, item)
  399. def log_vpn_disconnect(self, key, gateway, timestamp):
  400. item = self.get_vpn_item(key, create=True)
  401. active = {}
  402. if gateway in item['active']:
  403. active = item['active'][gateway]
  404. del item['active'][gateway]
  405. active['disestablish'] = timestamp
  406. item['last'][gateway] = active
  407. self.store_vpn_item(key, item)