Skip to content

Commit b0db5ab

Browse files
committed
Fix issue with Flask instrumentation when a request spawn children threads and copie the request context
1 parent 7af87e1 commit b0db5ab

File tree

2 files changed

+10
-5
lines changed

2 files changed

+10
-5
lines changed

CHANGELOG.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
2626
([#1618](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/1618))
2727

2828
### Fixed
29-
29+
- Fix Flask instrumentation to only close the span if it was created by the same thread. `ValueError: generator already executing` ([#1654](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/1654))
3030
- Fix TortoiseORM instrumentation `AttributeError: type object 'Config' has no attribute 'title'`
3131
([#1575](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/1575))
3232
- Fix SQLAlchemy uninstrumentation

instrumentation/opentelemetry-instrumentation-flask/src/opentelemetry/instrumentation/flask/__init__.py

+9-4
Original file line numberDiff line numberDiff line change
@@ -238,8 +238,8 @@ def response_hook(span: Span, status: str, response_headers: List):
238238
API
239239
---
240240
"""
241-
242241
from logging import getLogger
242+
from threading import get_ident
243243
from time import time_ns
244244
from timeit import default_timer
245245
from typing import Collection
@@ -397,7 +397,10 @@ def _before_request():
397397

398398
activation = trace.use_span(span, end_on_exit=True)
399399
activation.__enter__() # pylint: disable=E1101
400-
flask_request_environ[_ENVIRON_ACTIVATION_KEY] = activation
400+
flask_request_environ[_ENVIRON_ACTIVATION_KEY] = (
401+
get_ident(),
402+
activation,
403+
)
401404
flask_request_environ[_ENVIRON_SPAN_KEY] = span
402405
flask_request_environ[_ENVIRON_TOKEN] = token
403406

@@ -436,8 +439,10 @@ def _teardown_request(exc):
436439
if excluded_urls and excluded_urls.url_disabled(flask.request.url):
437440
return
438441

439-
activation = flask.request.environ.get(_ENVIRON_ACTIVATION_KEY)
440-
if not activation:
442+
thread_id, activation = flask.request.environ.get(
443+
_ENVIRON_ACTIVATION_KEY
444+
)
445+
if not activation or thread_id != get_ident():
441446
# This request didn't start a span, maybe because it was created in
442447
# a way that doesn't run `before_request`, like when it is created
443448
# with `app.test_request_context`.

0 commit comments

Comments
 (0)