Skip to content

Commit e0d7bb7

Browse files
feat: Detect interpreter in shutdown state on thread spawn (#2468)
This detects if the interpreter is already in shutdown state and no longer spawns a background thread. --------- Co-authored-by: Anton Pirker <[email protected]>
1 parent 552017a commit e0d7bb7

File tree

2 files changed

+21
-8
lines changed

2 files changed

+21
-8
lines changed

sentry_sdk/metrics.py

+13-6
Original file line numberDiff line numberDiff line change
@@ -332,18 +332,27 @@ def __init__(
332332
self._ensure_thread()
333333

334334
def _ensure_thread(self):
335-
# type: (...) -> None
335+
# type: (...) -> bool
336336
"""For forking processes we might need to restart this thread.
337337
This ensures that our process actually has that thread running.
338338
"""
339+
if not self._running:
340+
return False
339341
pid = os.getpid()
340342
if self._flusher_pid == pid:
341-
return
343+
return True
342344
with self._lock:
343345
self._flusher_pid = pid
344346
self._flusher = Thread(target=self._flush_loop)
345347
self._flusher.daemon = True
346-
self._flusher.start()
348+
try:
349+
self._flusher.start()
350+
except RuntimeError:
351+
# Unfortunately at this point the interpreter is in a start that no
352+
# longer allows us to spawn a thread and we have to bail.
353+
self._running = False
354+
return False
355+
return True
347356

348357
def _flush_loop(self):
349358
# type: (...) -> None
@@ -400,9 +409,7 @@ def add(
400409
timestamp=None, # type: Optional[float]
401410
):
402411
# type: (...) -> None
403-
self._ensure_thread()
404-
405-
if self._flusher is None:
412+
if not self._ensure_thread() or self._flusher is None:
406413
return
407414

408415
if timestamp is None:

sentry_sdk/worker.py

+8-2
Original file line numberDiff line numberDiff line change
@@ -67,8 +67,14 @@ def start(self):
6767
target=self._target, name="raven-sentry.BackgroundWorker"
6868
)
6969
self._thread.daemon = True
70-
self._thread.start()
71-
self._thread_for_pid = os.getpid()
70+
try:
71+
self._thread.start()
72+
self._thread_for_pid = os.getpid()
73+
except RuntimeError:
74+
# At this point we can no longer start because the interpreter
75+
# is already shutting down. Sadly at this point we can no longer
76+
# send out events.
77+
self._thread = None
7278

7379
def kill(self):
7480
# type: () -> None

0 commit comments

Comments
 (0)