Beispiel #1
0
 def do_GET(self):
     #self.registry = MetricsHandler.registry
     self.registry = prometheus_client.CollectorRegistry()
     function = self.path.split('?')[0]
     param = self.path.split('?')[1]
     input_name = dict(pair.split('=') for pair in param.split('&'))
     if function == '/probe':
         if input_name.get('module') == 'ping':
             # http://localhost:8888/probe?module=ping&target=8.8.8.8
             result = ping(input_name.get('target'))
             if result[0]:
                 self.rtt_min = Gauge('ping_rtt_min',
                                      'RTT Min',
                                      registry=self.registry)
                 self.rtt_min.set(result[0])
             if result[1]:
                 self.rtt_avg = Gauge('ping_rtt_avg',
                                      'RTT Avg',
                                      registry=self.registry)
                 self.rtt_avg.set(result[1])
             if result[2]:
                 self.rtt_max = Gauge('ping_rtt_max',
                                      'RTT Max',
                                      registry=self.registry)
                 self.rtt_max.set(result[2])
             self.packet_loss = Gauge('ping_packet_loss',
                                      'Packet Loss',
                                      registry=self.registry)
             self.packet_loss.set(result[3])
             return MetricsHandler.do_GET(self)
         elif input_name.get('module') == 'speedtest':
             # http://localhost:8888/probe?module=speedtest
             # optional: http://localhost:8888/probe?module=speedtest&target=17846
             if input_name.get('target'):
                 result = testspeed(input_name.get('target'))
             else:
                 result = testspeed(0)
             if result[0]:
                 self.rtt_min = Gauge('speedtest_download',
                                      'Speedtest download', ['server'],
                                      registry=self.registry)
                 self.rtt_min.labels(server=result[3]).set(result[0])
             if result[1]:
                 self.rtt_avg = Gauge('speedtest_upload',
                                      'Speedtest Upload', ['server'],
                                      registry=self.registry)
                 self.rtt_avg.labels(server=result[3]).set(result[1])
             if result[2]:
                 self.rtt_max = Gauge('speedtest_latency',
                                      'Speedtest Latency', ['server'],
                                      registry=self.registry)
                 self.rtt_max.labels(server=result[3]).set(result[2])
             return MetricsHandler.do_GET(self)
         else:
             print("module not defined")
     else:
         print("function not defined")
 def do_GET(self):
     path = urlparse(self.path).path
     try:
         if path == "/":
             self.send_html()
         elif path == "/xml":
             self.send_xml()
         elif path == "/metrics":
             MetricsHandler.do_GET(self)
         else:
             self.send_error(404)
     except Exception as e:
         self.send_error(500, str(e))
Beispiel #3
0
def nsxv3_agent_exporter():
    os.environ['PATH_INFO'] = "/metrics"
    CustomMetricsHandler = MetricsHandler.factory(REGISTRY)
    from eventlet.green.http.server import HTTPServer
    server = HTTPServer(('', cfg.CONF.AGENT.agent_prometheus_exporter_port), CustomMetricsHandler)
    thread = threading.Thread(target=server.serve_forever)
    thread.start()
def start_http_server(port, addr='', registry=core.REGISTRY):
    """Starts an HTTP server for prometheus metrics as a daemon thread"""
    httpd = _ThreadingSimpleServer((addr, port),
                                   MetricsHandler.factory(registry))
    thread = threading.Thread(target=httpd.serve_forever)
    thread.daemon = False
    thread.start()
Beispiel #5
0
    def do_GET(self):

        if self.path == "/status":
            message = dict(status="alive")
            self.send_response(200)
            self.end_headers()
            self.wfile.write(bytes(json.dumps(message), "utf-8"))

        else:
            return MetricsHandler.do_GET(self)
