From 352e0a0c194196a65aab086c33a3a9c5216c249f Mon Sep 17 00:00:00 2001 From: Laust Rud Jacobsen Date: Tue, 27 Sep 2016 12:37:31 +0200 Subject: [PATCH] start_http_server: start HTTPServer in main thread before handing off to daemon thread This means if you call start_http_server with an already used port/addr combination, you can rescue the OSError, and try for a different port. With this, it becomes possible to probe a range of ports to find one that is available. Idea for this comes from https://github.com/korfuri/django-prometheus/blob/2b6eac500cc9bea402a45f04ca7b63189889785a/django_prometheus/exports.py#L77-L88 - which makes it easy to let each uwsgi worker listen on a port by automatically trying a whole range of ports and picking one that works. --- prometheus_client/exposition.py | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/prometheus_client/exposition.py b/prometheus_client/exposition.py index 7e51ecec..18a47abb 100644 --- a/prometheus_client/exposition.py +++ b/prometheus_client/exposition.py @@ -82,10 +82,15 @@ def log_message(self, format, *args): def start_http_server(port, addr=''): """Starts a HTTP server for prometheus metrics as a daemon thread.""" class PrometheusMetricsServer(threading.Thread): + def __init__(self, httpd): + self.httpd = httpd + super(PrometheusMetricsServer, self).__init__() + def run(self): - httpd = HTTPServer((addr, port), MetricsHandler) - httpd.serve_forever() - t = PrometheusMetricsServer() + self.httpd.serve_forever() + + httpd = HTTPServer((addr, port), MetricsHandler) + t = PrometheusMetricsServer(httpd) t.daemon = True t.start()