graphite.py 2.0 KB

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