transaction_profiler.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809
  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. The MIT License (MIT)
  5. Copyright (c) 2014 Nylas
  6. Permission is hereby granted, free of charge, to any person obtaining a copy
  7. of this software and associated documentation files (the "Software"), to deal
  8. in the Software without restriction, including without limitation the rights
  9. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. copies of the Software, and to permit persons to whom the Software is
  11. furnished to do so, subject to the following conditions:
  12. The above copyright notice and this permission notice shall be included in all
  13. copies or substantial portions of the Software.
  14. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  20. SOFTWARE.
  21. """
  22. import atexit
  23. import os
  24. import platform
  25. import random
  26. import sys
  27. import threading
  28. import time
  29. import uuid
  30. import warnings
  31. from abc import ABC, abstractmethod
  32. from collections import deque
  33. import sentry_sdk
  34. from sentry_sdk._lru_cache import LRUCache
  35. from sentry_sdk.profiler.utils import (
  36. DEFAULT_SAMPLING_FREQUENCY,
  37. extract_stack,
  38. )
  39. from sentry_sdk.utils import (
  40. capture_internal_exception,
  41. capture_internal_exceptions,
  42. get_current_thread_meta,
  43. is_gevent,
  44. is_valid_sample_rate,
  45. logger,
  46. nanosecond_time,
  47. set_in_app_in_frames,
  48. )
  49. from typing import TYPE_CHECKING
  50. if TYPE_CHECKING:
  51. from typing import Any
  52. from typing import Callable
  53. from typing import Deque
  54. from typing import Dict
  55. from typing import List
  56. from typing import Optional
  57. from typing import Set
  58. from typing import Type
  59. from typing_extensions import TypedDict
  60. from sentry_sdk.profiler.utils import (
  61. ProcessedStack,
  62. ProcessedFrame,
  63. ProcessedThreadMetadata,
  64. FrameId,
  65. StackId,
  66. ThreadId,
  67. ExtractedSample,
  68. )
  69. from sentry_sdk._types import Event, SamplingContext, ProfilerMode
  70. ProcessedSample = TypedDict(
  71. "ProcessedSample",
  72. {
  73. "elapsed_since_start_ns": str,
  74. "thread_id": ThreadId,
  75. "stack_id": int,
  76. },
  77. )
  78. ProcessedProfile = TypedDict(
  79. "ProcessedProfile",
  80. {
  81. "frames": List[ProcessedFrame],
  82. "stacks": List[ProcessedStack],
  83. "samples": List[ProcessedSample],
  84. "thread_metadata": Dict[ThreadId, ProcessedThreadMetadata],
  85. },
  86. )
  87. try:
  88. from gevent.monkey import get_original
  89. from gevent.threadpool import ThreadPool as _ThreadPool
  90. ThreadPool: "Optional[Type[_ThreadPool]]" = _ThreadPool
  91. thread_sleep = get_original("time", "sleep")
  92. except ImportError:
  93. thread_sleep = time.sleep
  94. ThreadPool = None
  95. _scheduler: "Optional[Scheduler]" = None
  96. # The minimum number of unique samples that must exist in a profile to be
  97. # considered valid.
  98. PROFILE_MINIMUM_SAMPLES = 2
  99. def has_profiling_enabled(options: "Dict[str, Any]") -> bool:
  100. profiles_sampler = options["profiles_sampler"]
  101. if profiles_sampler is not None:
  102. return True
  103. profiles_sample_rate = options["profiles_sample_rate"]
  104. if profiles_sample_rate is not None and profiles_sample_rate > 0:
  105. return True
  106. profiles_sample_rate = options["_experiments"].get("profiles_sample_rate")
  107. if profiles_sample_rate is not None:
  108. logger.warning(
  109. "_experiments['profiles_sample_rate'] is deprecated. "
  110. "Please use the non-experimental profiles_sample_rate option "
  111. "directly."
  112. )
  113. if profiles_sample_rate > 0:
  114. return True
  115. return False
  116. def setup_profiler(options: "Dict[str, Any]") -> bool:
  117. global _scheduler
  118. if _scheduler is not None:
  119. logger.debug("[Profiling] Profiler is already setup")
  120. return False
  121. frequency = DEFAULT_SAMPLING_FREQUENCY
  122. if is_gevent():
  123. # If gevent has patched the threading modules then we cannot rely on
  124. # them to spawn a native thread for sampling.
  125. # Instead we default to the GeventScheduler which is capable of
  126. # spawning native threads within gevent.
  127. default_profiler_mode = GeventScheduler.mode
  128. else:
  129. default_profiler_mode = ThreadScheduler.mode
  130. if options.get("profiler_mode") is not None:
  131. profiler_mode = options["profiler_mode"]
  132. else:
  133. profiler_mode = options.get("_experiments", {}).get("profiler_mode")
  134. if profiler_mode is not None:
  135. logger.warning(
  136. "_experiments['profiler_mode'] is deprecated. Please use the "
  137. "non-experimental profiler_mode option directly."
  138. )
  139. profiler_mode = profiler_mode or default_profiler_mode
  140. if (
  141. profiler_mode == ThreadScheduler.mode
  142. # for legacy reasons, we'll keep supporting sleep mode for this scheduler
  143. or profiler_mode == "sleep"
  144. ):
  145. _scheduler = ThreadScheduler(frequency=frequency)
  146. elif profiler_mode == GeventScheduler.mode:
  147. _scheduler = GeventScheduler(frequency=frequency)
  148. else:
  149. raise ValueError("Unknown profiler mode: {}".format(profiler_mode))
  150. logger.debug(
  151. "[Profiling] Setting up profiler in {mode} mode".format(mode=_scheduler.mode)
  152. )
  153. _scheduler.setup()
  154. atexit.register(teardown_profiler)
  155. return True
  156. def teardown_profiler() -> None:
  157. global _scheduler
  158. if _scheduler is not None:
  159. _scheduler.teardown()
  160. _scheduler = None
  161. MAX_PROFILE_DURATION_NS = int(3e10) # 30 seconds
  162. class Profile:
  163. def __init__(
  164. self,
  165. sampled: "Optional[bool]",
  166. start_ns: int,
  167. hub: "Optional[sentry_sdk.Hub]" = None,
  168. scheduler: "Optional[Scheduler]" = None,
  169. ) -> None:
  170. self.scheduler = _scheduler if scheduler is None else scheduler
  171. self.event_id: str = uuid.uuid4().hex
  172. self.sampled: "Optional[bool]" = sampled
  173. # Various framework integrations are capable of overwriting the active thread id.
  174. # If it is set to `None` at the end of the profile, we fall back to the default.
  175. self._default_active_thread_id: int = get_current_thread_meta()[0] or 0
  176. self.active_thread_id: "Optional[int]" = None
  177. try:
  178. self.start_ns: int = start_ns
  179. except AttributeError:
  180. self.start_ns = 0
  181. self.stop_ns: int = 0
  182. self.active: bool = False
  183. self.indexed_frames: "Dict[FrameId, int]" = {}
  184. self.indexed_stacks: "Dict[StackId, int]" = {}
  185. self.frames: "List[ProcessedFrame]" = []
  186. self.stacks: "List[ProcessedStack]" = []
  187. self.samples: "List[ProcessedSample]" = []
  188. self.unique_samples = 0
  189. # Backwards compatibility with the old hub property
  190. self._hub: "Optional[sentry_sdk.Hub]" = None
  191. if hub is not None:
  192. self._hub = hub
  193. warnings.warn(
  194. "The `hub` parameter is deprecated. Please do not use it.",
  195. DeprecationWarning,
  196. stacklevel=2,
  197. )
  198. def update_active_thread_id(self) -> None:
  199. self.active_thread_id = get_current_thread_meta()[0]
  200. logger.debug(
  201. "[Profiling] updating active thread id to {tid}".format(
  202. tid=self.active_thread_id
  203. )
  204. )
  205. def _set_initial_sampling_decision(
  206. self, sampling_context: "SamplingContext"
  207. ) -> None:
  208. """
  209. Sets the profile's sampling decision according to the following
  210. precedence rules:
  211. 1. If the transaction to be profiled is not sampled, that decision
  212. will be used, regardless of anything else.
  213. 2. Use `profiles_sample_rate` to decide.
  214. """
  215. # The corresponding transaction was not sampled,
  216. # so don't generate a profile for it.
  217. if not self.sampled:
  218. logger.debug(
  219. "[Profiling] Discarding profile because transaction is discarded."
  220. )
  221. self.sampled = False
  222. return
  223. # The profiler hasn't been properly initialized.
  224. if self.scheduler is None:
  225. logger.debug(
  226. "[Profiling] Discarding profile because profiler was not started."
  227. )
  228. self.sampled = False
  229. return
  230. client = sentry_sdk.get_client()
  231. if not client.is_active():
  232. self.sampled = False
  233. return
  234. options = client.options
  235. if callable(options.get("profiles_sampler")):
  236. sample_rate = options["profiles_sampler"](sampling_context)
  237. elif options["profiles_sample_rate"] is not None:
  238. sample_rate = options["profiles_sample_rate"]
  239. else:
  240. sample_rate = options["_experiments"].get("profiles_sample_rate")
  241. # The profiles_sample_rate option was not set, so profiling
  242. # was never enabled.
  243. if sample_rate is None:
  244. logger.debug(
  245. "[Profiling] Discarding profile because profiling was not enabled."
  246. )
  247. self.sampled = False
  248. return
  249. if not is_valid_sample_rate(sample_rate, source="Profiling"):
  250. logger.warning(
  251. "[Profiling] Discarding profile because of invalid sample rate."
  252. )
  253. self.sampled = False
  254. return
  255. # Now we roll the dice. random.random is inclusive of 0, but not of 1,
  256. # so strict < is safe here. In case sample_rate is a boolean, cast it
  257. # to a float (True becomes 1.0 and False becomes 0.0)
  258. self.sampled = random.random() < float(sample_rate)
  259. if self.sampled:
  260. logger.debug("[Profiling] Initializing profile")
  261. else:
  262. logger.debug(
  263. "[Profiling] Discarding profile because it's not included in the random sample (sample rate = {sample_rate})".format(
  264. sample_rate=float(sample_rate)
  265. )
  266. )
  267. def start(self) -> None:
  268. if not self.sampled or self.active:
  269. return
  270. assert self.scheduler, "No scheduler specified"
  271. logger.debug("[Profiling] Starting profile")
  272. self.active = True
  273. if not self.start_ns:
  274. self.start_ns = nanosecond_time()
  275. self.scheduler.start_profiling(self)
  276. def stop(self) -> None:
  277. if not self.sampled or not self.active:
  278. return
  279. assert self.scheduler, "No scheduler specified"
  280. logger.debug("[Profiling] Stopping profile")
  281. self.active = False
  282. self.stop_ns = nanosecond_time()
  283. def __enter__(self) -> "Profile":
  284. scope = sentry_sdk.get_isolation_scope()
  285. old_profile = scope.profile
  286. scope.profile = self
  287. self._context_manager_state = (scope, old_profile)
  288. self.start()
  289. return self
  290. def __exit__(
  291. self, ty: "Optional[Any]", value: "Optional[Any]", tb: "Optional[Any]"
  292. ) -> None:
  293. with capture_internal_exceptions():
  294. self.stop()
  295. scope, old_profile = self._context_manager_state
  296. del self._context_manager_state
  297. scope.profile = old_profile
  298. def write(self, ts: int, sample: "ExtractedSample") -> None:
  299. if not self.active:
  300. return
  301. if ts < self.start_ns:
  302. return
  303. offset = ts - self.start_ns
  304. if offset > MAX_PROFILE_DURATION_NS:
  305. self.stop()
  306. return
  307. self.unique_samples += 1
  308. elapsed_since_start_ns = str(offset)
  309. for tid, (stack_id, frame_ids, frames) in sample:
  310. try:
  311. # Check if the stack is indexed first, this lets us skip
  312. # indexing frames if it's not necessary
  313. if stack_id not in self.indexed_stacks:
  314. for i, frame_id in enumerate(frame_ids):
  315. if frame_id not in self.indexed_frames:
  316. self.indexed_frames[frame_id] = len(self.indexed_frames)
  317. self.frames.append(frames[i])
  318. self.indexed_stacks[stack_id] = len(self.indexed_stacks)
  319. self.stacks.append(
  320. [self.indexed_frames[frame_id] for frame_id in frame_ids]
  321. )
  322. self.samples.append(
  323. {
  324. "elapsed_since_start_ns": elapsed_since_start_ns,
  325. "thread_id": tid,
  326. "stack_id": self.indexed_stacks[stack_id],
  327. }
  328. )
  329. except AttributeError:
  330. # For some reason, the frame we get doesn't have certain attributes.
  331. # When this happens, we abandon the current sample as it's bad.
  332. capture_internal_exception(sys.exc_info())
  333. def process(self) -> "ProcessedProfile":
  334. # This collects the thread metadata at the end of a profile. Doing it
  335. # this way means that any threads that terminate before the profile ends
  336. # will not have any metadata associated with it.
  337. thread_metadata: "Dict[str, ProcessedThreadMetadata]" = {
  338. str(thread.ident): {
  339. "name": str(thread.name),
  340. }
  341. for thread in threading.enumerate()
  342. }
  343. return {
  344. "frames": self.frames,
  345. "stacks": self.stacks,
  346. "samples": self.samples,
  347. "thread_metadata": thread_metadata,
  348. }
  349. def to_json(
  350. self, event_opt: "Event", options: "Dict[str, Any]"
  351. ) -> "Dict[str, Any]":
  352. profile = self.process()
  353. set_in_app_in_frames(
  354. profile["frames"],
  355. options["in_app_exclude"],
  356. options["in_app_include"],
  357. options["project_root"],
  358. )
  359. return {
  360. "environment": event_opt.get("environment"),
  361. "event_id": self.event_id,
  362. "platform": "python",
  363. "profile": profile,
  364. "release": event_opt.get("release", ""),
  365. "timestamp": event_opt["start_timestamp"],
  366. "version": "1",
  367. "device": {
  368. "architecture": platform.machine(),
  369. },
  370. "os": {
  371. "name": platform.system(),
  372. "version": platform.release(),
  373. },
  374. "runtime": {
  375. "name": platform.python_implementation(),
  376. "version": platform.python_version(),
  377. },
  378. "transactions": [
  379. {
  380. "id": event_opt["event_id"],
  381. "name": event_opt["transaction"],
  382. # we start the transaction before the profile and this is
  383. # the transaction start time relative to the profile, so we
  384. # hardcode it to 0 until we can start the profile before
  385. "relative_start_ns": "0",
  386. # use the duration of the profile instead of the transaction
  387. # because we end the transaction after the profile
  388. "relative_end_ns": str(self.stop_ns - self.start_ns),
  389. "trace_id": event_opt["contexts"]["trace"]["trace_id"],
  390. "active_thread_id": str(
  391. self._default_active_thread_id
  392. if self.active_thread_id is None
  393. else self.active_thread_id
  394. ),
  395. }
  396. ],
  397. }
  398. def valid(self) -> bool:
  399. client = sentry_sdk.get_client()
  400. if not client.is_active():
  401. return False
  402. if not has_profiling_enabled(client.options):
  403. return False
  404. if self.sampled is None or not self.sampled:
  405. if client.transport:
  406. client.transport.record_lost_event(
  407. "sample_rate", data_category="profile"
  408. )
  409. return False
  410. if self.unique_samples < PROFILE_MINIMUM_SAMPLES:
  411. if client.transport:
  412. client.transport.record_lost_event(
  413. "insufficient_data", data_category="profile"
  414. )
  415. logger.debug("[Profiling] Discarding profile because insufficient samples.")
  416. return False
  417. return True
  418. @property
  419. def hub(self) -> "Optional[sentry_sdk.Hub]":
  420. warnings.warn(
  421. "The `hub` attribute is deprecated. Please do not access it.",
  422. DeprecationWarning,
  423. stacklevel=2,
  424. )
  425. return self._hub
  426. @hub.setter
  427. def hub(self, value: "Optional[sentry_sdk.Hub]") -> None:
  428. warnings.warn(
  429. "The `hub` attribute is deprecated. Please do not set it.",
  430. DeprecationWarning,
  431. stacklevel=2,
  432. )
  433. self._hub = value
  434. class Scheduler(ABC):
  435. mode: "ProfilerMode" = "unknown"
  436. def __init__(self, frequency: int) -> None:
  437. self.interval = 1.0 / frequency
  438. self.sampler = self.make_sampler()
  439. # cap the number of new profiles at any time so it does not grow infinitely
  440. self.new_profiles: "Deque[Profile]" = deque(maxlen=128)
  441. self.active_profiles: "Set[Profile]" = set()
  442. def __enter__(self) -> "Scheduler":
  443. self.setup()
  444. return self
  445. def __exit__(
  446. self, ty: "Optional[Any]", value: "Optional[Any]", tb: "Optional[Any]"
  447. ) -> None:
  448. self.teardown()
  449. @abstractmethod
  450. def setup(self) -> None:
  451. pass
  452. @abstractmethod
  453. def teardown(self) -> None:
  454. pass
  455. def ensure_running(self) -> None:
  456. """
  457. Ensure the scheduler is running. By default, this method is a no-op.
  458. The method should be overridden by any implementation for which it is
  459. relevant.
  460. """
  461. return None
  462. def start_profiling(self, profile: "Profile") -> None:
  463. self.ensure_running()
  464. self.new_profiles.append(profile)
  465. def make_sampler(self) -> "Callable[..., None]":
  466. cwd = os.getcwd()
  467. cache = LRUCache(max_size=256)
  468. def _sample_stack(*args: "Any", **kwargs: "Any") -> None:
  469. """
  470. Take a sample of the stack on all the threads in the process.
  471. This should be called at a regular interval to collect samples.
  472. """
  473. # no profiles taking place, so we can stop early
  474. if not self.new_profiles and not self.active_profiles:
  475. # make sure to clear the cache if we're not profiling so we dont
  476. # keep a reference to the last stack of frames around
  477. return
  478. # This is the number of profiles we want to pop off.
  479. # It's possible another thread adds a new profile to
  480. # the list and we spend longer than we want inside
  481. # the loop below.
  482. #
  483. # Also make sure to set this value before extracting
  484. # frames so we do not write to any new profiles that
  485. # were started after this point.
  486. new_profiles = len(self.new_profiles)
  487. now = nanosecond_time()
  488. try:
  489. sample = [
  490. (str(tid), extract_stack(frame, cache, cwd))
  491. for tid, frame in sys._current_frames().items()
  492. ]
  493. except AttributeError:
  494. # For some reason, the frame we get doesn't have certain attributes.
  495. # When this happens, we abandon the current sample as it's bad.
  496. capture_internal_exception(sys.exc_info())
  497. return
  498. # Move the new profiles into the active_profiles set.
  499. #
  500. # We cannot directly add the to active_profiles set
  501. # in `start_profiling` because it is called from other
  502. # threads which can cause a RuntimeError when it the
  503. # set sizes changes during iteration without a lock.
  504. #
  505. # We also want to avoid using a lock here so threads
  506. # that are starting profiles are not blocked until it
  507. # can acquire the lock.
  508. for _ in range(new_profiles):
  509. self.active_profiles.add(self.new_profiles.popleft())
  510. inactive_profiles = []
  511. for profile in self.active_profiles:
  512. if profile.active:
  513. profile.write(now, sample)
  514. else:
  515. # If a profile is marked inactive, we buffer it
  516. # to `inactive_profiles` so it can be removed.
  517. # We cannot remove it here as it would result
  518. # in a RuntimeError.
  519. inactive_profiles.append(profile)
  520. for profile in inactive_profiles:
  521. self.active_profiles.remove(profile)
  522. return _sample_stack
  523. class ThreadScheduler(Scheduler):
  524. """
  525. This scheduler is based on running a daemon thread that will call
  526. the sampler at a regular interval.
  527. """
  528. mode: "ProfilerMode" = "thread"
  529. name = "sentry.profiler.ThreadScheduler"
  530. def __init__(self, frequency: int) -> None:
  531. super().__init__(frequency=frequency)
  532. # used to signal to the thread that it should stop
  533. self.running = False
  534. self.thread: "Optional[threading.Thread]" = None
  535. self.pid: "Optional[int]" = None
  536. self.lock = threading.Lock()
  537. def setup(self) -> None:
  538. pass
  539. def teardown(self) -> None:
  540. if self.running:
  541. self.running = False
  542. if self.thread is not None:
  543. self.thread.join()
  544. def ensure_running(self) -> None:
  545. """
  546. Check that the profiler has an active thread to run in, and start one if
  547. that's not the case.
  548. Note that this might fail (e.g. in Python 3.12 it's not possible to
  549. spawn new threads at interpreter shutdown). In that case self.running
  550. will be False after running this function.
  551. """
  552. pid = os.getpid()
  553. # is running on the right process
  554. if self.running and self.pid == pid:
  555. return
  556. with self.lock:
  557. # another thread may have tried to acquire the lock
  558. # at the same time so it may start another thread
  559. # make sure to check again before proceeding
  560. if self.running and self.pid == pid:
  561. return
  562. self.pid = pid
  563. self.running = True
  564. # make sure the thread is a daemon here otherwise this
  565. # can keep the application running after other threads
  566. # have exited
  567. self.thread = threading.Thread(name=self.name, target=self.run, daemon=True)
  568. try:
  569. self.thread.start()
  570. except RuntimeError:
  571. # Unfortunately at this point the interpreter is in a state that no
  572. # longer allows us to spawn a thread and we have to bail.
  573. self.running = False
  574. self.thread = None
  575. return
  576. def run(self) -> None:
  577. last = time.perf_counter()
  578. while self.running:
  579. self.sampler()
  580. # some time may have elapsed since the last time
  581. # we sampled, so we need to account for that and
  582. # not sleep for too long
  583. elapsed = time.perf_counter() - last
  584. if elapsed < self.interval:
  585. thread_sleep(self.interval - elapsed)
  586. # after sleeping, make sure to take the current
  587. # timestamp so we can use it next iteration
  588. last = time.perf_counter()
  589. class GeventScheduler(Scheduler):
  590. """
  591. This scheduler is based on the thread scheduler but adapted to work with
  592. gevent. When using gevent, it may monkey patch the threading modules
  593. (`threading` and `_thread`). This results in the use of greenlets instead
  594. of native threads.
  595. This is an issue because the sampler CANNOT run in a greenlet because
  596. 1. Other greenlets doing sync work will prevent the sampler from running
  597. 2. The greenlet runs in the same thread as other greenlets so when taking
  598. a sample, other greenlets will have been evicted from the thread. This
  599. results in a sample containing only the sampler's code.
  600. """
  601. mode: "ProfilerMode" = "gevent"
  602. name = "sentry.profiler.GeventScheduler"
  603. def __init__(self, frequency: int) -> None:
  604. if ThreadPool is None:
  605. raise ValueError("Profiler mode: {} is not available".format(self.mode))
  606. super().__init__(frequency=frequency)
  607. # used to signal to the thread that it should stop
  608. self.running = False
  609. self.thread: "Optional[_ThreadPool]" = None
  610. self.pid: "Optional[int]" = None
  611. # This intentionally uses the gevent patched threading.Lock.
  612. # The lock will be required when first trying to start profiles
  613. # as we need to spawn the profiler thread from the greenlets.
  614. self.lock = threading.Lock()
  615. def setup(self) -> None:
  616. pass
  617. def teardown(self) -> None:
  618. if self.running:
  619. self.running = False
  620. if self.thread is not None:
  621. self.thread.join()
  622. def ensure_running(self) -> None:
  623. pid = os.getpid()
  624. # is running on the right process
  625. if self.running and self.pid == pid:
  626. return
  627. with self.lock:
  628. # another thread may have tried to acquire the lock
  629. # at the same time so it may start another thread
  630. # make sure to check again before proceeding
  631. if self.running and self.pid == pid:
  632. return
  633. self.pid = pid
  634. self.running = True
  635. self.thread = ThreadPool(1) # type: ignore[misc]
  636. try:
  637. self.thread.spawn(self.run)
  638. except RuntimeError:
  639. # Unfortunately at this point the interpreter is in a state that no
  640. # longer allows us to spawn a thread and we have to bail.
  641. self.running = False
  642. self.thread = None
  643. return
  644. def run(self) -> None:
  645. last = time.perf_counter()
  646. while self.running:
  647. self.sampler()
  648. # some time may have elapsed since the last time
  649. # we sampled, so we need to account for that and
  650. # not sleep for too long
  651. elapsed = time.perf_counter() - last
  652. if elapsed < self.interval:
  653. thread_sleep(self.interval - elapsed)
  654. # after sleeping, make sure to take the current
  655. # timestamp so we can use it next iteration
  656. last = time.perf_counter()