Skip to content

Openverse is a search engine for openly-licensed media. This monorepo includes all application code.

Fix Sentry configuration for multiprocessing environment (#2506)

sarayourfriend08bb0317e111
diff --git a/ingestion_server/ingestion_server/api.py b/ingestion_server/ingestion_server/api.py
index 68d606e0d..c99f12f66 100644
--- a/ingestion_server/ingestion_server/api.py
+++ b/ingestion_server/ingestion_server/api.py
@@ -160,6 +160,7 @@ class TaskResource(BaseTaskResource):
active_workers = Value("i", int(False))
is_bad_request = Value("i", 0)
+ task_sentry_hub = sentry_sdk.Hub(sentry_sdk.Hub.current)
task = Process(
target=perform_task,
kwargs={
@@ -178,6 +179,7 @@ class TaskResource(BaseTaskResource):
"destination_index_suffix": destination_index_suffix,
"alias": alias,
"force_delete": force_delete,
+ "sentry_hub": task_sentry_hub,
},
)
task.start()
diff --git a/ingestion_server/ingestion_server/tasks.py b/ingestion_server/ingestion_server/tasks.py
index 2ee56c6d6..10e7cd53b 100644
--- a/ingestion_server/ingestion_server/tasks.py
+++ b/ingestion_server/ingestion_server/tasks.py
@@ -3,8 +3,11 @@
import datetime
import logging
from enum import Enum, auto
+from functools import wraps
from multiprocessing import Value
+import sentry_sdk
+
from ingestion_server import slack
from ingestion_server.constants.media_types import MediaType
from ingestion_server.es_helpers import elasticsearch_connect
@@ -153,6 +156,47 @@ class TaskTracker:
return {"task_id": task_id} | self.serialize_task_info(task_info)
+def _with_sentry(fn):
+ """
+ Wrap the decorated function for Sentry multiprocessing.
+
+ Convenience function to wrap ``perform_task`` in such a way
+ to extract the ``sentry_hub`` kwarg passed by ``api.py``, send
+ exceptions to Sentry, and fully flush the client's Sentry
+ queue before the worker exits.
+
+ We cannot use the convenient ``ThreadingIntegration`` because it
+ does not support ``multiprocessing``, only the legacy ``threading``
+ module (we use ``multiprocessing``)
+ """
+
+ @wraps(fn)
+ def fn_with_sentry(*args, **kwargs):
+ hub = kwargs.pop("sentry_hub")
+ with hub:
+ try:
+ result = fn(*args, **kwargs)
+ except Exception as exc:
+ result = None
+ logging.error(exc, exc_info=exc)
+ sentry_sdk.capture_exception(exc)
+
+ client = hub.client
+ if client is not None:
+ # Sentry does not send events right away (it handles messages async)
+ # and because the task finishing will shut down the worker thread
+ # we need to flush the client before exiting the function.
+ # ``client.flush`` will block until all messages in Sentry's queue are sent.
+ # We do this _outside_ the try/except so that _anything_ passed to sentry
+ # (like messages, etc) also get sent before the worker thread is closed.
+ client.flush(timeout=5)
+
+ return result
+
+ return fn_with_sentry
+
+
+@_with_sentry
def perform_task(
task_id: str,
model: MediaType,