Skip to content

Commit

Permalink
Fix issue on older celery versions
Browse files Browse the repository at this point in the history
  • Loading branch information
TimPansino committed Apr 9, 2024
1 parent 2d66b24 commit dd87bce
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 6 deletions.
8 changes: 6 additions & 2 deletions newrelic/hooks/application_celery.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,11 @@ def _application():
with BackgroundTask(_application(), _name, "Celery", source=instance) as transaction:
# Attempt to grab distributed tracing headers
try:
headers = wrapped.request.headers
# Headers on earlier versions of Celery may end up as attributes
# on the request context instead of as custom headers. Handler this
# by defaulting to using vars() if headers is not available
headers = getattr(wrapped.request, "headers", None) or vars(wrapped.request)

settings = transaction.settings
if headers is not None and settings is not None:
if settings.distributed_tracing.enabled:
Expand Down Expand Up @@ -179,7 +183,7 @@ def wrap_Celery_send_task(wrapped, instance, args, kwargs):
if dt_headers:
if "headers" not in kwargs or not original_headers:
kwargs["headers"] = dict(dt_headers)
elif hasattr(original_headers, "items"):
else:
kwargs["headers"] = dt_headers = dict(dt_headers)
dt_headers.update(dict(original_headers))

Expand Down
11 changes: 7 additions & 4 deletions tests/application_celery/test_celery.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,8 +78,8 @@ def test_celery_tasks_ignore_transaction():
No transaction is recorded, due to the call to ignore_transaction(),
so no validation fixture is used. The purpose of this test is to make
sure the agent doesn't throw an error.
"""

add_result = add(1, 2)
assert add_result == 3

Expand All @@ -99,8 +99,8 @@ def test_celery_tasks_end_transaction():
"""
Only functions that run before the call to end_of_transaction() are
included in the transaction.
"""

add_result = add(1, 2)
assert add_result == 3

Expand All @@ -119,7 +119,10 @@ def test_celery_tasks_end_transaction():
@validate_transaction_count(1)
@validate_code_level_metrics("_target_application", "nested_add")
def test_celery_nested_tasks():
""" """

"""
Celery tasks run inside other celery tasks should not start a new transactions,
and should create a function trace instead.
"""

add_result = nested_add(1, 2)
assert add_result == 3

0 comments on commit dd87bce

Please sign in to comment.