otel-profiling 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,109 @@
1
+ Metadata-Version: 2.3
2
+ Name: otel-profiling
3
+ Version: 0.1.0
4
+ Summary: Continuous in-process CPU and wall-clock profiler for Python that exports OpenTelemetry (OTLP) profiles
5
+ Author: Gabriel Chaves
6
+ Author-email: Gabriel Chaves <gabriel.chaves@olist.com>
7
+ Requires-Dist: opentelemetry-api>=1.45.0
8
+ Requires-Dist: opentelemetry-instrumentation>=0.66b0
9
+ Requires-Dist: opentelemetry-proto>=1.45.0
10
+ Requires-Python: >=3.15
11
+ Description-Content-Type: text/markdown
12
+
13
+ # otel-profiling
14
+
15
+ Continuous in-process CPU and wall-clock profiler for Python that exports [OpenTelemetry profiles](https://opentelemetry.io/docs/specs/otel/profiles/) over OTLP.
16
+
17
+ It samples the stacks of every running thread with CPython's built-in remote debugging API (the same one behind
18
+ `python -m profiling.sampling`), so it needs **no extra privileges** (no `SYS_PTRACE`, no eBPF) and **no native
19
+ dependencies**. It runs inside your process, which makes it a fit for environments where you can't deploy a
20
+ profiling agent or a privileged sidecar.
21
+
22
+ > **Status: experimental.** The OTLP profiles signal is still `v1development`, and the CPython API used for
23
+ > sampling is private (`_remote_debugging`). Expect breaking changes between Python minor versions.
24
+
25
+ ## Requirements
26
+
27
+ - Python **3.15+**
28
+ - A backend that accepts OTLP profiles over HTTP/protobuf (e.g. the OpenTelemetry Collector with the profiles
29
+ feature gate, OpenObserve, Grafana Pyroscope)
30
+
31
+ ## Installation
32
+
33
+ ```bash
34
+ pip install otel-profiling
35
+ ```
36
+
37
+ ## Usage
38
+
39
+ The package registers an `opentelemetry_instrumentor` entry point, so with zero-code instrumentation it is picked up
40
+ automatically:
41
+
42
+ ```bash
43
+ export OTEL_PROFILES_EXPORTER=otlp
44
+ opentelemetry-instrument python app.py
45
+ ```
46
+
47
+ Or enable it manually, after configuring your tracer provider:
48
+
49
+ ```python
50
+ from otel_profiling import ProfilingInstrumentor
51
+
52
+ ProfilingInstrumentor().instrument()
53
+ ```
54
+
55
+ The profiler only starts when `OTEL_PROFILES_EXPORTER=otlp`, so it is safe to call `instrument()` unconditionally.
56
+ Profiles carry the resource of the tracer provider (`service.name`, `service.instance.id`, ...), so they line up
57
+ with your traces in the backend.
58
+
59
+ ### Keyword arguments
60
+
61
+ Arguments passed to `instrument()` take precedence over environment variables.
62
+
63
+ | Argument | Default |
64
+ |---|---|
65
+ | `tracer_provider` | The global tracer provider (its resource is attached to the profiles) |
66
+ | `endpoint` | `OTEL_EXPORTER_OTLP_PROFILES_ENDPOINT`, or `OTEL_EXPORTER_OTLP_ENDPOINT` + `/v1/profiles` |
67
+ | `headers` | `OTEL_EXPORTER_OTLP_PROFILES_HEADERS`, or `OTEL_EXPORTER_OTLP_HEADERS` |
68
+ | `sample_interval_millis` | `OTEL_PYTHON_PROFILING_SAMPLE_INTERVAL`, or `10` |
69
+ | `export_interval_millis` | `OTEL_PYTHON_PROFILING_EXPORT_INTERVAL`, or `10000` |
70
+ | `profile_types` | `OTEL_PYTHON_PROFILING_TYPES`, or `("cpu", "wall")` |
71
+
72
+ ## Environment variables
73
+
74
+ | Variable | Default | Description |
75
+ |---|---|---|
76
+ | `OTEL_PROFILES_EXPORTER` | — | Set to `otlp` to enable the profiler |
77
+ | `OTEL_EXPORTER_OTLP_PROFILES_ENDPOINT` | `OTEL_EXPORTER_OTLP_ENDPOINT` + `/v1/profiles` | Full URL profiles are sent to |
78
+ | `OTEL_EXPORTER_OTLP_PROFILES_HEADERS` | `OTEL_EXPORTER_OTLP_HEADERS` | Export headers, as `key=value` pairs separated by commas |
79
+ | `OTEL_PYTHON_PROFILING_SAMPLE_INTERVAL` | `10` | Milliseconds between stack samples |
80
+ | `OTEL_PYTHON_PROFILING_EXPORT_INTERVAL` | `10000` | Milliseconds between exports |
81
+ | `OTEL_PYTHON_PROFILING_TYPES` | `cpu,wall` | Comma-separated profile types to collect (see below) |
82
+
83
+ ## Profile types
84
+
85
+ | Type | Samples | Use it to find |
86
+ |---|---|---|
87
+ | `cpu` | Threads running Python code or native code on CPU | Hot code paths burning CPU |
88
+ | `wall` | Every thread with a Python stack, including those blocked on I/O, locks or `sleep` | Where requests spend time waiting (HTTP calls, database, LLM APIs) |
89
+
90
+ Both come from the same stack sample, so enabling both costs no extra sampling. Each export carries one profile per
91
+ enabled type, sharing the same dictionary.
92
+
93
+ ## How it works
94
+
95
+ - A daemon thread reads the stacks of all threads every sample interval. Every thread counts towards `wall`; only
96
+ threads running on CPU, holding the GIL or waiting for it count towards `cpu`. The sampler itself holds the GIL
97
+ while sampling, so a busy Python thread shows up as *waiting for the GIL* and is still counted as CPU.
98
+ - Samples are aggregated per stack and sent every export interval as an `ExportProfilesServiceRequest`
99
+ (`cpu` / `wall` in `nanoseconds`, each sample weighted by the sampling period).
100
+ - After `fork()` (e.g. Gunicorn workers, `multiprocessing`) the profiler restarts in the child, and the last window
101
+ is flushed at interpreter exit.
102
+
103
+ ## Limitations
104
+
105
+ - Samples are not linked to spans yet (`trace_id` / `span_id`).
106
+ - asyncio tasks are not unwound individually: the stacks are per thread, so suspended tasks don't show up in
107
+ either profile; only the task running at sample time does.
108
+ - A thread genuinely contending for the GIL also counts as `cpu`.
109
+ - Only HTTP/protobuf export is supported (no gRPC).
@@ -0,0 +1,97 @@
1
+ # otel-profiling
2
+
3
+ Continuous in-process CPU and wall-clock profiler for Python that exports [OpenTelemetry profiles](https://opentelemetry.io/docs/specs/otel/profiles/) over OTLP.
4
+
5
+ It samples the stacks of every running thread with CPython's built-in remote debugging API (the same one behind
6
+ `python -m profiling.sampling`), so it needs **no extra privileges** (no `SYS_PTRACE`, no eBPF) and **no native
7
+ dependencies**. It runs inside your process, which makes it a fit for environments where you can't deploy a
8
+ profiling agent or a privileged sidecar.
9
+
10
+ > **Status: experimental.** The OTLP profiles signal is still `v1development`, and the CPython API used for
11
+ > sampling is private (`_remote_debugging`). Expect breaking changes between Python minor versions.
12
+
13
+ ## Requirements
14
+
15
+ - Python **3.15+**
16
+ - A backend that accepts OTLP profiles over HTTP/protobuf (e.g. the OpenTelemetry Collector with the profiles
17
+ feature gate, OpenObserve, Grafana Pyroscope)
18
+
19
+ ## Installation
20
+
21
+ ```bash
22
+ pip install otel-profiling
23
+ ```
24
+
25
+ ## Usage
26
+
27
+ The package registers an `opentelemetry_instrumentor` entry point, so with zero-code instrumentation it is picked up
28
+ automatically:
29
+
30
+ ```bash
31
+ export OTEL_PROFILES_EXPORTER=otlp
32
+ opentelemetry-instrument python app.py
33
+ ```
34
+
35
+ Or enable it manually, after configuring your tracer provider:
36
+
37
+ ```python
38
+ from otel_profiling import ProfilingInstrumentor
39
+
40
+ ProfilingInstrumentor().instrument()
41
+ ```
42
+
43
+ The profiler only starts when `OTEL_PROFILES_EXPORTER=otlp`, so it is safe to call `instrument()` unconditionally.
44
+ Profiles carry the resource of the tracer provider (`service.name`, `service.instance.id`, ...), so they line up
45
+ with your traces in the backend.
46
+
47
+ ### Keyword arguments
48
+
49
+ Arguments passed to `instrument()` take precedence over environment variables.
50
+
51
+ | Argument | Default |
52
+ |---|---|
53
+ | `tracer_provider` | The global tracer provider (its resource is attached to the profiles) |
54
+ | `endpoint` | `OTEL_EXPORTER_OTLP_PROFILES_ENDPOINT`, or `OTEL_EXPORTER_OTLP_ENDPOINT` + `/v1/profiles` |
55
+ | `headers` | `OTEL_EXPORTER_OTLP_PROFILES_HEADERS`, or `OTEL_EXPORTER_OTLP_HEADERS` |
56
+ | `sample_interval_millis` | `OTEL_PYTHON_PROFILING_SAMPLE_INTERVAL`, or `10` |
57
+ | `export_interval_millis` | `OTEL_PYTHON_PROFILING_EXPORT_INTERVAL`, or `10000` |
58
+ | `profile_types` | `OTEL_PYTHON_PROFILING_TYPES`, or `("cpu", "wall")` |
59
+
60
+ ## Environment variables
61
+
62
+ | Variable | Default | Description |
63
+ |---|---|---|
64
+ | `OTEL_PROFILES_EXPORTER` | — | Set to `otlp` to enable the profiler |
65
+ | `OTEL_EXPORTER_OTLP_PROFILES_ENDPOINT` | `OTEL_EXPORTER_OTLP_ENDPOINT` + `/v1/profiles` | Full URL profiles are sent to |
66
+ | `OTEL_EXPORTER_OTLP_PROFILES_HEADERS` | `OTEL_EXPORTER_OTLP_HEADERS` | Export headers, as `key=value` pairs separated by commas |
67
+ | `OTEL_PYTHON_PROFILING_SAMPLE_INTERVAL` | `10` | Milliseconds between stack samples |
68
+ | `OTEL_PYTHON_PROFILING_EXPORT_INTERVAL` | `10000` | Milliseconds between exports |
69
+ | `OTEL_PYTHON_PROFILING_TYPES` | `cpu,wall` | Comma-separated profile types to collect (see below) |
70
+
71
+ ## Profile types
72
+
73
+ | Type | Samples | Use it to find |
74
+ |---|---|---|
75
+ | `cpu` | Threads running Python code or native code on CPU | Hot code paths burning CPU |
76
+ | `wall` | Every thread with a Python stack, including those blocked on I/O, locks or `sleep` | Where requests spend time waiting (HTTP calls, database, LLM APIs) |
77
+
78
+ Both come from the same stack sample, so enabling both costs no extra sampling. Each export carries one profile per
79
+ enabled type, sharing the same dictionary.
80
+
81
+ ## How it works
82
+
83
+ - A daemon thread reads the stacks of all threads every sample interval. Every thread counts towards `wall`; only
84
+ threads running on CPU, holding the GIL or waiting for it count towards `cpu`. The sampler itself holds the GIL
85
+ while sampling, so a busy Python thread shows up as *waiting for the GIL* and is still counted as CPU.
86
+ - Samples are aggregated per stack and sent every export interval as an `ExportProfilesServiceRequest`
87
+ (`cpu` / `wall` in `nanoseconds`, each sample weighted by the sampling period).
88
+ - After `fork()` (e.g. Gunicorn workers, `multiprocessing`) the profiler restarts in the child, and the last window
89
+ is flushed at interpreter exit.
90
+
91
+ ## Limitations
92
+
93
+ - Samples are not linked to spans yet (`trace_id` / `span_id`).
94
+ - asyncio tasks are not unwound individually: the stacks are per thread, so suspended tasks don't show up in
95
+ either profile; only the task running at sample time does.
96
+ - A thread genuinely contending for the GIL also counts as `cpu`.
97
+ - Only HTTP/protobuf export is supported (no gRPC).
@@ -0,0 +1,83 @@
1
+ [project]
2
+ name = "otel-profiling"
3
+ version = "0.1.0"
4
+ description = "Continuous in-process CPU and wall-clock profiler for Python that exports OpenTelemetry (OTLP) profiles"
5
+ readme = "README.md"
6
+ requires-python = ">=3.15"
7
+ dependencies = [
8
+ "opentelemetry-api>=1.45.0",
9
+ "opentelemetry-instrumentation>=0.66b0",
10
+ "opentelemetry-proto>=1.45.0",
11
+ ]
12
+
13
+ [[project.authors]]
14
+ name = "Gabriel Chaves"
15
+ email = "gabriel.chaves@olist.com"
16
+
17
+ [project.entry-points.opentelemetry_instrumentor]
18
+ profiling = "otel_profiling:ProfilingInstrumentor"
19
+
20
+ [dependency-groups]
21
+ dev = [
22
+ "mypy>=1.19.1",
23
+ "opentelemetry-sdk>=1.45.0",
24
+ "pre-commit>=4.0.0",
25
+ "pytest>=9.0.2",
26
+ "pytest-cov>=7.0.0",
27
+ "types-protobuf>=6.30.0",
28
+ ]
29
+
30
+ [build-system]
31
+ requires = ["uv_build>=0.10.2,<0.11.0"]
32
+ build-backend = "uv_build"
33
+
34
+ [tool.uv.build-backend]
35
+ module-name = "otel_profiling"
36
+
37
+ [tool.mypy]
38
+ strict = true
39
+
40
+ [[tool.mypy.overrides]]
41
+ module = ["profiling.*"]
42
+ ignore_missing_imports = true
43
+
44
+ [tool.pytest.ini_options]
45
+ addopts = "--cov --cov-report=term-missing"
46
+
47
+ [tool.ruff]
48
+ target-version = "py315"
49
+ line-length = 110
50
+
51
+ [tool.ruff.lint]
52
+ select = ["ALL"]
53
+ ignore = [
54
+ "ANN",
55
+ "D100",
56
+ "D107",
57
+ "DOC",
58
+ "PD",
59
+ "NPY",
60
+ "AIR",
61
+ "FAST",
62
+ "COM812",
63
+ "ISC001",
64
+ "CPY001",
65
+ ]
66
+
67
+ [tool.ruff.lint.per-file-ignores]
68
+ "tests/**" = [
69
+ "S101",
70
+ "ARG",
71
+ "SLF001",
72
+ "PLR2004",
73
+ "TC",
74
+ ]
75
+
76
+ [tool.ruff.lint.isort]
77
+ known-first-party = ["otel_profiling"]
78
+
79
+ [tool.ruff.lint.pylint]
80
+ max-args = 8
81
+
82
+ [tool.coverage.run]
83
+ source = ["src/otel_profiling"]
@@ -0,0 +1,83 @@
1
+ [project]
2
+ name = "otel-profiling"
3
+ version = "0.1.0"
4
+ description = "Continuous in-process CPU and wall-clock profiler for Python that exports OpenTelemetry (OTLP) profiles"
5
+ readme = "README.md"
6
+ authors = [
7
+ { name = "Gabriel Chaves", email = "gabriel.chaves@olist.com" }
8
+ ]
9
+ requires-python = ">=3.15"
10
+ dependencies = [
11
+ "opentelemetry-api>=1.45.0",
12
+ "opentelemetry-instrumentation>=0.66b0",
13
+ "opentelemetry-proto>=1.45.0",
14
+ ]
15
+
16
+ [project.entry-points.opentelemetry_instrumentor]
17
+ profiling = "otel_profiling:ProfilingInstrumentor"
18
+
19
+ [dependency-groups]
20
+ dev = [
21
+ "mypy>=1.19.1",
22
+ "opentelemetry-sdk>=1.45.0",
23
+ "pre-commit>=4.0.0",
24
+ "pytest>=9.0.2",
25
+ "pytest-cov>=7.0.0",
26
+ "types-protobuf>=6.30.0",
27
+ ]
28
+
29
+ [build-system]
30
+ requires = ["uv_build>=0.10.2,<0.11.0"]
31
+ build-backend = "uv_build"
32
+
33
+ [tool.uv.build-backend]
34
+ module-name = "otel_profiling"
35
+
36
+ [tool.mypy]
37
+ strict = true
38
+
39
+ [[tool.mypy.overrides]]
40
+ module = ["profiling.*"]
41
+ ignore_missing_imports = true
42
+
43
+ [tool.pytest.ini_options]
44
+ addopts = "--cov --cov-report=term-missing"
45
+
46
+ [tool.ruff]
47
+ target-version = "py315"
48
+ line-length = 110
49
+
50
+ [tool.ruff.lint]
51
+ select = ["ALL"]
52
+ ignore = [
53
+ # annotations — mypy strict mode already covers this
54
+ "ANN",
55
+ # docstrings — not enforced in this project
56
+ "D100", "D107",
57
+ # pydoclint — redundant with mypy
58
+ "DOC",
59
+ # pandas / numpy / airflow / fastapi — not used
60
+ "PD", "NPY", "AIR", "FAST",
61
+ # conflicts with ruff formatter
62
+ "COM812", "ISC001",
63
+ # no copyright headers in this project
64
+ "CPY001",
65
+ ]
66
+
67
+ [tool.ruff.lint.per-file-ignores]
68
+ "tests/**" = [
69
+ "S101", # assert allowed in tests
70
+ "ARG", # unused arguments (fixtures)
71
+ "SLF001", # private member access in tests
72
+ "PLR2004", # magic values in tests
73
+ "TC", # imports used only for annotations
74
+ ]
75
+
76
+ [tool.ruff.lint.isort]
77
+ known-first-party = ["otel_profiling"]
78
+
79
+ [tool.ruff.lint.pylint]
80
+ max-args = 8
81
+
82
+ [tool.coverage.run]
83
+ source = ["src/otel_profiling"]
@@ -0,0 +1,5 @@
1
+ """Continuous in-process CPU and wall-clock profiler that exports OpenTelemetry (OTLP) profiles."""
2
+
3
+ from otel_profiling.instrumentor import ProfilingInstrumentor
4
+
5
+ __all__ = ["ProfilingInstrumentor"]
@@ -0,0 +1,44 @@
1
+ OTEL_PROFILES_EXPORTER = "OTEL_PROFILES_EXPORTER"
2
+ """
3
+ .. envvar:: OTEL_PROFILES_EXPORTER
4
+
5
+ Selects the profiles exporter. The profiler only starts when set to ``otlp``.
6
+ """
7
+
8
+ OTEL_EXPORTER_OTLP_PROFILES_ENDPOINT = "OTEL_EXPORTER_OTLP_PROFILES_ENDPOINT"
9
+ """
10
+ .. envvar:: OTEL_EXPORTER_OTLP_PROFILES_ENDPOINT
11
+
12
+ Full URL the profiles are sent to. Defaults to ``OTEL_EXPORTER_OTLP_ENDPOINT`` with
13
+ ``/v1/profiles`` appended.
14
+ """
15
+
16
+ OTEL_EXPORTER_OTLP_PROFILES_HEADERS = "OTEL_EXPORTER_OTLP_PROFILES_HEADERS"
17
+ """
18
+ .. envvar:: OTEL_EXPORTER_OTLP_PROFILES_HEADERS
19
+
20
+ Headers sent with each export, as ``key=value`` pairs separated by commas. Defaults to
21
+ ``OTEL_EXPORTER_OTLP_HEADERS``.
22
+ """
23
+
24
+ OTEL_PYTHON_PROFILING_SAMPLE_INTERVAL = "OTEL_PYTHON_PROFILING_SAMPLE_INTERVAL"
25
+ """
26
+ .. envvar:: OTEL_PYTHON_PROFILING_SAMPLE_INTERVAL
27
+
28
+ Milliseconds between stack samples. Default: ``10``.
29
+ """
30
+
31
+ OTEL_PYTHON_PROFILING_EXPORT_INTERVAL = "OTEL_PYTHON_PROFILING_EXPORT_INTERVAL"
32
+ """
33
+ .. envvar:: OTEL_PYTHON_PROFILING_EXPORT_INTERVAL
34
+
35
+ Milliseconds between profile exports. Default: ``10000``.
36
+ """
37
+
38
+ OTEL_PYTHON_PROFILING_TYPES = "OTEL_PYTHON_PROFILING_TYPES"
39
+ """
40
+ .. envvar:: OTEL_PYTHON_PROFILING_TYPES
41
+
42
+ Comma-separated profile types to collect: ``cpu`` (threads running on CPU) and/or ``wall``
43
+ (every thread, including those blocked on I/O or locks). Default: ``cpu,wall``.
44
+ """
@@ -0,0 +1,136 @@
1
+ import atexit
2
+ import logging
3
+ import os
4
+ import weakref
5
+ from typing import TYPE_CHECKING, Any, override
6
+
7
+ from opentelemetry import trace
8
+ from opentelemetry.instrumentation.instrumentor import BaseInstrumentor # type: ignore[attr-defined]
9
+ from opentelemetry.util.re import parse_env_headers
10
+
11
+ from otel_profiling.environment_variables import (
12
+ OTEL_EXPORTER_OTLP_PROFILES_ENDPOINT,
13
+ OTEL_EXPORTER_OTLP_PROFILES_HEADERS,
14
+ OTEL_PROFILES_EXPORTER,
15
+ OTEL_PYTHON_PROFILING_EXPORT_INTERVAL,
16
+ OTEL_PYTHON_PROFILING_SAMPLE_INTERVAL,
17
+ OTEL_PYTHON_PROFILING_TYPES,
18
+ )
19
+ from otel_profiling.profiler import PROFILE_TYPES, Profiler, ProfileType, to_proto_resource
20
+
21
+ if TYPE_CHECKING:
22
+ from collections.abc import Collection
23
+
24
+ logger = logging.getLogger(__name__)
25
+
26
+ _DEFAULT_ENDPOINT = "http://localhost:4318"
27
+
28
+
29
+ class ProfilingInstrumentor(BaseInstrumentor): # type: ignore[misc]
30
+ """OpenTelemetry instrumentor that runs a continuous profiler exporting OTLP profiles.
31
+
32
+ Enabled only when ``OTEL_PROFILES_EXPORTER=otlp``. Keyword arguments to ``instrument()``
33
+ take precedence over environment variables:
34
+
35
+ - ``tracer_provider``: provider whose resource is attached to the profiles
36
+ (default: the global provider).
37
+ - ``endpoint`` / ``headers``: default to ``OTEL_EXPORTER_OTLP_PROFILES_*``, falling back to
38
+ ``OTEL_EXPORTER_OTLP_*``.
39
+ - ``sample_interval_millis``: default ``OTEL_PYTHON_PROFILING_SAMPLE_INTERVAL`` or ``10``.
40
+ - ``export_interval_millis``: default ``OTEL_PYTHON_PROFILING_EXPORT_INTERVAL`` or ``10000``.
41
+ - ``profile_types``: profile types to collect (``cpu``, ``wall``); default
42
+ ``OTEL_PYTHON_PROFILING_TYPES`` or both.
43
+
44
+ The profiler is restarted in forked children and flushed at interpreter exit.
45
+ """
46
+
47
+ _profiler: Profiler | None = None
48
+ _config: dict[str, Any]
49
+
50
+ @property
51
+ def profiler(self) -> Profiler | None:
52
+ """The running profiler, if any."""
53
+ return self._profiler
54
+
55
+ @override
56
+ def instrumentation_dependencies(self) -> Collection[str]:
57
+ return ()
58
+
59
+ @override
60
+ def _instrument(self, **kwargs: Any) -> None:
61
+ profile_types = _profile_types(kwargs.get("profile_types"))
62
+ if os.environ.get(OTEL_PROFILES_EXPORTER) != "otlp" or not profile_types:
63
+ return
64
+
65
+ tracer_provider = kwargs.get("tracer_provider") or trace.get_tracer_provider()
66
+ resource = getattr(tracer_provider, "resource", None)
67
+ self._config = {
68
+ "resource": to_proto_resource(resource.attributes if resource else {}),
69
+ "endpoint": kwargs.get("endpoint") or _endpoint(),
70
+ "headers": kwargs.get("headers") or _headers(),
71
+ "interval": _millis(
72
+ kwargs.get("sample_interval_millis"), OTEL_PYTHON_PROFILING_SAMPLE_INTERVAL, 10
73
+ ),
74
+ "export_interval": _millis(
75
+ kwargs.get("export_interval_millis"), OTEL_PYTHON_PROFILING_EXPORT_INTERVAL, 10000
76
+ ),
77
+ "profile_types": profile_types,
78
+ }
79
+ self._start()
80
+ atexit.register(self._stop)
81
+ if hasattr(os, "register_at_fork"):
82
+ weak_restart = weakref.WeakMethod(self._restart_in_child)
83
+
84
+ def _after_in_child() -> None:
85
+ if restart := weak_restart():
86
+ restart()
87
+
88
+ os.register_at_fork(after_in_child=_after_in_child)
89
+
90
+ @override
91
+ def _uninstrument(self, **kwargs: Any) -> None:
92
+ self._stop()
93
+
94
+ def _start(self) -> None:
95
+ self._profiler = Profiler(**self._config)
96
+ self._profiler.start()
97
+
98
+ def _stop(self) -> None:
99
+ if self._profiler:
100
+ self._profiler.stop()
101
+ self._profiler = None
102
+
103
+ def _restart_in_child(self) -> None:
104
+ if self._profiler:
105
+ self._start()
106
+
107
+
108
+ def _endpoint() -> str:
109
+ if endpoint := os.environ.get(OTEL_EXPORTER_OTLP_PROFILES_ENDPOINT):
110
+ return endpoint
111
+
112
+ return os.environ.get("OTEL_EXPORTER_OTLP_ENDPOINT", _DEFAULT_ENDPOINT).rstrip("/") + "/v1/profiles"
113
+
114
+
115
+ def _headers() -> dict[str, str]:
116
+ raw = os.environ.get(OTEL_EXPORTER_OTLP_PROFILES_HEADERS) or os.environ.get(
117
+ "OTEL_EXPORTER_OTLP_HEADERS", ""
118
+ )
119
+ return dict(parse_env_headers(raw, liberal=True))
120
+
121
+
122
+ def _millis(value: int | None, env_var: str, default: int) -> float:
123
+ return int(value or os.environ.get(env_var) or default) / 1000
124
+
125
+
126
+ def _profile_types(value: Collection[str] | None) -> tuple[ProfileType, ...]:
127
+ if value is None:
128
+ raw = os.environ.get(OTEL_PYTHON_PROFILING_TYPES)
129
+ value = raw.split(",") if raw else PROFILE_TYPES
130
+
131
+ requested = {item.strip().lower() for item in value}
132
+ unknown = requested - set(PROFILE_TYPES)
133
+ if unknown:
134
+ logger.warning("Ignoring unknown profile types: %s", ", ".join(sorted(unknown)))
135
+
136
+ return tuple(profile_type for profile_type in PROFILE_TYPES if profile_type in requested)
@@ -0,0 +1,268 @@
1
+ import _remote_debugging
2
+ import logging
3
+ import os
4
+ import threading
5
+ import time
6
+ import urllib.request
7
+ from collections import Counter
8
+ from profiling.sampling.constants import (
9
+ PROFILING_MODE_WALL,
10
+ THREAD_STATUS_GIL_REQUESTED,
11
+ THREAD_STATUS_HAS_GIL,
12
+ THREAD_STATUS_ON_CPU,
13
+ )
14
+ from typing import TYPE_CHECKING, Literal
15
+
16
+ from opentelemetry.instrumentation.utils import suppress_instrumentation
17
+ from opentelemetry.proto.collector.profiles.v1development.profiles_service_pb2 import (
18
+ ExportProfilesServiceRequest,
19
+ )
20
+ from opentelemetry.proto.common.v1.common_pb2 import AnyValue, InstrumentationScope, KeyValue
21
+ from opentelemetry.proto.profiles.v1development.profiles_pb2 import (
22
+ Function,
23
+ Line,
24
+ Location,
25
+ Profile,
26
+ ProfilesDictionary,
27
+ ResourceProfiles,
28
+ Sample,
29
+ ScopeProfiles,
30
+ Stack,
31
+ ValueType,
32
+ )
33
+ from opentelemetry.proto.resource.v1.resource_pb2 import Resource
34
+
35
+ if TYPE_CHECKING:
36
+ from collections.abc import Mapping
37
+
38
+ from opentelemetry.util.types import AttributeValue
39
+
40
+ logger = logging.getLogger(__name__)
41
+
42
+ type Frame = tuple[str, str, int]
43
+ type StackKey = tuple[Frame, ...]
44
+ type ProfileType = Literal["cpu", "wall"]
45
+ type Samples = dict[ProfileType, Counter[StackKey]]
46
+
47
+ PROFILE_TYPES: tuple[ProfileType, ...] = ("cpu", "wall")
48
+
49
+ _SCOPE_NAME = "otel_profiling"
50
+ _NANOS_PER_SECOND = 1_000_000_000
51
+ _RUNNING = THREAD_STATUS_ON_CPU | THREAD_STATUS_HAS_GIL | THREAD_STATUS_GIL_REQUESTED
52
+
53
+
54
+ class _Dictionary:
55
+ def __init__(self) -> None:
56
+ self.strings: dict[str, int] = {"": 0}
57
+ self.functions: dict[tuple[str, str], int] = {("", ""): 0}
58
+ self.locations: dict[Frame, int] = {}
59
+ self.stacks: dict[StackKey, int] = {(): 0}
60
+ self.function_table = [Function()]
61
+ self.location_table = [Location()]
62
+ self.stack_table = [Stack()]
63
+
64
+ def string(self, value: str) -> int:
65
+ return self.strings.setdefault(value, len(self.strings))
66
+
67
+ def function(self, filename: str, name: str) -> int:
68
+ key = (filename, name)
69
+ if key not in self.functions:
70
+ self.functions[key] = len(self.function_table)
71
+ self.function_table.append(
72
+ Function(name_strindex=self.string(name), filename_strindex=self.string(filename)),
73
+ )
74
+
75
+ return self.functions[key]
76
+
77
+ def location(self, frame: Frame) -> int:
78
+ if frame not in self.locations:
79
+ filename, name, lineno = frame
80
+ self.locations[frame] = len(self.location_table)
81
+ self.location_table.append(
82
+ Location(lines=[Line(function_index=self.function(filename, name), line=lineno)]),
83
+ )
84
+
85
+ return self.locations[frame]
86
+
87
+ def stack(self, key: StackKey) -> int:
88
+ if key not in self.stacks:
89
+ self.stacks[key] = len(self.stack_table)
90
+ self.stack_table.append(Stack(location_indices=[self.location(frame) for frame in key]))
91
+
92
+ return self.stacks[key]
93
+
94
+ def to_proto(self) -> ProfilesDictionary:
95
+ return ProfilesDictionary(
96
+ string_table=list(self.strings),
97
+ function_table=self.function_table,
98
+ location_table=self.location_table,
99
+ stack_table=self.stack_table,
100
+ )
101
+
102
+
103
+ class Profiler:
104
+ """Continuous in-process profiler exporting OTLP profiles.
105
+
106
+ Samples the stacks of every thread through CPython's remote debugging API and
107
+ periodically exports the aggregated samples as an OTLP ``ExportProfilesServiceRequest``
108
+ over HTTP/protobuf, with one profile per enabled type:
109
+
110
+ - ``cpu``: threads running Python code or native code on CPU.
111
+ - ``wall``: every thread with a Python stack, including those blocked on I/O or locks.
112
+ """
113
+
114
+ def __init__(
115
+ self,
116
+ resource: Resource,
117
+ endpoint: str,
118
+ headers: Mapping[str, str],
119
+ interval: float,
120
+ export_interval: float,
121
+ profile_types: tuple[ProfileType, ...] = PROFILE_TYPES,
122
+ ) -> None:
123
+ self.resource = resource
124
+ self.profile_types = profile_types
125
+ self.endpoint = endpoint
126
+ self.headers = {**headers, "Content-Type": "application/x-protobuf"}
127
+ self.interval = interval
128
+ self.export_interval = export_interval
129
+ self._stop = threading.Event()
130
+ self._thread = threading.Thread(target=self._run, name="otel-profiler", daemon=True)
131
+
132
+ @property
133
+ def is_alive(self) -> bool:
134
+ """Whether the sampling thread is running."""
135
+ return self._thread.is_alive()
136
+
137
+ def start(self) -> None:
138
+ """Start the sampling thread."""
139
+ self._thread.start()
140
+
141
+ def stop(self) -> None:
142
+ """Stop the sampling thread and export the remaining samples."""
143
+ self._stop.set()
144
+ self._thread.join()
145
+
146
+ def _run(self) -> None:
147
+ unwinder = _remote_debugging.RemoteUnwinder(
148
+ os.getpid(),
149
+ all_threads=True,
150
+ mode=PROFILING_MODE_WALL,
151
+ skip_non_matching_threads=False,
152
+ cache_frames=True,
153
+ )
154
+ own_thread = threading.get_native_id()
155
+ samples = self._new_samples()
156
+ window_start = time.time_ns()
157
+
158
+ while not self._stop.wait(self.interval):
159
+ try:
160
+ _sample(unwinder, own_thread, samples)
161
+ except RuntimeError, OSError:
162
+ logger.debug("Profiler sampling failed", exc_info=True)
163
+
164
+ now = time.time_ns()
165
+ if now - window_start >= self.export_interval * _NANOS_PER_SECOND:
166
+ self.export(samples, window_start, now)
167
+ samples = self._new_samples()
168
+ window_start = now
169
+
170
+ self.export(samples, window_start, time.time_ns())
171
+
172
+ def _new_samples(self) -> Samples:
173
+ return {profile_type: Counter() for profile_type in self.profile_types}
174
+
175
+ def export(self, samples: Samples, start: int, end: int) -> None:
176
+ """Send the aggregated samples of a time window, logging failures instead of raising."""
177
+ if not any(samples.values()):
178
+ return
179
+
180
+ try:
181
+ body = self.build_request(samples, start, end).SerializeToString()
182
+ request = urllib.request.Request( # noqa: S310
183
+ self.endpoint, data=body, headers=self.headers, method="POST"
184
+ )
185
+ with suppress_instrumentation(), urllib.request.urlopen(request, timeout=10): # noqa: S310
186
+ pass
187
+ except Exception:
188
+ logger.warning("Profiler export failed", exc_info=True)
189
+
190
+ def build_request(self, samples: Samples, start: int, end: int) -> ExportProfilesServiceRequest:
191
+ """Build the OTLP export request for the samples collected between ``start`` and ``end``."""
192
+ dictionary = _Dictionary()
193
+ period = int(self.interval * _NANOS_PER_SECOND)
194
+ profiles = [
195
+ Profile(
196
+ sample_type=ValueType(
197
+ type_strindex=dictionary.string(profile_type),
198
+ unit_strindex=dictionary.string("nanoseconds"),
199
+ ),
200
+ period_type=ValueType(
201
+ type_strindex=dictionary.string(profile_type),
202
+ unit_strindex=dictionary.string("nanoseconds"),
203
+ ),
204
+ period=period,
205
+ time_unix_nano=start,
206
+ duration_nano=end - start,
207
+ profile_id=os.urandom(16),
208
+ samples=[
209
+ Sample(stack_index=dictionary.stack(key), values=[count * period])
210
+ for key, count in counter.items()
211
+ ],
212
+ )
213
+ for profile_type, counter in samples.items()
214
+ if counter
215
+ ]
216
+ return ExportProfilesServiceRequest(
217
+ resource_profiles=[
218
+ ResourceProfiles(
219
+ resource=self.resource,
220
+ scope_profiles=[
221
+ ScopeProfiles(scope=InstrumentationScope(name=_SCOPE_NAME), profiles=profiles),
222
+ ],
223
+ ),
224
+ ],
225
+ dictionary=dictionary.to_proto(),
226
+ )
227
+
228
+
229
+ def _sample(unwinder: _remote_debugging.RemoteUnwinder, own_thread: int, samples: Samples) -> None:
230
+ cpu, wall = samples.get("cpu"), samples.get("wall")
231
+ for interpreter in unwinder.get_stack_trace():
232
+ for thread in interpreter.threads:
233
+ if thread.thread_id == own_thread or not thread.frame_info:
234
+ continue
235
+
236
+ key = tuple(_frame(frame) for frame in thread.frame_info)
237
+ if wall is not None:
238
+ wall[key] += 1
239
+
240
+ if cpu is not None and thread.status & _RUNNING:
241
+ cpu[key] += 1
242
+
243
+
244
+ def _frame(frame: _remote_debugging.FrameInfo | tuple[object, ...]) -> Frame:
245
+ filename, location, funcname, *_ = frame
246
+ lineno = location[0] if isinstance(location, tuple) else 0
247
+ return str(filename), str(funcname), int(lineno)
248
+
249
+
250
+ def to_proto_resource(attributes: Mapping[str, AttributeValue]) -> Resource:
251
+ """Convert OpenTelemetry resource attributes to the OTLP ``Resource`` message."""
252
+ return Resource(
253
+ attributes=[KeyValue(key=key, value=_any_value(value)) for key, value in attributes.items()]
254
+ )
255
+
256
+
257
+ def _any_value(value: AttributeValue) -> AnyValue:
258
+ match value:
259
+ case bool():
260
+ return AnyValue(bool_value=value)
261
+ case int():
262
+ return AnyValue(int_value=value)
263
+ case float():
264
+ return AnyValue(double_value=value)
265
+ case str():
266
+ return AnyValue(string_value=value)
267
+ case _:
268
+ return AnyValue(string_value=str(value))