2
0

graphite.py 2.2 KB

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