Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 35 additions & 1 deletion prometheus_client/exposition.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@
BaseHandler, build_opener, HTTPHandler, HTTPRedirectHandler, HTTPSHandler,
Request,
)
from wsgiref.simple_server import make_server, WSGIRequestHandler, WSGIServer
from wsgiref.simple_server import (
make_server, ServerHandler, WSGIRequestHandler, WSGIServer,
)

from .openmetrics import exposition as openmetrics
from .registry import Collector, REGISTRY
Expand Down Expand Up @@ -163,12 +165,44 @@ def prometheus_app(environ, start_response):
return prometheus_app


class _ServerHandler(ServerHandler):
"""ServerHandler that also treats a dropped TLS connection as a disconnect."""

def handle_error(self):
# wsgiref ignores BrokenPipeError and ConnectionResetError when the
# client goes away mid-response, but a TLS client that does the same
# raises SSLEOFError, which would be logged with a full traceback.
if isinstance(sys.exc_info()[1], ssl.SSLEOFError):
return
super().handle_error()


class _SilentHandler(WSGIRequestHandler):
"""WSGI handler that does not log requests."""

def log_message(self, format, *args):
"""Log nothing."""

def handle(self):
"""Handle a single request, as WSGIRequestHandler does, using _ServerHandler."""
self.raw_requestline = self.rfile.readline(65537)
if len(self.raw_requestline) > 65536:
self.requestline = ''
self.request_version = ''
self.command = ''
self.send_error(414)
return

if not self.parse_request():
return

handler = _ServerHandler(
self.rfile, self.wfile, self.get_stderr(), self.get_environ(),
multithread=False,
)
handler.request_handler = self
handler.run(self.server.get_app())


class ThreadingWSGIServer(ThreadingMixIn, WSGIServer):
"""Thread per request HTTP server."""
Expand Down
28 changes: 26 additions & 2 deletions tests/test_exposition.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
import gzip
from http.server import BaseHTTPRequestHandler, HTTPServer
import io
import os
import ssl
import threading
import time
import unittest
from unittest import mock
import urllib
from wsgiref.util import setup_testing_defaults

import pytest

Expand All @@ -17,8 +20,9 @@
)
from prometheus_client.core import GaugeHistogramMetricFamily, Timestamp
from prometheus_client.exposition import (
basic_auth_handler, choose_encoder, default_handler, MetricsHandler,
passthrough_redirect_handler, start_wsgi_server, tls_auth_handler,
_ServerHandler, basic_auth_handler, choose_encoder, default_handler,
MetricsHandler, passthrough_redirect_handler, start_wsgi_server,
tls_auth_handler,
)
import prometheus_client.openmetrics.exposition as openmetrics

Expand Down Expand Up @@ -960,5 +964,25 @@ def test_escape_label_name(scenario):
assert got == scenario["expectedValue"], f"[{scenario['name']}] Value encoding failed"


class TestServerHandlerErrors(unittest.TestCase):
def _run(self, error):
def app(environ, start_response):
raise error

environ = {}
setup_testing_defaults(environ)
stderr = io.StringIO()
handler = _ServerHandler(io.BytesIO(), io.BytesIO(), stderr, environ)
handler.request_handler = mock.Mock()
handler.run(app)
return stderr.getvalue()

def test_dropped_tls_connection_is_not_logged(self):
self.assertEqual(self._run(ssl.SSLEOFError()), "")

def test_other_errors_are_still_logged(self):
self.assertIn("ValueError", self._run(ValueError("boom")))


if __name__ == '__main__':
unittest.main()