Skip to content

Commit 9316307

Browse files
authored
Enable Prometheus multiprocess collector (#3525)
1 parent c8506e5 commit 9316307

File tree

2 files changed

+27
-2
lines changed

2 files changed

+27
-2
lines changed

Dockerfile

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,8 @@ COPY --from=python-builder /opt/venv /opt/venv
2727

2828
ENV KINTO_INI=/etc/kinto/kinto.ini \
2929
PORT=8888 \
30-
PATH="/opt/venv/bin:$PATH"
30+
PATH="/opt/venv/bin:$PATH" \
31+
PROMETHEUS_MULTIPROC_DIR="/tmp/metrics"
3132

3233
RUN kinto init --ini $KINTO_INI --host 0.0.0.0 --backend=memory --cache-backend=memory
3334

kinto/plugins/prometheus.py

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
import logging
2+
import os
3+
import shutil
14
import warnings
25
from time import perf_counter as time_now
36

@@ -15,15 +18,29 @@
1518
prometheus_module = None
1619

1720

21+
logger = logging.getLogger(__name__)
22+
1823
_METRICS = {}
1924
_REGISTRY = None
2025

2126

27+
PROMETHEUS_MULTIPROC_DIR = os.getenv("PROMETHEUS_MULTIPROC_DIR")
28+
29+
2230
def get_registry():
2331
global _REGISTRY
2432

2533
if _REGISTRY is None:
26-
_REGISTRY = prometheus_module.CollectorRegistry()
34+
if PROMETHEUS_MULTIPROC_DIR: # pragma: no cover
35+
from prometheus_client import multiprocess
36+
37+
_reset_multiproc_folder_content()
38+
# Ref: https://prometheus.github.io/client_python/multiprocess/
39+
_REGISTRY = prometheus_module.CollectorRegistry()
40+
multiprocess.MultiProcessCollector(_REGISTRY)
41+
else:
42+
_REGISTRY = prometheus_module.REGISTRY
43+
logger.warning("Prometheus metrics will run in single-process mode only.")
2744
return _REGISTRY
2845

2946

@@ -170,6 +187,12 @@ def metrics_view(request):
170187
return resp
171188

172189

190+
def _reset_multiproc_folder_content(): # pragma: no cover
191+
if os.path.exists(PROMETHEUS_MULTIPROC_DIR):
192+
shutil.rmtree(PROMETHEUS_MULTIPROC_DIR)
193+
os.mkdir(PROMETHEUS_MULTIPROC_DIR)
194+
195+
173196
def includeme(config):
174197
if prometheus_module is None:
175198
error_msg = (
@@ -190,6 +213,7 @@ def includeme(config):
190213
# This is mainly useful in tests, where the plugin is included
191214
# several times with different settings.
192215
registry = get_registry()
216+
193217
for collector in _METRICS.values():
194218
try:
195219
registry.unregister(collector)

0 commit comments

Comments
 (0)