mtn-stats.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #!/usr/bin/env python3
  2. from collections import defaultdict
  3. from pprint import pprint
  4. import sys
  5. from netaddr import IPSet, IPNetwork
  6. from registry import Inetnum
  7. from utils import read_json
  8. class Count():
  9. # timestamp -> int (deletion or addition)
  10. count = defaultdict(int)
  11. def feed(self, line):
  12. data = line.split()
  13. timestamp = int(data[0])
  14. if data[1] == "add_file":
  15. self.count[timestamp] += 1
  16. elif data[1] == "delete":
  17. self.count[timestamp] -= 1
  18. def dump(self):
  19. return self.count
  20. def history(self):
  21. count = 0
  22. for timestamp in sorted(self.count):
  23. count += self.count[timestamp]
  24. print("{} {}".format(timestamp, count))
  25. class Subnets():
  26. # timestamp -> (added subnets, removed subnets)
  27. space = defaultdict(lambda: (IPSet([]), IPSet([])))
  28. dn42 = IPSet(["172.22.0.0/15"])
  29. registry = Inetnum("/home/zorun/net.dn42.registry")
  30. def feed(self, timestamp, type, subnet):
  31. if not subnet in self.dn42:
  32. return
  33. if subnet in self.registry.data and not self.registry.data[subnet]["status"][0].lower().startswith("assigned"):
  34. return
  35. if data[1] == "add_file":
  36. self.space[timestamp][0].add(subnet)
  37. elif data[1] == "delete":
  38. self.space[timestamp][1].add(subnet)
  39. def history(self):
  40. current = IPSet(read_json("/srv/http/dn42/tower-bird.json"))
  41. used = IPSet([])
  42. for timestamp in sorted(self.space):
  43. used = used.difference(self.space[timestamp][1])
  44. used = used.union(self.space[timestamp][0])
  45. announced = used.intersection(current)
  46. print("{} {} {}".format(timestamp,
  47. float(used.size) / float(self.dn42.size),
  48. float(announced.size) / float(self.dn42.size)))
  49. return used
  50. if __name__ == '__main__':
  51. persons = Count()
  52. inetnums = Subnets()
  53. for line in sys.stdin:
  54. data = line.split()
  55. if data[2].startswith('"data/person/'):
  56. persons.feed(line)
  57. elif data[2].startswith('"data/inetnum/'):
  58. subnet = data[2][14:-1].replace('_', '/')
  59. inetnums.feed(int(data[0]), data[1], subnet)
  60. #persons.history()
  61. result = inetnums.history()
  62. registry = (subnet for subnet in inetnums.registry.data.keys() if inetnums.registry.data[subnet]["status"][0].lower().startswith("assigned"))
  63. registry = IPSet(registry)
  64. pprint(result)
  65. print("\n\n")
  66. pprint(registry.intersection(inetnums.dn42).difference(result))