11import logging
22
3+
34# This is a fake import, only used during type checking.
45from typing import TYPE_CHECKING , Callable
5-
66from prometheus_client import REGISTRY # type: ignore
77from prometheus_client .twisted import MetricsResource # type: ignore
88from twisted import logger # type: ignore
1212from twisted .logger import STDLibLogObserver # type: ignore
1313from twisted .python import threadpool # type: ignore
1414from twisted .web .http import Request , proxiedLogFormatter # type: ignore
15+ import twisted .web .http
1516from twisted .web .server import Site # type: ignore
1617from twisted .web .wsgi import WSGIResource # type: ignore
1718
1819from .metrics import TwistedThreadPoolCollector
1920
20-
2121if TYPE_CHECKING :
2222 from wsgiref .types import WSGIApplication
2323
2828class KubernetesWSGISite (Site ):
2929 """Extension to Site to ignore heath checks for access logging."""
3030
31- def __init__ (self , health_check_path : str , * args , ** kwargs ):
31+ def __init__ (self , health_check_path : str , hide_server : bool = False , * args , ** kwargs ):
32+ self .hide_server = hide_server
3233 self .__health_check_path = health_check_path
3334 super ().__init__ (* args , ** kwargs )
3435
3536 def log (self , request ):
3637 path = request .path .decode ()
3738 if path != self .__health_check_path :
3839 return super ().log (request )
40+
41+ def getResourceFor (self , request ):
42+ if self .hide_server :
43+ request .setHeader (b'server' , b"" )
44+
45+ return super ().getResourceFor (request )
3946
4047
4148class MetricsSite (Site ):
@@ -53,6 +60,7 @@ def serve(
5360 health_check_path : str = "/healthz" ,
5461 min_threads : int = 5 ,
5562 max_threads : int = 20 ,
63+ hide_server : bool = True ,
5664):
5765 # Quiet the Twisted factory logging.
5866 Factory .noisy = False
@@ -76,6 +84,7 @@ def serve(
7684 port ,
7785 access_log_formatter ,
7886 health_check_path ,
87+ hide_server ,
7988 )
8089 _listen_metrics (reactor , metrics_port )
8190
@@ -96,6 +105,7 @@ def _listen_wsgi(
96105 port : int ,
97106 access_log_formatter : LogFormatter ,
98107 health_check_path : str ,
108+ hide_server : bool ,
99109) -> None :
100110 """Listen for the WSGI application."""
101111 wsgi_resource = WSGIResource (reactor , pool , application )
0 commit comments