Skip to content

Commit

Permalink
Fix Django/Datadog integration with Spinach
Browse files Browse the repository at this point in the history
ddtrace used to be a Django app, which Spinach could look for to
know if it should use the Datadog integration.

Since ddtrace now recommends patching Django, Spinach has to adapt
to this new method to know if it should use the Datadog
integration.
  • Loading branch information
NicolasLM committed Mar 28, 2021
1 parent 7b8a495 commit d20a8ab
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 6 deletions.
23 changes: 21 additions & 2 deletions spinach/contrib/datadog.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,6 @@ def register_datadog(tracer=None, namespace: Optional[str]=None,
service: str='spinach'):
"""Register the Datadog integration.
Exceptions making jobs fail are sent to Sentry.
:param tracer: optionally use a custom ddtrace Tracer instead of the global
one.
:param namespace: optionally only register the Datadog integration for a
Expand Down Expand Up @@ -42,3 +40,24 @@ def job_failed(namespace, job, **kwargs):
def job_schedule_retry(namespace, job, **kwargs):
root_span = tracer.current_root_span()
root_span.set_traceback()


def register_datadog_if_module_patched(module: str, *args, **kwargs) -> bool:
"""Register the datadog integration if ddtrace is already used.
This can be used to enable datadog for Spinach only if datadog
is enabled for Django.
:param module: Name of the module that must already be patched
:return: boolean telling if the integration was registered
"""
try:
from ddtrace.monkey import get_patched_modules
except ImportError:
return False

if module not in get_patched_modules():
return False

register_datadog(*args, **kwargs)
return True
11 changes: 7 additions & 4 deletions spinach/contrib/spinachd/management/commands/spinach.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
from django.apps import apps
from django.core.management.base import BaseCommand
try:
from raven.contrib.django.models import client as raven_client
Expand All @@ -7,6 +6,7 @@

from spinach.const import DEFAULT_QUEUE, DEFAULT_WORKER_NUMBER
from spinach.contrib.sentry import register_sentry
from spinach.contrib.datadog import register_datadog_if_module_patched

from ...apps import spin

Expand Down Expand Up @@ -41,9 +41,12 @@ def handle(self, *args, **options):
if raven_client is not None:
register_sentry(raven_client, spin.namespace)

if apps.is_installed('ddtrace.contrib.django'):
from spinach.contrib.datadog import register_datadog
register_datadog(namespace=spin.namespace)
# Use the Datadog integration if Datadog is already used
# to trace Django.
register_datadog_if_module_patched(
'django',
namespance=spin.namespace
)

spin.start_workers(
number=options['threads'],
Expand Down

0 comments on commit d20a8ab

Please sign in to comment.