Skip to content

Commit

Permalink
Change default HTTP Server to WSGI Server
Browse files Browse the repository at this point in the history
Signed-off-by: Emil Madsen <sovende@gmail.com>
  • Loading branch information
Skeen committed Feb 17, 2020
1 parent b48346d commit 4f1d836
Showing 1 changed file with 13 additions and 21 deletions.
34 changes: 13 additions & 21 deletions prometheus_client/exposition.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import socket
import sys
import threading
from wsgiref.simple_server import make_server, WSGIRequestHandler
from wsgiref.simple_server import make_server, WSGIServer, WSGIRequestHandler

from .openmetrics import exposition as openmetrics
from .registry import REGISTRY
Expand Down Expand Up @@ -64,15 +64,26 @@ def log_message(self, format, *args):
"""Log nothing."""


class ThreadingWSGIServer(ThreadingMixIn, WSGIServer):
"""Thread per request HTTP server."""
# Make worker threads "fire and forget". Beginning with Python 3.7 this
# prevents a memory leak because ``ThreadingMixIn`` starts to gather all
# non-daemon threads in a list in order to join on them at server close.
daemon_threads = True


def start_wsgi_server(port, addr='', registry=REGISTRY):
"""Starts a WSGI server for prometheus metrics as a daemon thread."""
app = make_wsgi_app(registry)
httpd = make_server(addr, port, app, handler_class=_SilentHandler)
httpd = make_server(addr, port, app, ThreadingWSGIServer, handler_class=_SilentHandler)
t = threading.Thread(target=httpd.serve_forever)
t.daemon = True
t.start()


start_http_server = start_wsgi_server


def generate_latest(registry=REGISTRY):
"""Returns the metrics from the registry in latest text format as a string."""

Expand Down Expand Up @@ -181,25 +192,6 @@ def factory(cls, registry):
return MyMetricsHandler


class _ThreadingSimpleServer(ThreadingMixIn, HTTPServer):
"""Thread per request HTTP server."""
# Make worker threads "fire and forget". Beginning with Python 3.7 this
# prevents a memory leak because ``ThreadingMixIn`` starts to gather all
# non-daemon threads in a list in order to join on them at server close.
# Enabling daemon threads virtually makes ``_ThreadingSimpleServer`` the
# same as Python 3.7's ``ThreadingHTTPServer``.
daemon_threads = True


def start_http_server(port, addr='', registry=REGISTRY):
"""Starts an HTTP server for prometheus metrics as a daemon thread"""
CustomMetricsHandler = MetricsHandler.factory(registry)
httpd = _ThreadingSimpleServer((addr, port), CustomMetricsHandler)
t = threading.Thread(target=httpd.serve_forever)
t.daemon = True
t.start()


def write_to_textfile(path, registry):
"""Write metrics to the given path.
Expand Down

0 comments on commit 4f1d836

Please sign in to comment.