Skip to content

Commit c34b81d

Browse files
jayme-githubtback
authored andcommitted
Don't expose metrics on production port (openlabs#14)
* /metrics endpoint is now exposed via port 9191 only. This closes openlabs#13. * Remove some duplicate code in case of /metrics request. * Reorder if clause to match as early as possible.
1 parent 5e3ce12 commit c34b81d

File tree

3 files changed

+13
-16
lines changed

3 files changed

+13
-16
lines changed

Dockerfile

+2-2
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,8 @@ RUN apt-get update && \
99
rm -rf /var/lib/apt/lists/* /var/tmp/* /tmp/*
1010

1111
ADD src/* /
12-
EXPOSE 5555
12+
EXPOSE 5555 9191
1313

1414
ENTRYPOINT ["usr/local/bin/gunicorn"]
1515

16-
CMD ["-b", "0.0.0.0:5555", "--log-file", "-", "app:application"]
16+
CMD ["-b", "0.0.0.0:5555", "-b", "0.0.0.0:9191", "--log-file", "-", "app:application"]

src/app.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,8 @@
1717
from prometheus import prometheus_metrics
1818

1919
@Request.application
20-
@prometheus_metrics('/metrics', ('/', '/healthz'))
20+
@prometheus_metrics(9191, '/metrics', ('/', '/healthz'))
2121
def application(request):
22-
2322
if request.method == 'GET':
2423
return Response(status=status.OK)
2524

src/prometheus.py

+10-12
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
['method', 'endpoint', 'code']
1515
)
1616

17-
def prometheus_metrics(metrics_path, monitor_endpoints):
17+
def prometheus_metrics(metrics_port, metrics_path, monitor_endpoints):
1818
monitor_endpoints = set([metrics_path] + list(monitor_endpoints))
1919
def prometheus_metrics_decorator(f):
2020
@wraps(f)
@@ -25,17 +25,15 @@ def f_wrapper(request):
2525
return f(request)
2626

2727
start_time = time()
28-
if request.method == 'GET' and request.path == metrics_path:
29-
status = 200
30-
REQUEST_LATENCIES.labels(
31-
request.method, request.path, status
32-
).observe(time() - start_time)
33-
34-
REQUEST_COUNT.labels(request.method, request.path, status).inc()
35-
return Response(generate_latest(REGISTRY), status=status)
36-
37-
with REQUEST_COUNT.labels(request.method, request.path, 500).count_exceptions():
38-
response = f(request)
28+
# Only respond to /metrics requests via dedicated metrics port
29+
request_port = int(request.environ.get('SERVER_PORT', '-1'))
30+
if request_port == metrics_port and \
31+
request.path == metrics_path and \
32+
request.method == 'GET':
33+
response = Response(generate_latest(REGISTRY), status=200)
34+
else:
35+
with REQUEST_COUNT.labels(request.method, request.path, 500).count_exceptions():
36+
response = f(request)
3937

4038
REQUEST_COUNT.labels(
4139
request.method,

0 commit comments

Comments
 (0)