sentry-sdk 0.18.0__py2.py3-none-any.whl → 2.46.0__py2.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.
- sentry_sdk/__init__.py +48 -6
- sentry_sdk/_compat.py +64 -56
- sentry_sdk/_init_implementation.py +84 -0
- sentry_sdk/_log_batcher.py +172 -0
- sentry_sdk/_lru_cache.py +47 -0
- sentry_sdk/_metrics_batcher.py +167 -0
- sentry_sdk/_queue.py +81 -19
- sentry_sdk/_types.py +311 -11
- sentry_sdk/_werkzeug.py +98 -0
- sentry_sdk/ai/__init__.py +7 -0
- sentry_sdk/ai/monitoring.py +137 -0
- sentry_sdk/ai/utils.py +144 -0
- sentry_sdk/api.py +409 -67
- sentry_sdk/attachments.py +75 -0
- sentry_sdk/client.py +849 -103
- sentry_sdk/consts.py +1389 -34
- sentry_sdk/crons/__init__.py +10 -0
- sentry_sdk/crons/api.py +62 -0
- sentry_sdk/crons/consts.py +4 -0
- sentry_sdk/crons/decorator.py +135 -0
- sentry_sdk/debug.py +12 -15
- sentry_sdk/envelope.py +112 -61
- sentry_sdk/feature_flags.py +71 -0
- sentry_sdk/hub.py +442 -386
- sentry_sdk/integrations/__init__.py +228 -58
- sentry_sdk/integrations/_asgi_common.py +108 -0
- sentry_sdk/integrations/_wsgi_common.py +131 -40
- sentry_sdk/integrations/aiohttp.py +221 -72
- sentry_sdk/integrations/anthropic.py +439 -0
- sentry_sdk/integrations/argv.py +4 -6
- sentry_sdk/integrations/ariadne.py +161 -0
- sentry_sdk/integrations/arq.py +247 -0
- sentry_sdk/integrations/asgi.py +237 -135
- sentry_sdk/integrations/asyncio.py +144 -0
- sentry_sdk/integrations/asyncpg.py +208 -0
- sentry_sdk/integrations/atexit.py +13 -18
- sentry_sdk/integrations/aws_lambda.py +233 -80
- sentry_sdk/integrations/beam.py +27 -35
- sentry_sdk/integrations/boto3.py +137 -0
- sentry_sdk/integrations/bottle.py +91 -69
- sentry_sdk/integrations/celery/__init__.py +529 -0
- sentry_sdk/integrations/celery/beat.py +293 -0
- sentry_sdk/integrations/celery/utils.py +43 -0
- sentry_sdk/integrations/chalice.py +35 -28
- sentry_sdk/integrations/clickhouse_driver.py +177 -0
- sentry_sdk/integrations/cloud_resource_context.py +280 -0
- sentry_sdk/integrations/cohere.py +274 -0
- sentry_sdk/integrations/dedupe.py +32 -8
- sentry_sdk/integrations/django/__init__.py +343 -89
- sentry_sdk/integrations/django/asgi.py +201 -22
- sentry_sdk/integrations/django/caching.py +204 -0
- sentry_sdk/integrations/django/middleware.py +80 -32
- sentry_sdk/integrations/django/signals_handlers.py +91 -0
- sentry_sdk/integrations/django/templates.py +69 -2
- sentry_sdk/integrations/django/transactions.py +39 -14
- sentry_sdk/integrations/django/views.py +69 -16
- sentry_sdk/integrations/dramatiq.py +226 -0
- sentry_sdk/integrations/excepthook.py +19 -13
- sentry_sdk/integrations/executing.py +5 -6
- sentry_sdk/integrations/falcon.py +128 -65
- sentry_sdk/integrations/fastapi.py +141 -0
- sentry_sdk/integrations/flask.py +114 -75
- sentry_sdk/integrations/gcp.py +67 -36
- sentry_sdk/integrations/gnu_backtrace.py +14 -22
- sentry_sdk/integrations/google_genai/__init__.py +301 -0
- sentry_sdk/integrations/google_genai/consts.py +16 -0
- sentry_sdk/integrations/google_genai/streaming.py +155 -0
- sentry_sdk/integrations/google_genai/utils.py +576 -0
- sentry_sdk/integrations/gql.py +162 -0
- sentry_sdk/integrations/graphene.py +151 -0
- sentry_sdk/integrations/grpc/__init__.py +168 -0
- sentry_sdk/integrations/grpc/aio/__init__.py +7 -0
- sentry_sdk/integrations/grpc/aio/client.py +95 -0
- sentry_sdk/integrations/grpc/aio/server.py +100 -0
- sentry_sdk/integrations/grpc/client.py +91 -0
- sentry_sdk/integrations/grpc/consts.py +1 -0
- sentry_sdk/integrations/grpc/server.py +66 -0
- sentry_sdk/integrations/httpx.py +178 -0
- sentry_sdk/integrations/huey.py +174 -0
- sentry_sdk/integrations/huggingface_hub.py +378 -0
- sentry_sdk/integrations/langchain.py +1132 -0
- sentry_sdk/integrations/langgraph.py +337 -0
- sentry_sdk/integrations/launchdarkly.py +61 -0
- sentry_sdk/integrations/litellm.py +287 -0
- sentry_sdk/integrations/litestar.py +315 -0
- sentry_sdk/integrations/logging.py +261 -85
- sentry_sdk/integrations/loguru.py +213 -0
- sentry_sdk/integrations/mcp.py +566 -0
- sentry_sdk/integrations/modules.py +6 -33
- sentry_sdk/integrations/openai.py +725 -0
- sentry_sdk/integrations/openai_agents/__init__.py +61 -0
- sentry_sdk/integrations/openai_agents/consts.py +1 -0
- sentry_sdk/integrations/openai_agents/patches/__init__.py +5 -0
- sentry_sdk/integrations/openai_agents/patches/agent_run.py +140 -0
- sentry_sdk/integrations/openai_agents/patches/error_tracing.py +77 -0
- sentry_sdk/integrations/openai_agents/patches/models.py +50 -0
- sentry_sdk/integrations/openai_agents/patches/runner.py +45 -0
- sentry_sdk/integrations/openai_agents/patches/tools.py +77 -0
- sentry_sdk/integrations/openai_agents/spans/__init__.py +5 -0
- sentry_sdk/integrations/openai_agents/spans/agent_workflow.py +21 -0
- sentry_sdk/integrations/openai_agents/spans/ai_client.py +42 -0
- sentry_sdk/integrations/openai_agents/spans/execute_tool.py +48 -0
- sentry_sdk/integrations/openai_agents/spans/handoff.py +19 -0
- sentry_sdk/integrations/openai_agents/spans/invoke_agent.py +86 -0
- sentry_sdk/integrations/openai_agents/utils.py +199 -0
- sentry_sdk/integrations/openfeature.py +35 -0
- sentry_sdk/integrations/opentelemetry/__init__.py +7 -0
- sentry_sdk/integrations/opentelemetry/consts.py +5 -0
- sentry_sdk/integrations/opentelemetry/integration.py +58 -0
- sentry_sdk/integrations/opentelemetry/propagator.py +117 -0
- sentry_sdk/integrations/opentelemetry/span_processor.py +391 -0
- sentry_sdk/integrations/otlp.py +82 -0
- sentry_sdk/integrations/pure_eval.py +20 -11
- sentry_sdk/integrations/pydantic_ai/__init__.py +47 -0
- sentry_sdk/integrations/pydantic_ai/consts.py +1 -0
- sentry_sdk/integrations/pydantic_ai/patches/__init__.py +4 -0
- sentry_sdk/integrations/pydantic_ai/patches/agent_run.py +215 -0
- sentry_sdk/integrations/pydantic_ai/patches/graph_nodes.py +110 -0
- sentry_sdk/integrations/pydantic_ai/patches/model_request.py +40 -0
- sentry_sdk/integrations/pydantic_ai/patches/tools.py +98 -0
- sentry_sdk/integrations/pydantic_ai/spans/__init__.py +3 -0
- sentry_sdk/integrations/pydantic_ai/spans/ai_client.py +246 -0
- sentry_sdk/integrations/pydantic_ai/spans/execute_tool.py +49 -0
- sentry_sdk/integrations/pydantic_ai/spans/invoke_agent.py +112 -0
- sentry_sdk/integrations/pydantic_ai/utils.py +223 -0
- sentry_sdk/integrations/pymongo.py +214 -0
- sentry_sdk/integrations/pyramid.py +71 -60
- sentry_sdk/integrations/quart.py +237 -0
- sentry_sdk/integrations/ray.py +165 -0
- sentry_sdk/integrations/redis/__init__.py +48 -0
- sentry_sdk/integrations/redis/_async_common.py +116 -0
- sentry_sdk/integrations/redis/_sync_common.py +119 -0
- sentry_sdk/integrations/redis/consts.py +19 -0
- sentry_sdk/integrations/redis/modules/__init__.py +0 -0
- sentry_sdk/integrations/redis/modules/caches.py +118 -0
- sentry_sdk/integrations/redis/modules/queries.py +65 -0
- sentry_sdk/integrations/redis/rb.py +32 -0
- sentry_sdk/integrations/redis/redis.py +69 -0
- sentry_sdk/integrations/redis/redis_cluster.py +107 -0
- sentry_sdk/integrations/redis/redis_py_cluster_legacy.py +50 -0
- sentry_sdk/integrations/redis/utils.py +148 -0
- sentry_sdk/integrations/rq.py +62 -52
- sentry_sdk/integrations/rust_tracing.py +284 -0
- sentry_sdk/integrations/sanic.py +248 -114
- sentry_sdk/integrations/serverless.py +13 -22
- sentry_sdk/integrations/socket.py +96 -0
- sentry_sdk/integrations/spark/spark_driver.py +115 -62
- sentry_sdk/integrations/spark/spark_worker.py +42 -50
- sentry_sdk/integrations/sqlalchemy.py +82 -37
- sentry_sdk/integrations/starlette.py +737 -0
- sentry_sdk/integrations/starlite.py +292 -0
- sentry_sdk/integrations/statsig.py +37 -0
- sentry_sdk/integrations/stdlib.py +100 -58
- sentry_sdk/integrations/strawberry.py +394 -0
- sentry_sdk/integrations/sys_exit.py +70 -0
- sentry_sdk/integrations/threading.py +142 -38
- sentry_sdk/integrations/tornado.py +68 -53
- sentry_sdk/integrations/trytond.py +15 -20
- sentry_sdk/integrations/typer.py +60 -0
- sentry_sdk/integrations/unleash.py +33 -0
- sentry_sdk/integrations/unraisablehook.py +53 -0
- sentry_sdk/integrations/wsgi.py +126 -125
- sentry_sdk/logger.py +96 -0
- sentry_sdk/metrics.py +81 -0
- sentry_sdk/monitor.py +120 -0
- sentry_sdk/profiler/__init__.py +49 -0
- sentry_sdk/profiler/continuous_profiler.py +730 -0
- sentry_sdk/profiler/transaction_profiler.py +839 -0
- sentry_sdk/profiler/utils.py +195 -0
- sentry_sdk/scope.py +1542 -112
- sentry_sdk/scrubber.py +177 -0
- sentry_sdk/serializer.py +152 -210
- sentry_sdk/session.py +177 -0
- sentry_sdk/sessions.py +202 -179
- sentry_sdk/spotlight.py +242 -0
- sentry_sdk/tracing.py +1202 -294
- sentry_sdk/tracing_utils.py +1236 -0
- sentry_sdk/transport.py +693 -189
- sentry_sdk/types.py +52 -0
- sentry_sdk/utils.py +1395 -228
- sentry_sdk/worker.py +30 -17
- sentry_sdk-2.46.0.dist-info/METADATA +268 -0
- sentry_sdk-2.46.0.dist-info/RECORD +189 -0
- {sentry_sdk-0.18.0.dist-info → sentry_sdk-2.46.0.dist-info}/WHEEL +1 -1
- sentry_sdk-2.46.0.dist-info/entry_points.txt +2 -0
- sentry_sdk-2.46.0.dist-info/licenses/LICENSE +21 -0
- sentry_sdk/_functools.py +0 -66
- sentry_sdk/integrations/celery.py +0 -275
- sentry_sdk/integrations/redis.py +0 -103
- sentry_sdk-0.18.0.dist-info/LICENSE +0 -9
- sentry_sdk-0.18.0.dist-info/METADATA +0 -66
- sentry_sdk-0.18.0.dist-info/RECORD +0 -65
- {sentry_sdk-0.18.0.dist-info → sentry_sdk-2.46.0.dist-info}/top_level.txt +0 -0
|
@@ -0,0 +1,839 @@
|
|
|
1
|
+
"""
|
|
2
|
+
This file is originally based on code from https://github.com/nylas/nylas-perftools,
|
|
3
|
+
which is published under the following license:
|
|
4
|
+
|
|
5
|
+
The MIT License (MIT)
|
|
6
|
+
|
|
7
|
+
Copyright (c) 2014 Nylas
|
|
8
|
+
|
|
9
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
10
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
11
|
+
in the Software without restriction, including without limitation the rights
|
|
12
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
13
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
14
|
+
furnished to do so, subject to the following conditions:
|
|
15
|
+
|
|
16
|
+
The above copyright notice and this permission notice shall be included in all
|
|
17
|
+
copies or substantial portions of the Software.
|
|
18
|
+
|
|
19
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
20
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
21
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
22
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
23
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
24
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
25
|
+
SOFTWARE.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
import atexit
|
|
29
|
+
import os
|
|
30
|
+
import platform
|
|
31
|
+
import random
|
|
32
|
+
import sys
|
|
33
|
+
import threading
|
|
34
|
+
import time
|
|
35
|
+
import uuid
|
|
36
|
+
import warnings
|
|
37
|
+
from abc import ABC, abstractmethod
|
|
38
|
+
from collections import deque
|
|
39
|
+
|
|
40
|
+
import sentry_sdk
|
|
41
|
+
from sentry_sdk._lru_cache import LRUCache
|
|
42
|
+
from sentry_sdk.profiler.utils import (
|
|
43
|
+
DEFAULT_SAMPLING_FREQUENCY,
|
|
44
|
+
extract_stack,
|
|
45
|
+
)
|
|
46
|
+
from sentry_sdk.utils import (
|
|
47
|
+
capture_internal_exception,
|
|
48
|
+
capture_internal_exceptions,
|
|
49
|
+
get_current_thread_meta,
|
|
50
|
+
is_gevent,
|
|
51
|
+
is_valid_sample_rate,
|
|
52
|
+
logger,
|
|
53
|
+
nanosecond_time,
|
|
54
|
+
set_in_app_in_frames,
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
from typing import TYPE_CHECKING
|
|
58
|
+
|
|
59
|
+
if TYPE_CHECKING:
|
|
60
|
+
from typing import Any
|
|
61
|
+
from typing import Callable
|
|
62
|
+
from typing import Deque
|
|
63
|
+
from typing import Dict
|
|
64
|
+
from typing import List
|
|
65
|
+
from typing import Optional
|
|
66
|
+
from typing import Set
|
|
67
|
+
from typing import Type
|
|
68
|
+
from typing_extensions import TypedDict
|
|
69
|
+
|
|
70
|
+
from sentry_sdk.profiler.utils import (
|
|
71
|
+
ProcessedStack,
|
|
72
|
+
ProcessedFrame,
|
|
73
|
+
ProcessedThreadMetadata,
|
|
74
|
+
FrameId,
|
|
75
|
+
StackId,
|
|
76
|
+
ThreadId,
|
|
77
|
+
ExtractedSample,
|
|
78
|
+
)
|
|
79
|
+
from sentry_sdk._types import Event, SamplingContext, ProfilerMode
|
|
80
|
+
|
|
81
|
+
ProcessedSample = TypedDict(
|
|
82
|
+
"ProcessedSample",
|
|
83
|
+
{
|
|
84
|
+
"elapsed_since_start_ns": str,
|
|
85
|
+
"thread_id": ThreadId,
|
|
86
|
+
"stack_id": int,
|
|
87
|
+
},
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
ProcessedProfile = TypedDict(
|
|
91
|
+
"ProcessedProfile",
|
|
92
|
+
{
|
|
93
|
+
"frames": List[ProcessedFrame],
|
|
94
|
+
"stacks": List[ProcessedStack],
|
|
95
|
+
"samples": List[ProcessedSample],
|
|
96
|
+
"thread_metadata": Dict[ThreadId, ProcessedThreadMetadata],
|
|
97
|
+
},
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
try:
|
|
102
|
+
from gevent.monkey import get_original
|
|
103
|
+
from gevent.threadpool import ThreadPool as _ThreadPool
|
|
104
|
+
|
|
105
|
+
ThreadPool = _ThreadPool # type: Optional[Type[_ThreadPool]]
|
|
106
|
+
thread_sleep = get_original("time", "sleep")
|
|
107
|
+
except ImportError:
|
|
108
|
+
thread_sleep = time.sleep
|
|
109
|
+
|
|
110
|
+
ThreadPool = None
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
_scheduler = None # type: Optional[Scheduler]
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
# The minimum number of unique samples that must exist in a profile to be
|
|
117
|
+
# considered valid.
|
|
118
|
+
PROFILE_MINIMUM_SAMPLES = 2
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def has_profiling_enabled(options):
|
|
122
|
+
# type: (Dict[str, Any]) -> bool
|
|
123
|
+
profiles_sampler = options["profiles_sampler"]
|
|
124
|
+
if profiles_sampler is not None:
|
|
125
|
+
return True
|
|
126
|
+
|
|
127
|
+
profiles_sample_rate = options["profiles_sample_rate"]
|
|
128
|
+
if profiles_sample_rate is not None and profiles_sample_rate > 0:
|
|
129
|
+
return True
|
|
130
|
+
|
|
131
|
+
profiles_sample_rate = options["_experiments"].get("profiles_sample_rate")
|
|
132
|
+
if profiles_sample_rate is not None:
|
|
133
|
+
logger.warning(
|
|
134
|
+
"_experiments['profiles_sample_rate'] is deprecated. "
|
|
135
|
+
"Please use the non-experimental profiles_sample_rate option "
|
|
136
|
+
"directly."
|
|
137
|
+
)
|
|
138
|
+
if profiles_sample_rate > 0:
|
|
139
|
+
return True
|
|
140
|
+
|
|
141
|
+
return False
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def setup_profiler(options):
|
|
145
|
+
# type: (Dict[str, Any]) -> bool
|
|
146
|
+
global _scheduler
|
|
147
|
+
|
|
148
|
+
if _scheduler is not None:
|
|
149
|
+
logger.debug("[Profiling] Profiler is already setup")
|
|
150
|
+
return False
|
|
151
|
+
|
|
152
|
+
frequency = DEFAULT_SAMPLING_FREQUENCY
|
|
153
|
+
|
|
154
|
+
if is_gevent():
|
|
155
|
+
# If gevent has patched the threading modules then we cannot rely on
|
|
156
|
+
# them to spawn a native thread for sampling.
|
|
157
|
+
# Instead we default to the GeventScheduler which is capable of
|
|
158
|
+
# spawning native threads within gevent.
|
|
159
|
+
default_profiler_mode = GeventScheduler.mode
|
|
160
|
+
else:
|
|
161
|
+
default_profiler_mode = ThreadScheduler.mode
|
|
162
|
+
|
|
163
|
+
if options.get("profiler_mode") is not None:
|
|
164
|
+
profiler_mode = options["profiler_mode"]
|
|
165
|
+
else:
|
|
166
|
+
profiler_mode = options.get("_experiments", {}).get("profiler_mode")
|
|
167
|
+
if profiler_mode is not None:
|
|
168
|
+
logger.warning(
|
|
169
|
+
"_experiments['profiler_mode'] is deprecated. Please use the "
|
|
170
|
+
"non-experimental profiler_mode option directly."
|
|
171
|
+
)
|
|
172
|
+
profiler_mode = profiler_mode or default_profiler_mode
|
|
173
|
+
|
|
174
|
+
if (
|
|
175
|
+
profiler_mode == ThreadScheduler.mode
|
|
176
|
+
# for legacy reasons, we'll keep supporting sleep mode for this scheduler
|
|
177
|
+
or profiler_mode == "sleep"
|
|
178
|
+
):
|
|
179
|
+
_scheduler = ThreadScheduler(frequency=frequency)
|
|
180
|
+
elif profiler_mode == GeventScheduler.mode:
|
|
181
|
+
_scheduler = GeventScheduler(frequency=frequency)
|
|
182
|
+
else:
|
|
183
|
+
raise ValueError("Unknown profiler mode: {}".format(profiler_mode))
|
|
184
|
+
|
|
185
|
+
logger.debug(
|
|
186
|
+
"[Profiling] Setting up profiler in {mode} mode".format(mode=_scheduler.mode)
|
|
187
|
+
)
|
|
188
|
+
_scheduler.setup()
|
|
189
|
+
|
|
190
|
+
atexit.register(teardown_profiler)
|
|
191
|
+
|
|
192
|
+
return True
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def teardown_profiler():
|
|
196
|
+
# type: () -> None
|
|
197
|
+
|
|
198
|
+
global _scheduler
|
|
199
|
+
|
|
200
|
+
if _scheduler is not None:
|
|
201
|
+
_scheduler.teardown()
|
|
202
|
+
|
|
203
|
+
_scheduler = None
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
MAX_PROFILE_DURATION_NS = int(3e10) # 30 seconds
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
class Profile:
|
|
210
|
+
def __init__(
|
|
211
|
+
self,
|
|
212
|
+
sampled, # type: Optional[bool]
|
|
213
|
+
start_ns, # type: int
|
|
214
|
+
hub=None, # type: Optional[sentry_sdk.Hub]
|
|
215
|
+
scheduler=None, # type: Optional[Scheduler]
|
|
216
|
+
):
|
|
217
|
+
# type: (...) -> None
|
|
218
|
+
self.scheduler = _scheduler if scheduler is None else scheduler
|
|
219
|
+
|
|
220
|
+
self.event_id = uuid.uuid4().hex # type: str
|
|
221
|
+
|
|
222
|
+
self.sampled = sampled # type: Optional[bool]
|
|
223
|
+
|
|
224
|
+
# Various framework integrations are capable of overwriting the active thread id.
|
|
225
|
+
# If it is set to `None` at the end of the profile, we fall back to the default.
|
|
226
|
+
self._default_active_thread_id = get_current_thread_meta()[0] or 0 # type: int
|
|
227
|
+
self.active_thread_id = None # type: Optional[int]
|
|
228
|
+
|
|
229
|
+
try:
|
|
230
|
+
self.start_ns = start_ns # type: int
|
|
231
|
+
except AttributeError:
|
|
232
|
+
self.start_ns = 0
|
|
233
|
+
|
|
234
|
+
self.stop_ns = 0 # type: int
|
|
235
|
+
self.active = False # type: bool
|
|
236
|
+
|
|
237
|
+
self.indexed_frames = {} # type: Dict[FrameId, int]
|
|
238
|
+
self.indexed_stacks = {} # type: Dict[StackId, int]
|
|
239
|
+
self.frames = [] # type: List[ProcessedFrame]
|
|
240
|
+
self.stacks = [] # type: List[ProcessedStack]
|
|
241
|
+
self.samples = [] # type: List[ProcessedSample]
|
|
242
|
+
|
|
243
|
+
self.unique_samples = 0
|
|
244
|
+
|
|
245
|
+
# Backwards compatibility with the old hub property
|
|
246
|
+
self._hub = None # type: Optional[sentry_sdk.Hub]
|
|
247
|
+
if hub is not None:
|
|
248
|
+
self._hub = hub
|
|
249
|
+
warnings.warn(
|
|
250
|
+
"The `hub` parameter is deprecated. Please do not use it.",
|
|
251
|
+
DeprecationWarning,
|
|
252
|
+
stacklevel=2,
|
|
253
|
+
)
|
|
254
|
+
|
|
255
|
+
def update_active_thread_id(self):
|
|
256
|
+
# type: () -> None
|
|
257
|
+
self.active_thread_id = get_current_thread_meta()[0]
|
|
258
|
+
logger.debug(
|
|
259
|
+
"[Profiling] updating active thread id to {tid}".format(
|
|
260
|
+
tid=self.active_thread_id
|
|
261
|
+
)
|
|
262
|
+
)
|
|
263
|
+
|
|
264
|
+
def _set_initial_sampling_decision(self, sampling_context):
|
|
265
|
+
# type: (SamplingContext) -> None
|
|
266
|
+
"""
|
|
267
|
+
Sets the profile's sampling decision according to the following
|
|
268
|
+
precedence rules:
|
|
269
|
+
|
|
270
|
+
1. If the transaction to be profiled is not sampled, that decision
|
|
271
|
+
will be used, regardless of anything else.
|
|
272
|
+
|
|
273
|
+
2. Use `profiles_sample_rate` to decide.
|
|
274
|
+
"""
|
|
275
|
+
|
|
276
|
+
# The corresponding transaction was not sampled,
|
|
277
|
+
# so don't generate a profile for it.
|
|
278
|
+
if not self.sampled:
|
|
279
|
+
logger.debug(
|
|
280
|
+
"[Profiling] Discarding profile because transaction is discarded."
|
|
281
|
+
)
|
|
282
|
+
self.sampled = False
|
|
283
|
+
return
|
|
284
|
+
|
|
285
|
+
# The profiler hasn't been properly initialized.
|
|
286
|
+
if self.scheduler is None:
|
|
287
|
+
logger.debug(
|
|
288
|
+
"[Profiling] Discarding profile because profiler was not started."
|
|
289
|
+
)
|
|
290
|
+
self.sampled = False
|
|
291
|
+
return
|
|
292
|
+
|
|
293
|
+
client = sentry_sdk.get_client()
|
|
294
|
+
if not client.is_active():
|
|
295
|
+
self.sampled = False
|
|
296
|
+
return
|
|
297
|
+
|
|
298
|
+
options = client.options
|
|
299
|
+
|
|
300
|
+
if callable(options.get("profiles_sampler")):
|
|
301
|
+
sample_rate = options["profiles_sampler"](sampling_context)
|
|
302
|
+
elif options["profiles_sample_rate"] is not None:
|
|
303
|
+
sample_rate = options["profiles_sample_rate"]
|
|
304
|
+
else:
|
|
305
|
+
sample_rate = options["_experiments"].get("profiles_sample_rate")
|
|
306
|
+
|
|
307
|
+
# The profiles_sample_rate option was not set, so profiling
|
|
308
|
+
# was never enabled.
|
|
309
|
+
if sample_rate is None:
|
|
310
|
+
logger.debug(
|
|
311
|
+
"[Profiling] Discarding profile because profiling was not enabled."
|
|
312
|
+
)
|
|
313
|
+
self.sampled = False
|
|
314
|
+
return
|
|
315
|
+
|
|
316
|
+
if not is_valid_sample_rate(sample_rate, source="Profiling"):
|
|
317
|
+
logger.warning(
|
|
318
|
+
"[Profiling] Discarding profile because of invalid sample rate."
|
|
319
|
+
)
|
|
320
|
+
self.sampled = False
|
|
321
|
+
return
|
|
322
|
+
|
|
323
|
+
# Now we roll the dice. random.random is inclusive of 0, but not of 1,
|
|
324
|
+
# so strict < is safe here. In case sample_rate is a boolean, cast it
|
|
325
|
+
# to a float (True becomes 1.0 and False becomes 0.0)
|
|
326
|
+
self.sampled = random.random() < float(sample_rate)
|
|
327
|
+
|
|
328
|
+
if self.sampled:
|
|
329
|
+
logger.debug("[Profiling] Initializing profile")
|
|
330
|
+
else:
|
|
331
|
+
logger.debug(
|
|
332
|
+
"[Profiling] Discarding profile because it's not included in the random sample (sample rate = {sample_rate})".format(
|
|
333
|
+
sample_rate=float(sample_rate)
|
|
334
|
+
)
|
|
335
|
+
)
|
|
336
|
+
|
|
337
|
+
def start(self):
|
|
338
|
+
# type: () -> None
|
|
339
|
+
if not self.sampled or self.active:
|
|
340
|
+
return
|
|
341
|
+
|
|
342
|
+
assert self.scheduler, "No scheduler specified"
|
|
343
|
+
logger.debug("[Profiling] Starting profile")
|
|
344
|
+
self.active = True
|
|
345
|
+
if not self.start_ns:
|
|
346
|
+
self.start_ns = nanosecond_time()
|
|
347
|
+
self.scheduler.start_profiling(self)
|
|
348
|
+
|
|
349
|
+
def stop(self):
|
|
350
|
+
# type: () -> None
|
|
351
|
+
if not self.sampled or not self.active:
|
|
352
|
+
return
|
|
353
|
+
|
|
354
|
+
assert self.scheduler, "No scheduler specified"
|
|
355
|
+
logger.debug("[Profiling] Stopping profile")
|
|
356
|
+
self.active = False
|
|
357
|
+
self.stop_ns = nanosecond_time()
|
|
358
|
+
|
|
359
|
+
def __enter__(self):
|
|
360
|
+
# type: () -> Profile
|
|
361
|
+
scope = sentry_sdk.get_isolation_scope()
|
|
362
|
+
old_profile = scope.profile
|
|
363
|
+
scope.profile = self
|
|
364
|
+
|
|
365
|
+
self._context_manager_state = (scope, old_profile)
|
|
366
|
+
|
|
367
|
+
self.start()
|
|
368
|
+
|
|
369
|
+
return self
|
|
370
|
+
|
|
371
|
+
def __exit__(self, ty, value, tb):
|
|
372
|
+
# type: (Optional[Any], Optional[Any], Optional[Any]) -> None
|
|
373
|
+
with capture_internal_exceptions():
|
|
374
|
+
self.stop()
|
|
375
|
+
|
|
376
|
+
scope, old_profile = self._context_manager_state
|
|
377
|
+
del self._context_manager_state
|
|
378
|
+
|
|
379
|
+
scope.profile = old_profile
|
|
380
|
+
|
|
381
|
+
def write(self, ts, sample):
|
|
382
|
+
# type: (int, ExtractedSample) -> None
|
|
383
|
+
if not self.active:
|
|
384
|
+
return
|
|
385
|
+
|
|
386
|
+
if ts < self.start_ns:
|
|
387
|
+
return
|
|
388
|
+
|
|
389
|
+
offset = ts - self.start_ns
|
|
390
|
+
if offset > MAX_PROFILE_DURATION_NS:
|
|
391
|
+
self.stop()
|
|
392
|
+
return
|
|
393
|
+
|
|
394
|
+
self.unique_samples += 1
|
|
395
|
+
|
|
396
|
+
elapsed_since_start_ns = str(offset)
|
|
397
|
+
|
|
398
|
+
for tid, (stack_id, frame_ids, frames) in sample:
|
|
399
|
+
try:
|
|
400
|
+
# Check if the stack is indexed first, this lets us skip
|
|
401
|
+
# indexing frames if it's not necessary
|
|
402
|
+
if stack_id not in self.indexed_stacks:
|
|
403
|
+
for i, frame_id in enumerate(frame_ids):
|
|
404
|
+
if frame_id not in self.indexed_frames:
|
|
405
|
+
self.indexed_frames[frame_id] = len(self.indexed_frames)
|
|
406
|
+
self.frames.append(frames[i])
|
|
407
|
+
|
|
408
|
+
self.indexed_stacks[stack_id] = len(self.indexed_stacks)
|
|
409
|
+
self.stacks.append(
|
|
410
|
+
[self.indexed_frames[frame_id] for frame_id in frame_ids]
|
|
411
|
+
)
|
|
412
|
+
|
|
413
|
+
self.samples.append(
|
|
414
|
+
{
|
|
415
|
+
"elapsed_since_start_ns": elapsed_since_start_ns,
|
|
416
|
+
"thread_id": tid,
|
|
417
|
+
"stack_id": self.indexed_stacks[stack_id],
|
|
418
|
+
}
|
|
419
|
+
)
|
|
420
|
+
except AttributeError:
|
|
421
|
+
# For some reason, the frame we get doesn't have certain attributes.
|
|
422
|
+
# When this happens, we abandon the current sample as it's bad.
|
|
423
|
+
capture_internal_exception(sys.exc_info())
|
|
424
|
+
|
|
425
|
+
def process(self):
|
|
426
|
+
# type: () -> ProcessedProfile
|
|
427
|
+
|
|
428
|
+
# This collects the thread metadata at the end of a profile. Doing it
|
|
429
|
+
# this way means that any threads that terminate before the profile ends
|
|
430
|
+
# will not have any metadata associated with it.
|
|
431
|
+
thread_metadata = {
|
|
432
|
+
str(thread.ident): {
|
|
433
|
+
"name": str(thread.name),
|
|
434
|
+
}
|
|
435
|
+
for thread in threading.enumerate()
|
|
436
|
+
} # type: Dict[str, ProcessedThreadMetadata]
|
|
437
|
+
|
|
438
|
+
return {
|
|
439
|
+
"frames": self.frames,
|
|
440
|
+
"stacks": self.stacks,
|
|
441
|
+
"samples": self.samples,
|
|
442
|
+
"thread_metadata": thread_metadata,
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
def to_json(self, event_opt, options):
|
|
446
|
+
# type: (Event, Dict[str, Any]) -> Dict[str, Any]
|
|
447
|
+
profile = self.process()
|
|
448
|
+
|
|
449
|
+
set_in_app_in_frames(
|
|
450
|
+
profile["frames"],
|
|
451
|
+
options["in_app_exclude"],
|
|
452
|
+
options["in_app_include"],
|
|
453
|
+
options["project_root"],
|
|
454
|
+
)
|
|
455
|
+
|
|
456
|
+
return {
|
|
457
|
+
"environment": event_opt.get("environment"),
|
|
458
|
+
"event_id": self.event_id,
|
|
459
|
+
"platform": "python",
|
|
460
|
+
"profile": profile,
|
|
461
|
+
"release": event_opt.get("release", ""),
|
|
462
|
+
"timestamp": event_opt["start_timestamp"],
|
|
463
|
+
"version": "1",
|
|
464
|
+
"device": {
|
|
465
|
+
"architecture": platform.machine(),
|
|
466
|
+
},
|
|
467
|
+
"os": {
|
|
468
|
+
"name": platform.system(),
|
|
469
|
+
"version": platform.release(),
|
|
470
|
+
},
|
|
471
|
+
"runtime": {
|
|
472
|
+
"name": platform.python_implementation(),
|
|
473
|
+
"version": platform.python_version(),
|
|
474
|
+
},
|
|
475
|
+
"transactions": [
|
|
476
|
+
{
|
|
477
|
+
"id": event_opt["event_id"],
|
|
478
|
+
"name": event_opt["transaction"],
|
|
479
|
+
# we start the transaction before the profile and this is
|
|
480
|
+
# the transaction start time relative to the profile, so we
|
|
481
|
+
# hardcode it to 0 until we can start the profile before
|
|
482
|
+
"relative_start_ns": "0",
|
|
483
|
+
# use the duration of the profile instead of the transaction
|
|
484
|
+
# because we end the transaction after the profile
|
|
485
|
+
"relative_end_ns": str(self.stop_ns - self.start_ns),
|
|
486
|
+
"trace_id": event_opt["contexts"]["trace"]["trace_id"],
|
|
487
|
+
"active_thread_id": str(
|
|
488
|
+
self._default_active_thread_id
|
|
489
|
+
if self.active_thread_id is None
|
|
490
|
+
else self.active_thread_id
|
|
491
|
+
),
|
|
492
|
+
}
|
|
493
|
+
],
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
def valid(self):
|
|
497
|
+
# type: () -> bool
|
|
498
|
+
client = sentry_sdk.get_client()
|
|
499
|
+
if not client.is_active():
|
|
500
|
+
return False
|
|
501
|
+
|
|
502
|
+
if not has_profiling_enabled(client.options):
|
|
503
|
+
return False
|
|
504
|
+
|
|
505
|
+
if self.sampled is None or not self.sampled:
|
|
506
|
+
if client.transport:
|
|
507
|
+
client.transport.record_lost_event(
|
|
508
|
+
"sample_rate", data_category="profile"
|
|
509
|
+
)
|
|
510
|
+
return False
|
|
511
|
+
|
|
512
|
+
if self.unique_samples < PROFILE_MINIMUM_SAMPLES:
|
|
513
|
+
if client.transport:
|
|
514
|
+
client.transport.record_lost_event(
|
|
515
|
+
"insufficient_data", data_category="profile"
|
|
516
|
+
)
|
|
517
|
+
logger.debug("[Profiling] Discarding profile because insufficient samples.")
|
|
518
|
+
return False
|
|
519
|
+
|
|
520
|
+
return True
|
|
521
|
+
|
|
522
|
+
@property
|
|
523
|
+
def hub(self):
|
|
524
|
+
# type: () -> Optional[sentry_sdk.Hub]
|
|
525
|
+
warnings.warn(
|
|
526
|
+
"The `hub` attribute is deprecated. Please do not access it.",
|
|
527
|
+
DeprecationWarning,
|
|
528
|
+
stacklevel=2,
|
|
529
|
+
)
|
|
530
|
+
return self._hub
|
|
531
|
+
|
|
532
|
+
@hub.setter
|
|
533
|
+
def hub(self, value):
|
|
534
|
+
# type: (Optional[sentry_sdk.Hub]) -> None
|
|
535
|
+
warnings.warn(
|
|
536
|
+
"The `hub` attribute is deprecated. Please do not set it.",
|
|
537
|
+
DeprecationWarning,
|
|
538
|
+
stacklevel=2,
|
|
539
|
+
)
|
|
540
|
+
self._hub = value
|
|
541
|
+
|
|
542
|
+
|
|
543
|
+
class Scheduler(ABC):
|
|
544
|
+
mode = "unknown" # type: ProfilerMode
|
|
545
|
+
|
|
546
|
+
def __init__(self, frequency):
|
|
547
|
+
# type: (int) -> None
|
|
548
|
+
self.interval = 1.0 / frequency
|
|
549
|
+
|
|
550
|
+
self.sampler = self.make_sampler()
|
|
551
|
+
|
|
552
|
+
# cap the number of new profiles at any time so it does not grow infinitely
|
|
553
|
+
self.new_profiles = deque(maxlen=128) # type: Deque[Profile]
|
|
554
|
+
self.active_profiles = set() # type: Set[Profile]
|
|
555
|
+
|
|
556
|
+
def __enter__(self):
|
|
557
|
+
# type: () -> Scheduler
|
|
558
|
+
self.setup()
|
|
559
|
+
return self
|
|
560
|
+
|
|
561
|
+
def __exit__(self, ty, value, tb):
|
|
562
|
+
# type: (Optional[Any], Optional[Any], Optional[Any]) -> None
|
|
563
|
+
self.teardown()
|
|
564
|
+
|
|
565
|
+
@abstractmethod
|
|
566
|
+
def setup(self):
|
|
567
|
+
# type: () -> None
|
|
568
|
+
pass
|
|
569
|
+
|
|
570
|
+
@abstractmethod
|
|
571
|
+
def teardown(self):
|
|
572
|
+
# type: () -> None
|
|
573
|
+
pass
|
|
574
|
+
|
|
575
|
+
def ensure_running(self):
|
|
576
|
+
# type: () -> None
|
|
577
|
+
"""
|
|
578
|
+
Ensure the scheduler is running. By default, this method is a no-op.
|
|
579
|
+
The method should be overridden by any implementation for which it is
|
|
580
|
+
relevant.
|
|
581
|
+
"""
|
|
582
|
+
return None
|
|
583
|
+
|
|
584
|
+
def start_profiling(self, profile):
|
|
585
|
+
# type: (Profile) -> None
|
|
586
|
+
self.ensure_running()
|
|
587
|
+
self.new_profiles.append(profile)
|
|
588
|
+
|
|
589
|
+
def make_sampler(self):
|
|
590
|
+
# type: () -> Callable[..., None]
|
|
591
|
+
cwd = os.getcwd()
|
|
592
|
+
|
|
593
|
+
cache = LRUCache(max_size=256)
|
|
594
|
+
|
|
595
|
+
def _sample_stack(*args, **kwargs):
|
|
596
|
+
# type: (*Any, **Any) -> None
|
|
597
|
+
"""
|
|
598
|
+
Take a sample of the stack on all the threads in the process.
|
|
599
|
+
This should be called at a regular interval to collect samples.
|
|
600
|
+
"""
|
|
601
|
+
# no profiles taking place, so we can stop early
|
|
602
|
+
if not self.new_profiles and not self.active_profiles:
|
|
603
|
+
# make sure to clear the cache if we're not profiling so we dont
|
|
604
|
+
# keep a reference to the last stack of frames around
|
|
605
|
+
return
|
|
606
|
+
|
|
607
|
+
# This is the number of profiles we want to pop off.
|
|
608
|
+
# It's possible another thread adds a new profile to
|
|
609
|
+
# the list and we spend longer than we want inside
|
|
610
|
+
# the loop below.
|
|
611
|
+
#
|
|
612
|
+
# Also make sure to set this value before extracting
|
|
613
|
+
# frames so we do not write to any new profiles that
|
|
614
|
+
# were started after this point.
|
|
615
|
+
new_profiles = len(self.new_profiles)
|
|
616
|
+
|
|
617
|
+
now = nanosecond_time()
|
|
618
|
+
|
|
619
|
+
try:
|
|
620
|
+
sample = [
|
|
621
|
+
(str(tid), extract_stack(frame, cache, cwd))
|
|
622
|
+
for tid, frame in sys._current_frames().items()
|
|
623
|
+
]
|
|
624
|
+
except AttributeError:
|
|
625
|
+
# For some reason, the frame we get doesn't have certain attributes.
|
|
626
|
+
# When this happens, we abandon the current sample as it's bad.
|
|
627
|
+
capture_internal_exception(sys.exc_info())
|
|
628
|
+
return
|
|
629
|
+
|
|
630
|
+
# Move the new profiles into the active_profiles set.
|
|
631
|
+
#
|
|
632
|
+
# We cannot directly add the to active_profiles set
|
|
633
|
+
# in `start_profiling` because it is called from other
|
|
634
|
+
# threads which can cause a RuntimeError when it the
|
|
635
|
+
# set sizes changes during iteration without a lock.
|
|
636
|
+
#
|
|
637
|
+
# We also want to avoid using a lock here so threads
|
|
638
|
+
# that are starting profiles are not blocked until it
|
|
639
|
+
# can acquire the lock.
|
|
640
|
+
for _ in range(new_profiles):
|
|
641
|
+
self.active_profiles.add(self.new_profiles.popleft())
|
|
642
|
+
|
|
643
|
+
inactive_profiles = []
|
|
644
|
+
|
|
645
|
+
for profile in self.active_profiles:
|
|
646
|
+
if profile.active:
|
|
647
|
+
profile.write(now, sample)
|
|
648
|
+
else:
|
|
649
|
+
# If a profile is marked inactive, we buffer it
|
|
650
|
+
# to `inactive_profiles` so it can be removed.
|
|
651
|
+
# We cannot remove it here as it would result
|
|
652
|
+
# in a RuntimeError.
|
|
653
|
+
inactive_profiles.append(profile)
|
|
654
|
+
|
|
655
|
+
for profile in inactive_profiles:
|
|
656
|
+
self.active_profiles.remove(profile)
|
|
657
|
+
|
|
658
|
+
return _sample_stack
|
|
659
|
+
|
|
660
|
+
|
|
661
|
+
class ThreadScheduler(Scheduler):
|
|
662
|
+
"""
|
|
663
|
+
This scheduler is based on running a daemon thread that will call
|
|
664
|
+
the sampler at a regular interval.
|
|
665
|
+
"""
|
|
666
|
+
|
|
667
|
+
mode = "thread" # type: ProfilerMode
|
|
668
|
+
name = "sentry.profiler.ThreadScheduler"
|
|
669
|
+
|
|
670
|
+
def __init__(self, frequency):
|
|
671
|
+
# type: (int) -> None
|
|
672
|
+
super().__init__(frequency=frequency)
|
|
673
|
+
|
|
674
|
+
# used to signal to the thread that it should stop
|
|
675
|
+
self.running = False
|
|
676
|
+
self.thread = None # type: Optional[threading.Thread]
|
|
677
|
+
self.pid = None # type: Optional[int]
|
|
678
|
+
self.lock = threading.Lock()
|
|
679
|
+
|
|
680
|
+
def setup(self):
|
|
681
|
+
# type: () -> None
|
|
682
|
+
pass
|
|
683
|
+
|
|
684
|
+
def teardown(self):
|
|
685
|
+
# type: () -> None
|
|
686
|
+
if self.running:
|
|
687
|
+
self.running = False
|
|
688
|
+
if self.thread is not None:
|
|
689
|
+
self.thread.join()
|
|
690
|
+
|
|
691
|
+
def ensure_running(self):
|
|
692
|
+
# type: () -> None
|
|
693
|
+
"""
|
|
694
|
+
Check that the profiler has an active thread to run in, and start one if
|
|
695
|
+
that's not the case.
|
|
696
|
+
|
|
697
|
+
Note that this might fail (e.g. in Python 3.12 it's not possible to
|
|
698
|
+
spawn new threads at interpreter shutdown). In that case self.running
|
|
699
|
+
will be False after running this function.
|
|
700
|
+
"""
|
|
701
|
+
pid = os.getpid()
|
|
702
|
+
|
|
703
|
+
# is running on the right process
|
|
704
|
+
if self.running and self.pid == pid:
|
|
705
|
+
return
|
|
706
|
+
|
|
707
|
+
with self.lock:
|
|
708
|
+
# another thread may have tried to acquire the lock
|
|
709
|
+
# at the same time so it may start another thread
|
|
710
|
+
# make sure to check again before proceeding
|
|
711
|
+
if self.running and self.pid == pid:
|
|
712
|
+
return
|
|
713
|
+
|
|
714
|
+
self.pid = pid
|
|
715
|
+
self.running = True
|
|
716
|
+
|
|
717
|
+
# make sure the thread is a daemon here otherwise this
|
|
718
|
+
# can keep the application running after other threads
|
|
719
|
+
# have exited
|
|
720
|
+
self.thread = threading.Thread(name=self.name, target=self.run, daemon=True)
|
|
721
|
+
try:
|
|
722
|
+
self.thread.start()
|
|
723
|
+
except RuntimeError:
|
|
724
|
+
# Unfortunately at this point the interpreter is in a state that no
|
|
725
|
+
# longer allows us to spawn a thread and we have to bail.
|
|
726
|
+
self.running = False
|
|
727
|
+
self.thread = None
|
|
728
|
+
return
|
|
729
|
+
|
|
730
|
+
def run(self):
|
|
731
|
+
# type: () -> None
|
|
732
|
+
last = time.perf_counter()
|
|
733
|
+
|
|
734
|
+
while self.running:
|
|
735
|
+
self.sampler()
|
|
736
|
+
|
|
737
|
+
# some time may have elapsed since the last time
|
|
738
|
+
# we sampled, so we need to account for that and
|
|
739
|
+
# not sleep for too long
|
|
740
|
+
elapsed = time.perf_counter() - last
|
|
741
|
+
if elapsed < self.interval:
|
|
742
|
+
thread_sleep(self.interval - elapsed)
|
|
743
|
+
|
|
744
|
+
# after sleeping, make sure to take the current
|
|
745
|
+
# timestamp so we can use it next iteration
|
|
746
|
+
last = time.perf_counter()
|
|
747
|
+
|
|
748
|
+
|
|
749
|
+
class GeventScheduler(Scheduler):
|
|
750
|
+
"""
|
|
751
|
+
This scheduler is based on the thread scheduler but adapted to work with
|
|
752
|
+
gevent. When using gevent, it may monkey patch the threading modules
|
|
753
|
+
(`threading` and `_thread`). This results in the use of greenlets instead
|
|
754
|
+
of native threads.
|
|
755
|
+
|
|
756
|
+
This is an issue because the sampler CANNOT run in a greenlet because
|
|
757
|
+
1. Other greenlets doing sync work will prevent the sampler from running
|
|
758
|
+
2. The greenlet runs in the same thread as other greenlets so when taking
|
|
759
|
+
a sample, other greenlets will have been evicted from the thread. This
|
|
760
|
+
results in a sample containing only the sampler's code.
|
|
761
|
+
"""
|
|
762
|
+
|
|
763
|
+
mode = "gevent" # type: ProfilerMode
|
|
764
|
+
name = "sentry.profiler.GeventScheduler"
|
|
765
|
+
|
|
766
|
+
def __init__(self, frequency):
|
|
767
|
+
# type: (int) -> None
|
|
768
|
+
|
|
769
|
+
if ThreadPool is None:
|
|
770
|
+
raise ValueError("Profiler mode: {} is not available".format(self.mode))
|
|
771
|
+
|
|
772
|
+
super().__init__(frequency=frequency)
|
|
773
|
+
|
|
774
|
+
# used to signal to the thread that it should stop
|
|
775
|
+
self.running = False
|
|
776
|
+
self.thread = None # type: Optional[_ThreadPool]
|
|
777
|
+
self.pid = None # type: Optional[int]
|
|
778
|
+
|
|
779
|
+
# This intentionally uses the gevent patched threading.Lock.
|
|
780
|
+
# The lock will be required when first trying to start profiles
|
|
781
|
+
# as we need to spawn the profiler thread from the greenlets.
|
|
782
|
+
self.lock = threading.Lock()
|
|
783
|
+
|
|
784
|
+
def setup(self):
|
|
785
|
+
# type: () -> None
|
|
786
|
+
pass
|
|
787
|
+
|
|
788
|
+
def teardown(self):
|
|
789
|
+
# type: () -> None
|
|
790
|
+
if self.running:
|
|
791
|
+
self.running = False
|
|
792
|
+
if self.thread is not None:
|
|
793
|
+
self.thread.join()
|
|
794
|
+
|
|
795
|
+
def ensure_running(self):
|
|
796
|
+
# type: () -> None
|
|
797
|
+
pid = os.getpid()
|
|
798
|
+
|
|
799
|
+
# is running on the right process
|
|
800
|
+
if self.running and self.pid == pid:
|
|
801
|
+
return
|
|
802
|
+
|
|
803
|
+
with self.lock:
|
|
804
|
+
# another thread may have tried to acquire the lock
|
|
805
|
+
# at the same time so it may start another thread
|
|
806
|
+
# make sure to check again before proceeding
|
|
807
|
+
if self.running and self.pid == pid:
|
|
808
|
+
return
|
|
809
|
+
|
|
810
|
+
self.pid = pid
|
|
811
|
+
self.running = True
|
|
812
|
+
|
|
813
|
+
self.thread = ThreadPool(1) # type: ignore[misc]
|
|
814
|
+
try:
|
|
815
|
+
self.thread.spawn(self.run)
|
|
816
|
+
except RuntimeError:
|
|
817
|
+
# Unfortunately at this point the interpreter is in a state that no
|
|
818
|
+
# longer allows us to spawn a thread and we have to bail.
|
|
819
|
+
self.running = False
|
|
820
|
+
self.thread = None
|
|
821
|
+
return
|
|
822
|
+
|
|
823
|
+
def run(self):
|
|
824
|
+
# type: () -> None
|
|
825
|
+
last = time.perf_counter()
|
|
826
|
+
|
|
827
|
+
while self.running:
|
|
828
|
+
self.sampler()
|
|
829
|
+
|
|
830
|
+
# some time may have elapsed since the last time
|
|
831
|
+
# we sampled, so we need to account for that and
|
|
832
|
+
# not sleep for too long
|
|
833
|
+
elapsed = time.perf_counter() - last
|
|
834
|
+
if elapsed < self.interval:
|
|
835
|
+
thread_sleep(self.interval - elapsed)
|
|
836
|
+
|
|
837
|
+
# after sleeping, make sure to take the current
|
|
838
|
+
# timestamp so we can use it next iteration
|
|
839
|
+
last = time.perf_counter()
|