forked from open-telemetry/opentelemetry-python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path__init__.py
231 lines (181 loc) · 7.96 KB
/
__init__.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
# Copyright The OpenTelemetry Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
This library allows tracing HTTP requests made by the
`requests <https://requests.readthedocs.io/en/master/>`_ library.
Usage
-----
.. code-block:: python
import requests
import opentelemetry.instrumentation.requests
# You can optionally pass a custom TracerProvider to
RequestInstrumentor.instrument()
opentelemetry.instrumentation.requests.RequestsInstrumentor().instrument()
response = requests.get(url="https://www.example.org/")
Limitations
-----------
If you find any way to trigger an untraced HTTP request, please report it via a
GitHub issue with :code:`[requests: untraced API]` in the title.
API
---
"""
import functools
import types
from requests import Timeout, URLRequired
from requests.exceptions import InvalidSchema, InvalidURL, MissingSchema
from requests.sessions import Session
from opentelemetry import context, propagators
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
from opentelemetry.instrumentation.requests.version import __version__
from opentelemetry.instrumentation.utils import http_status_to_canonical_code
from opentelemetry.trace import SpanKind, get_tracer
from opentelemetry.trace.status import Status, StatusCanonicalCode
# A key to a context variable to avoid creating duplicate spans when instrumenting
# both, Session.request and Session.send, since Session.request calls into Session.send
_SUPPRESS_REQUESTS_INSTRUMENTATION_KEY = "suppress_requests_instrumentation"
# pylint: disable=unused-argument
def _instrument(tracer_provider=None, span_callback=None):
"""Enables tracing of all requests calls that go through
:code:`requests.session.Session.request` (this includes
:code:`requests.get`, etc.)."""
# Since
# https://github.com/psf/requests/commit/d72d1162142d1bf8b1b5711c664fbbd674f349d1
# (v0.7.0, Oct 23, 2011), get, post, etc are implemented via request which
# again, is implemented via Session.request (`Session` was named `session`
# before v1.0.0, Dec 17, 2012, see
# https://github.com/psf/requests/commit/4e5c4a6ab7bb0195dececdd19bb8505b872fe120)
wrapped_request = Session.request
wrapped_send = Session.send
@functools.wraps(wrapped_request)
def instrumented_request(self, method, url, *args, **kwargs):
def get_or_create_headers():
headers = kwargs.get("headers")
if headers is None:
headers = {}
kwargs["headers"] = headers
return headers
def call_wrapped():
return wrapped_request(self, method, url, *args, **kwargs)
return _instrumented_requests_call(
method, url, call_wrapped, get_or_create_headers
)
@functools.wraps(wrapped_send)
def instrumented_send(self, request, **kwargs):
def get_or_create_headers():
request.headers = (
request.headers if request.headers is not None else {}
)
return request.headers
def call_wrapped():
return wrapped_send(self, request, **kwargs)
return _instrumented_requests_call(
request.method, request.url, call_wrapped, get_or_create_headers
)
def _instrumented_requests_call(
method: str, url: str, call_wrapped, get_or_create_headers
):
if context.get_value("suppress_instrumentation") or context.get_value(
_SUPPRESS_REQUESTS_INSTRUMENTATION_KEY
):
return call_wrapped()
# See
# https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/trace/semantic_conventions/http.md#http-client
method = method.upper()
span_name = "HTTP {}".format(method)
exception = None
with get_tracer(
__name__, __version__, tracer_provider
).start_as_current_span(span_name, kind=SpanKind.CLIENT) as span:
span.set_attribute("component", "http")
span.set_attribute("http.method", method.upper())
span.set_attribute("http.url", url)
headers = get_or_create_headers()
propagators.inject(type(headers).__setitem__, headers)
token = context.attach(
context.set_value(_SUPPRESS_REQUESTS_INSTRUMENTATION_KEY, True)
)
try:
result = call_wrapped() # *** PROCEED
except Exception as exc: # pylint: disable=W0703
exception = exc
result = getattr(exc, "response", None)
finally:
context.detach(token)
if exception is not None:
span.set_status(
Status(_exception_to_canonical_code(exception))
)
span.record_exception(exception)
if result is not None:
span.set_attribute("http.status_code", result.status_code)
span.set_attribute("http.status_text", result.reason)
span.set_status(
Status(http_status_to_canonical_code(result.status_code))
)
if span_callback is not None:
span_callback(span, result)
if exception is not None:
raise exception.with_traceback(exception.__traceback__)
return result
instrumented_request.opentelemetry_instrumentation_requests_applied = True
Session.request = instrumented_request
instrumented_send.opentelemetry_instrumentation_requests_applied = True
Session.send = instrumented_send
def _uninstrument():
"""Disables instrumentation of :code:`requests` through this module.
Note that this only works if no other module also patches requests."""
_uninstrument_from(Session)
def _uninstrument_from(instr_root, restore_as_bound_func=False):
for instr_func_name in ("request", "send"):
instr_func = getattr(instr_root, instr_func_name)
if not getattr(
instr_func,
"opentelemetry_instrumentation_requests_applied",
False,
):
continue
original = instr_func.__wrapped__ # pylint:disable=no-member
if restore_as_bound_func:
original = types.MethodType(original, instr_root)
setattr(instr_root, instr_func_name, original)
def _exception_to_canonical_code(exc: Exception) -> StatusCanonicalCode:
if isinstance(
exc,
(InvalidURL, InvalidSchema, MissingSchema, URLRequired, ValueError),
):
return StatusCanonicalCode.INVALID_ARGUMENT
if isinstance(exc, Timeout):
return StatusCanonicalCode.DEADLINE_EXCEEDED
return StatusCanonicalCode.UNKNOWN
class RequestsInstrumentor(BaseInstrumentor):
"""An instrumentor for requests
See `BaseInstrumentor`
"""
def _instrument(self, **kwargs):
"""Instruments requests module
Args:
**kwargs: Optional arguments
``tracer_provider``: a TracerProvider, defaults to global
``span_callback``: An optional callback invoked before returning the http response. Invoked with Span and requests.Response
"""
_instrument(
tracer_provider=kwargs.get("tracer_provider"),
span_callback=kwargs.get("span_callback"),
)
def _uninstrument(self, **kwargs):
_uninstrument()
@staticmethod
def uninstrument_session(session):
"""Disables instrumentation on the session object."""
_uninstrument_from(session, restore_as_bound_func=True)