graphite.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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 push(self, data, ts=None):
  16. if ts is None: ts = time.time()
  17. ts = int(ts)
  18. output = StringIO.StringIO()
  19. whitelist = [ x for x in self.whitelist ] if not self.whitelist is None and len(self.whitelist) > 0 else None
  20. for nodeid in data:
  21. if (not whitelist is None) and (not nodeid in whitelist):
  22. #print("Skipping node {0} as it is not in the configured whitelist.".format(nodeid))
  23. continue
  24. nodeinfo = data[nodeid]
  25. for item in ['uptime']:
  26. if item in nodeinfo:
  27. print(self.prefix, nodeid, '.', item, ' ', nodeinfo[item], ' ', ts, sep='', file=output)
  28. traffic = nodeinfo['statistics']['traffic'] if 'statistics' in nodeinfo and 'traffic' in nodeinfo['statistics'] else None
  29. if not traffic is None:
  30. for item in ['rxbytes', 'txbytes']:
  31. print(self.prefix, nodeid, '.', item, ' ', traffic[item], ' ', ts, sep='', file=output)
  32. all_output = output.getvalue()
  33. if not self.dont_send:
  34. s = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
  35. s.connect((self.target_host, self.target_port))
  36. s.sendall(all_output)
  37. s.shutdown(socket.SHUT_WR)
  38. s.close()
  39. output.close()
  40. return all_output