2
0

graphite.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. #!/usr/bin/python
  2. from __future__ import print_function
  3. import socket
  4. import time
  5. import StringIO
  6. class GraphitePush:
  7. dont_send = False
  8. prefix = 'ffpb.nodes.'
  9. target_host = None
  10. target_port = 2003
  11. whitelist = None #[ '24a43cf85efa', '24a43cf85edb', '24a43cd94f69', '24a43ca367f0', '24a43ca36807', '24a43cd221d5' ]
  12. def __init__(self, host, port=2003):
  13. self.target_host = host
  14. self.target_port = port
  15. def __str__(self):
  16. return 'Graphite at [{0}]:{1} (prefix=\'{2}\', whitelist={3})'.format(
  17. self.target_host, self.target_port,
  18. self.prefix, self.whitelist)
  19. def push(self, data, ts=None):
  20. if ts is None: ts = time.time()
  21. ts = int(ts)
  22. output = StringIO.StringIO()
  23. whitelist = [ x for x in self.whitelist ] if not self.whitelist is None and len(self.whitelist) > 0 else None
  24. for nodeid in data:
  25. if (not whitelist is None) and (not nodeid in whitelist):
  26. #print("Skipping node {0} as it is not in the configured whitelist.".format(nodeid))
  27. continue
  28. nodeinfo = data[nodeid]
  29. for item in ['uptime']:
  30. if item in nodeinfo:
  31. print(self.prefix, nodeid, '.', item, ' ', nodeinfo[item], ' ', ts, sep='', file=output)
  32. traffic = nodeinfo['statistics']['traffic'] if 'statistics' in nodeinfo and 'traffic' in nodeinfo['statistics'] else None
  33. if not traffic is None:
  34. for item in ['rxbytes', 'txbytes']:
  35. print(self.prefix, nodeid, '.', item, ' ', traffic[item], ' ', ts, sep='', file=output)
  36. all_output = output.getvalue()
  37. if not self.dont_send:
  38. s = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
  39. s.connect((self.target_host, self.target_port))
  40. s.sendall(all_output)
  41. s.shutdown(socket.SHUT_WR)
  42. s.close()
  43. output.close()
  44. return all_output