Skip to content

Commit

Permalink
Don't expose metrics on production port (openlabs#14)
Browse files Browse the repository at this point in the history
* /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.
  • Loading branch information
jayme-github authored and tback committed Jul 29, 2016
1 parent 5e3ce12 commit c34b81d
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 16 deletions.
4 changes: 2 additions & 2 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ RUN apt-get update && \
rm -rf /var/lib/apt/lists/* /var/tmp/* /tmp/*

ADD src/* /
EXPOSE 5555
EXPOSE 5555 9191

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

CMD ["-b", "0.0.0.0:5555", "--log-file", "-", "app:application"]
CMD ["-b", "0.0.0.0:5555", "-b", "0.0.0.0:9191", "--log-file", "-", "app:application"]
3 changes: 1 addition & 2 deletions src/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,8 @@
from prometheus import prometheus_metrics

@Request.application
@prometheus_metrics('/metrics', ('/', '/healthz'))
@prometheus_metrics(9191, '/metrics', ('/', '/healthz'))
def application(request):

if request.method == 'GET':
return Response(status=status.OK)

Expand Down
22 changes: 10 additions & 12 deletions src/prometheus.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
['method', 'endpoint', 'code']
)

def prometheus_metrics(metrics_path, monitor_endpoints):
def prometheus_metrics(metrics_port, metrics_path, monitor_endpoints):
monitor_endpoints = set([metrics_path] + list(monitor_endpoints))
def prometheus_metrics_decorator(f):
@wraps(f)
Expand All @@ -25,17 +25,15 @@ def f_wrapper(request):
return f(request)

start_time = time()
if request.method == 'GET' and request.path == metrics_path:
status = 200
REQUEST_LATENCIES.labels(
request.method, request.path, status
).observe(time() - start_time)

REQUEST_COUNT.labels(request.method, request.path, status).inc()
return Response(generate_latest(REGISTRY), status=status)

with REQUEST_COUNT.labels(request.method, request.path, 500).count_exceptions():
response = f(request)
# Only respond to /metrics requests via dedicated metrics port
request_port = int(request.environ.get('SERVER_PORT', '-1'))
if request_port == metrics_port and \
request.path == metrics_path and \
request.method == 'GET':
response = Response(generate_latest(REGISTRY), status=200)
else:
with REQUEST_COUNT.labels(request.method, request.path, 500).count_exceptions():
response = f(request)

REQUEST_COUNT.labels(
request.method,
Expand Down

0 comments on commit c34b81d

Please sign in to comment.