otel-profiling 0.1.0__py3-none-any.whl
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.
- otel_profiling/__init__.py +5 -0
- otel_profiling/environment_variables.py +44 -0
- otel_profiling/instrumentor.py +136 -0
- otel_profiling/profiler.py +268 -0
- otel_profiling-0.1.0.dist-info/METADATA +109 -0
- otel_profiling-0.1.0.dist-info/RECORD +8 -0
- otel_profiling-0.1.0.dist-info/WHEEL +4 -0
- otel_profiling-0.1.0.dist-info/entry_points.txt +3 -0
|
@@ -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))
|
|
@@ -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,8 @@
|
|
|
1
|
+
otel_profiling/__init__.py,sha256=qVc0XX8i_cSi14-gVn0ahYKt8793-OJPOXpK7ULXo54,200
|
|
2
|
+
otel_profiling/environment_variables.py,sha256=4PJvsfWublyMYypN2xX4WnSQpNXw0cWUfKs8yrPLhDs,1345
|
|
3
|
+
otel_profiling/instrumentor.py,sha256=zYx9m5ScC73RhfOzDY9akYihLgmshtC6FFs1tpfLqqY,4915
|
|
4
|
+
otel_profiling/profiler.py,sha256=TKTf2iFpGJ5JfKd1VT6mmWi2pavcwWKd1iD7PuT3-n4,9599
|
|
5
|
+
otel_profiling-0.1.0.dist-info/WHEEL,sha256=G_-rrEibZr7OEM7zdH1dSO6s-VdjfnS5PA4CLAdI9Vw,80
|
|
6
|
+
otel_profiling-0.1.0.dist-info/entry_points.txt,sha256=v6tFQ7baACZBHPUVI95yGurRAc961OTLTh7P_Esqy8M,79
|
|
7
|
+
otel_profiling-0.1.0.dist-info/METADATA,sha256=aqeu2MkuBeKTV84lXedAujRnkWOtKA76kQxMM9B4E7c,5010
|
|
8
|
+
otel_profiling-0.1.0.dist-info/RECORD,,
|