Advertisement
Guest User

Untitled

a guest
Feb 18th, 2019
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.73 KB | None | 0 0
  1. import threading
  2. from http.server import HTTPServer
  3. import socket
  4. import time
  5. import datetime
  6. from prometheus.collectors import Gauge
  7. from prometheus.registry import Registry
  8. from prometheus.exporter import PrometheusMetricHandler
  9.  
  10.  
  11. PORT_NUMBER = 9999
  12. seconds = 0
  13.  
  14.  
  15. def seconds_elapsed():
  16.     return seconds
  17.  
  18.  
  19. def time_elapsed():
  20.     return datetime.timedelta(seconds=seconds_elapsed())
  21.  
  22.  
  23. def gather_data(registry):
  24.     """Gathers the metrics"""
  25.     global seconds
  26.  
  27.     # Acquire the name of host
  28.     host = socket.gethostname()
  29.     fqdn = socket.getfqdn(host)
  30.  
  31.     # Create our collectors
  32.     time_metric = Gauge("host_time_epoch", "")
  33.  
  34.     fqdn_metric = Gauge("fully_qualified_domain_name", "")
  35.  
  36.     # register the metric collectors
  37.     registry.register(time_metric)
  38.     registry.register(fqdn_metric)
  39.  
  40.     # Start gathering metrics every second
  41.     while True:
  42.         time.sleep(1)
  43.         seconds += 1
  44.         time_metric.set({'type': 'Timestamp'}, time_elapsed())
  45.         time_metric.set({'type': 'Seconds'}, seconds)
  46.         fqdn_metric.set("", fqdn)
  47.  
  48.  
  49. if __name__ == "__main__":
  50.     # Create the registry
  51.     registry = Registry()
  52.  
  53.     # Create the thread that gathers the data while we serve it
  54.     thread = threading.Thread(target=gather_data, args=(registry,))
  55.     thread.start()
  56.  
  57.     # Set a server to export (expose to prometheus) the data (in a thread)
  58.     try:
  59.         # We make this to set the registry in the handler
  60.         def handler(*args, **kwargs):
  61.             PrometheusMetricHandler(registry, *args, **kwargs)
  62.  
  63.  
  64.         server = HTTPServer(('0.0.0.0', PORT_NUMBER), handler)
  65.         server.serve_forever()
  66.  
  67.     except KeyboardInterrupt:
  68.         server.socket.close()
  69. thread.join()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement