graphite.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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.'
  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, 'nodes.', nodeid, '.', item, ' ', value, ' ', timestamp,
  24. sep='', file=output)
  25. def __do_send(self, data):
  26. sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
  27. sock.connect((self.target_host, self.target_port))
  28. sock.sendall(data)
  29. sock.shutdown(socket.SHUT_WR)
  30. sock.close()
  31. def push(self, data, timestamp=None):
  32. if timestamp is None:
  33. timestamp = time.time()
  34. timestamp = int(timestamp)
  35. output = StringIO.StringIO()
  36. whitelist = None
  37. if self.whitelist is not None and len(self.whitelist) > 0:
  38. whitelist = [x for x in self.whitelist]
  39. for nodeid in data:
  40. if whitelist is not None and nodeid not in whitelist:
  41. #logging.debug(
  42. # 'Graphite output skips node \'%s\' (not in whitelist).',
  43. # nodeid)
  44. continue
  45. nodeinfo = data[nodeid]
  46. for item in ['uptime']:
  47. if item in nodeinfo:
  48. self.__print_graphite_line(
  49. output, nodeid, item, nodeinfo[item], timestamp)
  50. traffic = nodeinfo.get('statistics', {}).get('traffic')
  51. if traffic is not None:
  52. for item in ['rxbytes', 'txbytes']:
  53. self.__print_graphite_line(
  54. output, nodeid, item, traffic[item], timestamp)
  55. all_output = output.getvalue()
  56. if not self.dont_send:
  57. self.__do_send(all_output)
  58. output.close()
  59. return all_output
  60. def handle_metric(self, source, key, value, ts):
  61. if self.whitelist is not None and len(self.whitelist) > 0:
  62. valid_prefixes = ['nodes.' + x for x in self.whitelist]
  63. if len([x for x in valid_prefixes if key.startswith(x)]) == 0:
  64. # not in whitelist
  65. return
  66. data = '{key} {value} {ts}\n'.format(
  67. key=self.prefix + str(key).replace(' ', '_'),
  68. value=float(value),
  69. ts=int(ts))
  70. self.__do_send(data)