Beispiel #6
0
def start_http_server(port, addr='', registry=REGISTRY):
    """Starts an HTTP server for prometheus metrics as a daemon thread"""
    def my_http_error_handler(request, client_address):
        print('Request from ' + client_address[0] + ':' +
              str(client_address[1]) + ' dropped. Broken pipe.')

    CustomMetricsHandler = MetricsHandler.factory(registry)
    httpd = _ThreadingSimpleServer((addr, port), CustomMetricsHandler)
    httpd.handle_error = my_http_error_handler
    t = threading.Thread(target=httpd.serve_forever)
    t.daemon = True
    t.start()
Beispiel #7
0
def main():
    p = argparse.ArgumentParser()
    p.add_argument('--port',
                   '-p',
                   default=int(os.environ.get('METRICS_PORT', 9801)),
                   type=int)
    p.add_argument('--min-interval',
                   type=int,
                   default=int(os.environ.get('MIN_INTERVAL', 5)),
                   help='Minimum time to refresh metrics, in seconds')
    p.add_argument('--verbose', '-v', action='store_true')
    p.add_argument('--debug', '-d', action='store_true')

    p.add_argument('--sql-host',
                   action='store_true',
                   default=os.environ.get('SQL_HOST', 'localhost'),
                   help="Bacula SQL host to connect to")
    p.add_argument('--sql-user',
                   action='store_true',
                   default=os.environ.get('SQL_USER', 'bacula'),
                   help="SQL user with read access to bacula DB")
    p.add_argument('--sql-db',
                   action='store_true',
                   default=os.environ.get('SQL_DB', 'bacula'),
                   help="Bacula SQL database name")
    p.add_argument('--sql-password',
                   action='store_true',
                   default=os.environ.get('SQL_PASSWORD', 'bacula'),
                   help="Password for SQL user")

    ns = p.parse_args()
    level = logging.ERROR
    if ns.verbose:
        level = logging.INFO
    if ns.debug:
        level = logging.DEBUG
    logging.basicConfig(level=level)

    r = prometheus_bacula.reader.Reader(
        datetime.timedelta(seconds=ns.min_interval),
        sql_db=ns.sql_db,
        sql_host=ns.sql_host,
        sql_password=ns.sql_password,
        sql_user=ns.sql_user)

    c = prometheus_bacula.collector.MetricsContainer(r)
    c.update()
    h = HTTPServer(('', ns.port), MetricsHandler.factory(c.registry))
    h.serve_forever()
def main(config_file, verbose):
    """
    Launch the exporter using a YAML config file.
    """

    # hush the logger from the compal library and use our own custom logger
    compal.LOGGER.setLevel(logging.WARNING)
    logger = get_logger(verbose)

    # load user and merge with defaults
    config = load_config(config_file)
    exporter_config = config[EXPORTER]

    # fire up collector
    reg = CollectorRegistry()
    reg.register(
        ConnectBoxCollector(
            logger,
            ip_address=config[IP_ADDRESS],
            password=config[PASSWORD],
            timeout=exporter_config[TIMEOUT_SECONDS],
        ))

    # start http server
    CustomMetricsHandler = MetricsHandler.factory(reg)
    httpd = _ThreadingSimpleServer(("", exporter_config[PORT]),
                                   CustomMetricsHandler)
    httpd_thread = threading.Thread(target=httpd.serve_forever)
    httpd_thread.start()

    logger.info(
        f"Exporter running at http://localhost:{exporter_config[PORT]}, querying {config[IP_ADDRESS]}"
    )

    # wait indefinitely
    try:
        while True:
            time.sleep(3)
    except KeyboardInterrupt:
        httpd.shutdown()
        httpd_thread.join()
 def log_request(self, code='-', *args, **kwargs):
     if code == 200:
         return
     # Old-style class, so no super()
     MetricsHandler.log_request(self, code, *args, **kwargs)
Beispiel #10
0
 def log_request(self, code='-', *args, **kwargs):
     if code == 200:
         return
     # Old-style class, so no super()
     MetricsHandler.log_request(self, code, *args, **kwargs)