Skip to content

Commit 7a306eb

Browse files
committed
fix: only create multiproc dir when prometheus and celery metrics are enabled
1 parent 6d104c4 commit 7a306eb

1 file changed

Lines changed: 39 additions & 8 deletions

File tree

src/django_o11y/__init__.py

Lines changed: 39 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -18,14 +18,45 @@
1818
except PackageNotFoundError:
1919
__version__ = "unknown"
2020

21-
# Create the multiproc dir before model imports trigger prometheus_client writes.
22-
# Falls back to PROMETHEUS_MULTIPROC_DIR for operators who set it directly.
23-
_multiproc_dir = os.environ.get(
24-
"DJANGO_O11Y_METRICS_MULTIPROC_BASE_DIR"
25-
) or os.environ.get("PROMETHEUS_MULTIPROC_DIR")
26-
if _multiproc_dir:
27-
os.environ.setdefault("PROMETHEUS_MULTIPROC_DIR", _multiproc_dir)
28-
pathlib.Path(_multiproc_dir).mkdir(parents=True, exist_ok=True)
21+
22+
def _is_celery_worker() -> bool:
23+
import sys
24+
25+
argv = sys.argv
26+
return bool(argv) and os.path.basename(argv[0]) == "celery" and "worker" in argv
27+
28+
29+
def _is_prefork_web_server() -> bool:
30+
import sys
31+
32+
return "gunicorn" in sys.modules or "uwsgi" in sys.modules
33+
34+
35+
def _bool_env(key: str, default: bool) -> bool:
36+
raw = os.environ.get(key)
37+
if raw is None:
38+
return default
39+
return raw.lower() not in ("false", "0", "no", "off")
40+
41+
42+
# Only create the multiproc dir when it will actually be used:
43+
# - Gunicorn/uWSGI with prometheus enabled
44+
# - Celery worker with both prometheus and celery metrics enabled
45+
_need_multiproc = (
46+
_is_prefork_web_server()
47+
and _bool_env("DJANGO_O11Y_METRICS_PROMETHEUS_ENABLED", True)
48+
) or (
49+
_is_celery_worker()
50+
and _bool_env("DJANGO_O11Y_METRICS_PROMETHEUS_ENABLED", True)
51+
and _bool_env("DJANGO_O11Y_CELERY_METRICS_ENABLED", True)
52+
)
53+
if _need_multiproc:
54+
_multiproc_dir = os.environ.get(
55+
"DJANGO_O11Y_METRICS_MULTIPROC_BASE_DIR"
56+
) or os.environ.get("PROMETHEUS_MULTIPROC_DIR")
57+
if _multiproc_dir:
58+
os.environ.setdefault("PROMETHEUS_MULTIPROC_DIR", _multiproc_dir)
59+
pathlib.Path(_multiproc_dir).mkdir(parents=True, exist_ok=True)
2960

3061
default_app_config = "django_o11y.apps.DjangoO11yConfig"
3162

0 commit comments

Comments
 (0)