Skip to content

Commit

Permalink
feat: Detect interpreter in shutdown state on thread spawn (#2468)
Browse files Browse the repository at this point in the history
This detects if the interpreter is already in shutdown state and no longer spawns a background thread.

---------

Co-authored-by: Anton Pirker <anton.pirker@sentry.io>
  • Loading branch information
mitsuhiko and antonpirker committed Oct 30, 2023
1 parent 552017a commit e0d7bb7
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 8 deletions.
19 changes: 13 additions & 6 deletions sentry_sdk/metrics.py
Expand Up @@ -332,18 +332,27 @@ def __init__(
self._ensure_thread()

def _ensure_thread(self):
# type: (...) -> None
# type: (...) -> bool
"""For forking processes we might need to restart this thread.
This ensures that our process actually has that thread running.
"""
if not self._running:
return False
pid = os.getpid()
if self._flusher_pid == pid:
return
return True
with self._lock:
self._flusher_pid = pid
self._flusher = Thread(target=self._flush_loop)
self._flusher.daemon = True
self._flusher.start()
try:
self._flusher.start()
except RuntimeError:
# Unfortunately at this point the interpreter is in a start that no
# longer allows us to spawn a thread and we have to bail.
self._running = False
return False
return True

def _flush_loop(self):
# type: (...) -> None
Expand Down Expand Up @@ -400,9 +409,7 @@ def add(
timestamp=None, # type: Optional[float]
):
# type: (...) -> None
self._ensure_thread()

if self._flusher is None:
if not self._ensure_thread() or self._flusher is None:
return

if timestamp is None:
Expand Down
10 changes: 8 additions & 2 deletions sentry_sdk/worker.py
Expand Up @@ -67,8 +67,14 @@ def start(self):
target=self._target, name="raven-sentry.BackgroundWorker"
)
self._thread.daemon = True
self._thread.start()
self._thread_for_pid = os.getpid()
try:
self._thread.start()
self._thread_for_pid = os.getpid()
except RuntimeError:
# At this point we can no longer start because the interpreter
# is already shutting down. Sadly at this point we can no longer
# send out events.
self._thread = None

def kill(self):
# type: () -> None
Expand Down

0 comments on commit e0d7bb7

Please sign in to comment.