Skip to content

feat: Detect interpreter in shutdown state on thread spawn #2468

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Oct 30, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 13 additions & 6 deletions sentry_sdk/metrics.py
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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