Skip to content
Open
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
78 changes: 2 additions & 76 deletions sentry_sdk/_batcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,10 @@
import random
import threading
import weakref
from datetime import datetime, timezone
from typing import TYPE_CHECKING, Generic, TypeVar

from sentry_sdk.envelope import Envelope, Item, PayloadRef
from sentry_sdk.utils import capture_internal_exceptions, format_timestamp
from sentry_sdk.utils import capture_internal_exceptions

if TYPE_CHECKING:
from typing import Any, Callable, Optional
Expand All @@ -32,7 +31,6 @@ def __init__(
self._capture_func = capture_func
self._record_lost_func = record_lost_func
self._running = True
self._lock = threading.Lock()
self._active: "threading.local" = threading.local()

self._flush_event: "threading.Event" = threading.Event()
Expand All @@ -54,44 +52,11 @@ def _reset_in_child() -> None:
def _reset_thread_state(self) -> None:
self._buffer = []
self._running = True
self._lock = threading.Lock()
self._active = threading.local()
self._flush_event = threading.Event()
self._flusher = None
self._flusher_pid = None

def _ensure_thread(self) -> 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 True

with self._lock:
# Recheck to make sure another thread didn't get here and start the
# the flusher in the meantime
if self._flusher_pid == pid:
return True

self._flusher_pid = pid

self._flusher = threading.Thread(target=self._flush_loop)
self._flusher.daemon = True

try:
self._flusher.start()
except RuntimeError:
# Unfortunately at this point the interpreter is in a state 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) -> None:
# Mark the flush-loop thread as active for its entire lifetime so
# that any re-entrant add() triggered by GC warnings during wait(),
Expand All @@ -109,34 +74,6 @@ def _flush_loop(self) -> None:
with capture_internal_exceptions():
self._flush()

def add(self, item: "T") -> None:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would be good to leave a stub for add() here so that the base class advertises it as part of the batcher "protocol"

# Bail out if the current thread is already executing batcher code.
# This prevents deadlocks when code running inside the batcher (e.g.
# _add_to_envelope during flush, or _flush_event.wait/set) triggers
# a GC-emitted warning that routes back through the logging
# integration into add().
if getattr(self._active, "flag", False):
return None

self._active.flag = True
try:
if not self._ensure_thread() or self._flusher is None:
return None

with self._lock:
dropped = len(self._buffer) >= self.MAX_BEFORE_DROP
if not dropped:
self._buffer.append(item)
if len(self._buffer) >= self.MAX_BEFORE_FLUSH:
self._flush_event.set()

# Record the loss outside of the lock, since this might involve
# serializing the item to report lost bytes
if dropped:
self._record_lost(item)
finally:
self._active.flag = False

def kill(self) -> None:
if self._flusher is None:
return
Expand Down Expand Up @@ -173,18 +110,7 @@ def _add_to_envelope(self, envelope: "Envelope") -> None:
envelope.add_item(self._to_envelope_item(self._buffer))

def _flush(self) -> "Optional[Envelope]":
envelope = Envelope(
headers={"sent_at": format_timestamp(datetime.now(timezone.utc))}
)
with self._lock:
if len(self._buffer) == 0:
return None

self._add_to_envelope(envelope)
self._buffer.clear()

self._capture_func(envelope)
return envelope
raise NotImplementedError

def _record_lost(self, item: "T") -> None:
envelope_item = None
Expand Down
94 changes: 92 additions & 2 deletions sentry_sdk/_log_batcher.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
import os
import threading
from datetime import datetime, timezone
from typing import TYPE_CHECKING

from sentry_sdk._batcher import Batcher
from sentry_sdk.utils import serialize_attribute
from sentry_sdk.envelope import Envelope
from sentry_sdk.utils import format_timestamp, serialize_attribute

if TYPE_CHECKING:
from typing import Any
from typing import Any, Callable, Optional

from sentry_sdk._types import Log

Expand All @@ -18,6 +22,92 @@ class LogBatcher(Batcher["Log"]):
CLIENT_REPORT_TYPE = "log_item"
CONTENT_TYPE = "application/vnd.sentry.items.log+json"

def __init__(
self,
capture_func: "Callable[[Envelope], None]",
record_lost_func: "Callable[..., None]",
) -> None:
super().__init__(capture_func, record_lost_func)
self._lock = threading.Lock()

def _reset_thread_state(self) -> None:
super()._reset_thread_state()
self._lock = threading.Lock()

def _ensure_thread(self) -> 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 True

with self._lock:
# Recheck to make sure another thread didn't get here and start the
# the flusher in the meantime
if self._flusher_pid == pid:
return True

self._flusher_pid = pid

self._flusher = threading.Thread(target=self._flush_loop)
self._flusher.daemon = True

try:
self._flusher.start()
except RuntimeError:
# Unfortunately at this point the interpreter is in a state that no
# longer allows us to spawn a thread and we have to bail.
self._running = False
return False

return True

def add(self, item: "Log") -> None:
# Bail out if the current thread is already executing batcher code.
# This prevents deadlocks when code running inside the batcher (e.g.
# _add_to_envelope during flush, or _flush_event.wait/set) triggers
# a GC-emitted warning that routes back through the logging
# integration into add().
if getattr(self._active, "flag", False):
return None

self._active.flag = True
try:
if not self._ensure_thread() or self._flusher is None:
return None

with self._lock:
dropped = len(self._buffer) >= self.MAX_BEFORE_DROP
if not dropped:
self._buffer.append(item)
if len(self._buffer) >= self.MAX_BEFORE_FLUSH:
self._flush_event.set()

# Record the loss outside of the lock, since this might involve
# serializing the item to report lost bytes
if dropped:
self._record_lost(item)
finally:
self._active.flag = False

def _flush(self) -> "Optional[Envelope]":
envelope = Envelope(
headers={"sent_at": format_timestamp(datetime.now(timezone.utc))}
)
with self._lock:
if len(self._buffer) == 0:
return None

self._add_to_envelope(envelope)
self._buffer.clear()

self._capture_func(envelope)
return envelope

@staticmethod
def _to_transport_format(item: "Log") -> "Any":
if "sentry.severity_number" not in item["attributes"]:
Expand Down
94 changes: 92 additions & 2 deletions sentry_sdk/_metrics_batcher.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
import os
import threading
from datetime import datetime, timezone
from typing import TYPE_CHECKING

from sentry_sdk._batcher import Batcher
from sentry_sdk.utils import serialize_attribute
from sentry_sdk.envelope import Envelope
from sentry_sdk.utils import format_timestamp, serialize_attribute

if TYPE_CHECKING:
from typing import Any
from typing import Any, Callable, Optional

from sentry_sdk._types import Metric

Expand All @@ -18,6 +22,92 @@ class MetricsBatcher(Batcher["Metric"]):
CLIENT_REPORT_TYPE = "trace_metric"
CONTENT_TYPE = "application/vnd.sentry.items.trace-metric+json"

def __init__(
self,
capture_func: "Callable[[Envelope], None]",
record_lost_func: "Callable[..., None]",
) -> None:
super().__init__(capture_func, record_lost_func)
self._lock = threading.Lock()

def _reset_thread_state(self) -> None:
super()._reset_thread_state()
self._lock = threading.Lock()

def _ensure_thread(self) -> 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 True

with self._lock:
# Recheck to make sure another thread didn't get here and start the
# the flusher in the meantime
if self._flusher_pid == pid:
return True

self._flusher_pid = pid

self._flusher = threading.Thread(target=self._flush_loop)
self._flusher.daemon = True

try:
self._flusher.start()
except RuntimeError:
# Unfortunately at this point the interpreter is in a state that no
# longer allows us to spawn a thread and we have to bail.
self._running = False
return False

return True

def add(self, item: "Metric") -> None:
# Bail out if the current thread is already executing batcher code.
# This prevents deadlocks when code running inside the batcher (e.g.
# _add_to_envelope during flush, or _flush_event.wait/set) triggers
# a GC-emitted warning that routes back through the logging
# integration into add().
if getattr(self._active, "flag", False):
return None

self._active.flag = True
try:
if not self._ensure_thread() or self._flusher is None:
return None

with self._lock:
dropped = len(self._buffer) >= self.MAX_BEFORE_DROP
if not dropped:
self._buffer.append(item)
if len(self._buffer) >= self.MAX_BEFORE_FLUSH:
self._flush_event.set()

# Record the loss outside of the lock, since this might involve
# serializing the item to report lost bytes
if dropped:
self._record_lost(item)
finally:
self._active.flag = False

def _flush(self) -> "Optional[Envelope]":
envelope = Envelope(
headers={"sent_at": format_timestamp(datetime.now(timezone.utc))}
)
with self._lock:
if len(self._buffer) == 0:
return None

self._add_to_envelope(envelope)
self._buffer.clear()

self._capture_func(envelope)
return envelope

@staticmethod
def _to_transport_format(item: "Metric") -> "Any":
res = {
Expand Down
32 changes: 32 additions & 0 deletions sentry_sdk/_span_batcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,38 @@ def _reset_thread_state(self) -> None:
self._flusher = None
self._flusher_pid = None

def _ensure_thread(self) -> 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 True

with self._lock:
# Recheck to make sure another thread didn't get here and start the
# the flusher in the meantime
if self._flusher_pid == pid:
return True

self._flusher_pid = pid

self._flusher = threading.Thread(target=self._flush_loop)
self._flusher.daemon = True

try:
self._flusher.start()
except RuntimeError:
# Unfortunately at this point the interpreter is in a state 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) -> None:
self._active.flag = True
while self._running:
Expand Down
Loading