Skip to content

Commit a71b838

Browse files
committed
sqlalchemy: make sqlalchemy thread safe
1 parent 2fd68a2 commit a71b838

File tree

2 files changed

+31
-13
lines changed
  • instrumentation/opentelemetry-instrumentation-sqlalchemy/src/opentelemetry/instrumentation/sqlalchemy

2 files changed

+31
-13
lines changed

CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
1010
- Remove `component` span attribute in instrumentations.
1111
`opentelemetry-instrumentation-aiopg`, `opentelemetry-instrumentation-dbapi` Remove unused `database_type` parameter from `trace_integration` function.
1212
([#301](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/301))
13+
- `opentelemetry-instrumentation-sqlalchemy` Fix multithreading issues in recording spans from SQLAlchemy ([#315](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/315))
1314

1415
## [0.17b0](https://github.com/open-telemetry/opentelemetry-python-contrib/releases/tag/v0.17b0) - 2021-01-20
1516

instrumentation/opentelemetry-instrumentation-sqlalchemy/src/opentelemetry/instrumentation/sqlalchemy/engine.py

+30-13
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,9 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414

15+
from threading import local
16+
from weakref import WeakKeyDictionary
17+
1518
from sqlalchemy.event import listen # pylint: disable=no-name-in-module
1619

1720
from opentelemetry import trace
@@ -66,12 +69,21 @@ def __init__(self, tracer, engine):
6669
self.tracer = tracer
6770
self.engine = engine
6871
self.vendor = _normalize_vendor(engine.name)
69-
self.current_span = None
72+
self.cursor_mapping = WeakKeyDictionary()
73+
self.local = local()
7074

7175
listen(engine, "before_cursor_execute", self._before_cur_exec)
7276
listen(engine, "after_cursor_execute", self._after_cur_exec)
7377
listen(engine, "handle_error", self._handle_error)
7478

79+
@property
80+
def current_thread_span(self):
81+
return getattr(self.local, "current_span", None)
82+
83+
@current_thread_span.setter
84+
def current_thread_span(self, span):
85+
setattr(self.local, "current_span", span)
86+
7587
def _operation_name(self, db_name, statement):
7688
parts = []
7789
if isinstance(statement, str):
@@ -94,34 +106,39 @@ def _before_cur_exec(self, conn, cursor, statement, *args):
94106
attrs = _get_attributes_from_cursor(self.vendor, cursor, attrs)
95107

96108
db_name = attrs.get(_DB, "")
97-
self.current_span = self.tracer.start_span(
109+
span = self.tracer.start_span(
98110
self._operation_name(db_name, statement),
99111
kind=trace.SpanKind.CLIENT,
100112
)
101-
with self.tracer.use_span(self.current_span, end_on_exit=False):
102-
if self.current_span.is_recording():
103-
self.current_span.set_attribute(_STMT, statement)
104-
self.current_span.set_attribute("db.system", self.vendor)
113+
self.current_thread_span = self.cursor_mapping[cursor] = span
114+
with self.tracer.use_span(span, end_on_exit=False):
115+
if span.is_recording():
116+
span.set_attribute(_STMT, statement)
117+
span.set_attribute("db.system", self.vendor)
105118
for key, value in attrs.items():
106-
self.current_span.set_attribute(key, value)
119+
span.set_attribute(key, value)
107120

108121
# pylint: disable=unused-argument
109122
def _after_cur_exec(self, conn, cursor, statement, *args):
110-
if self.current_span is None:
123+
span = self.cursor_mapping.get(cursor, None)
124+
# Only end if it is not finished already by an exception handled by SQLAlchemy
125+
if span is None or span.end_time is not None:
111126
return
112-
self.current_span.end()
127+
128+
span.end()
113129

114130
def _handle_error(self, context):
115-
if self.current_span is None:
131+
span = self.current_thread_span
132+
if span is None:
116133
return
117134

118135
try:
119-
if self.current_span.is_recording():
120-
self.current_span.set_status(
136+
if span.is_recording():
137+
span.set_status(
121138
Status(StatusCode.ERROR, str(context.original_exception),)
122139
)
123140
finally:
124-
self.current_span.end()
141+
span.end()
125142

126143

127144
def _get_attributes_from_url(url):

0 commit comments

Comments
 (0)