opentracing.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2019 The Matrix.org Foundation C.I.C.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. # NOTE
  16. # This is a small wrapper around opentracing because opentracing is not currently
  17. # packaged downstream (specifically debian). Since opentracing instrumentation is
  18. # fairly invasive it was awkward to make it optional. As a result we opted to encapsulate
  19. # all opentracing state in these methods which effectively noop if opentracing is
  20. # not present. We should strongly consider encouraging the downstream distributers
  21. # to package opentracing and making opentracing a full dependency. In order to facilitate
  22. # this move the methods have work very similarly to opentracing's and it should only
  23. # be a matter of few regexes to move over to opentracing's access patterns proper.
  24. """
  25. ============================
  26. Using OpenTracing in Synapse
  27. ============================
  28. Python-specific tracing concepts are at https://opentracing.io/guides/python/.
  29. Note that Synapse wraps OpenTracing in a small module (this one) in order to make the
  30. OpenTracing dependency optional. That means that the access patterns are
  31. different to those demonstrated in the OpenTracing guides. However, it is
  32. still useful to know, especially if OpenTracing is included as a full dependency
  33. in the future or if you are modifying this module.
  34. OpenTracing is encapsulated so that
  35. no span objects from OpenTracing are exposed in Synapse's code. This allows
  36. OpenTracing to be easily disabled in Synapse and thereby have OpenTracing as
  37. an optional dependency. This does however limit the number of modifiable spans
  38. at any point in the code to one. From here out references to `opentracing`
  39. in the code snippets refer to the Synapses module.
  40. Most methods provided in the module have a direct correlation to those provided
  41. by opentracing. Refer to docs there for a more in-depth documentation on some of
  42. the args and methods.
  43. Tracing
  44. -------
  45. In Synapse it is not possible to start a non-active span. Spans can be started
  46. using the ``start_active_span`` method. This returns a scope (see
  47. OpenTracing docs) which is a context manager that needs to be entered and
  48. exited. This is usually done by using ``with``.
  49. .. code-block:: python
  50. from synapse.logging.opentracing import start_active_span
  51. with start_active_span("operation name"):
  52. # Do something we want to tracer
  53. Forgetting to enter or exit a scope will result in some mysterious and grievous log
  54. context errors.
  55. At anytime where there is an active span ``opentracing.set_tag`` can be used to
  56. set a tag on the current active span.
  57. Tracing functions
  58. -----------------
  59. Functions can be easily traced using decorators. The name of
  60. the function becomes the operation name for the span.
  61. .. code-block:: python
  62. from synapse.logging.opentracing import trace
  63. # Start a span using 'interesting_function' as the operation name
  64. @trace
  65. def interesting_function(*args, **kwargs):
  66. # Does all kinds of cool and expected things
  67. return something_usual_and_useful
  68. Operation names can be explicitly set for a function by passing the
  69. operation name to ``trace``
  70. .. code-block:: python
  71. from synapse.logging.opentracing import trace
  72. @trace(opname="a_better_operation_name")
  73. def interesting_badly_named_function(*args, **kwargs):
  74. # Does all kinds of cool and expected things
  75. return something_usual_and_useful
  76. Setting Tags
  77. ------------
  78. To set a tag on the active span do
  79. .. code-block:: python
  80. from synapse.logging.opentracing import set_tag
  81. set_tag(tag_name, tag_value)
  82. There's a convenient decorator to tag all the args of the method. It uses
  83. inspection in order to use the formal parameter names prefixed with 'ARG_' as
  84. tag names. It uses kwarg names as tag names without the prefix.
  85. .. code-block:: python
  86. from synapse.logging.opentracing import tag_args
  87. @tag_args
  88. def set_fates(clotho, lachesis, atropos, father="Zues", mother="Themis"):
  89. pass
  90. set_fates("the story", "the end", "the act")
  91. # This will have the following tags
  92. # - ARG_clotho: "the story"
  93. # - ARG_lachesis: "the end"
  94. # - ARG_atropos: "the act"
  95. # - father: "Zues"
  96. # - mother: "Themis"
  97. Contexts and carriers
  98. ---------------------
  99. There are a selection of wrappers for injecting and extracting contexts from
  100. carriers provided. Unfortunately OpenTracing's three context injection
  101. techniques are not adequate for our inject of OpenTracing span-contexts into
  102. Twisted's http headers, EDU contents and our database tables. Also note that
  103. the binary encoding format mandated by OpenTracing is not actually implemented
  104. by jaeger_client v4.0.0 - it will silently noop.
  105. Please refer to the end of ``logging/opentracing.py`` for the available
  106. injection and extraction methods.
  107. Homeserver whitelisting
  108. -----------------------
  109. Most of the whitelist checks are encapsulated in the modules's injection
  110. and extraction method but be aware that using custom carriers or crossing
  111. unchartered waters will require the enforcement of the whitelist.
  112. ``logging/opentracing.py`` has a ``whitelisted_homeserver`` method which takes
  113. in a destination and compares it to the whitelist.
  114. Most injection methods take a 'destination' arg. The context will only be injected
  115. if the destination matches the whitelist or the destination is None.
  116. =======
  117. Gotchas
  118. =======
  119. - Checking whitelists on span propagation
  120. - Inserting pii
  121. - Forgetting to enter or exit a scope
  122. - Span source: make sure that the span you expect to be active across a
  123. function call really will be that one. Does the current function have more
  124. than one caller? Will all of those calling functions have be in a context
  125. with an active span?
  126. """
  127. import contextlib
  128. import inspect
  129. import logging
  130. import re
  131. import types
  132. from functools import wraps
  133. from typing import Dict
  134. from canonicaljson import json
  135. from twisted.internet import defer
  136. from synapse.config import ConfigError
  137. # Helper class
  138. class _DummyTagNames(object):
  139. """wrapper of opentracings tags. We need to have them if we
  140. want to reference them without opentracing around. Clearly they
  141. should never actually show up in a trace. `set_tags` overwrites
  142. these with the correct ones."""
  143. INVALID_TAG = "invalid-tag"
  144. COMPONENT = INVALID_TAG
  145. DATABASE_INSTANCE = INVALID_TAG
  146. DATABASE_STATEMENT = INVALID_TAG
  147. DATABASE_TYPE = INVALID_TAG
  148. DATABASE_USER = INVALID_TAG
  149. ERROR = INVALID_TAG
  150. HTTP_METHOD = INVALID_TAG
  151. HTTP_STATUS_CODE = INVALID_TAG
  152. HTTP_URL = INVALID_TAG
  153. MESSAGE_BUS_DESTINATION = INVALID_TAG
  154. PEER_ADDRESS = INVALID_TAG
  155. PEER_HOSTNAME = INVALID_TAG
  156. PEER_HOST_IPV4 = INVALID_TAG
  157. PEER_HOST_IPV6 = INVALID_TAG
  158. PEER_PORT = INVALID_TAG
  159. PEER_SERVICE = INVALID_TAG
  160. SAMPLING_PRIORITY = INVALID_TAG
  161. SERVICE = INVALID_TAG
  162. SPAN_KIND = INVALID_TAG
  163. SPAN_KIND_CONSUMER = INVALID_TAG
  164. SPAN_KIND_PRODUCER = INVALID_TAG
  165. SPAN_KIND_RPC_CLIENT = INVALID_TAG
  166. SPAN_KIND_RPC_SERVER = INVALID_TAG
  167. try:
  168. import opentracing
  169. tags = opentracing.tags
  170. except ImportError:
  171. opentracing = None
  172. tags = _DummyTagNames
  173. try:
  174. from jaeger_client import Config as JaegerConfig
  175. from synapse.logging.scopecontextmanager import LogContextScopeManager
  176. except ImportError:
  177. JaegerConfig = None # type: ignore
  178. LogContextScopeManager = None # type: ignore
  179. logger = logging.getLogger(__name__)
  180. # Block everything by default
  181. # A regex which matches the server_names to expose traces for.
  182. # None means 'block everything'.
  183. _homeserver_whitelist = None
  184. # Util methods
  185. def only_if_tracing(func):
  186. """Executes the function only if we're tracing. Otherwise returns None."""
  187. @wraps(func)
  188. def _only_if_tracing_inner(*args, **kwargs):
  189. if opentracing:
  190. return func(*args, **kwargs)
  191. else:
  192. return
  193. return _only_if_tracing_inner
  194. def ensure_active_span(message, ret=None):
  195. """Executes the operation only if opentracing is enabled and there is an active span.
  196. If there is no active span it logs message at the error level.
  197. Args:
  198. message (str): Message which fills in "There was no active span when trying to %s"
  199. in the error log if there is no active span and opentracing is enabled.
  200. ret (object): return value if opentracing is None or there is no active span.
  201. Returns (object): The result of the func or ret if opentracing is disabled or there
  202. was no active span.
  203. """
  204. def ensure_active_span_inner_1(func):
  205. @wraps(func)
  206. def ensure_active_span_inner_2(*args, **kwargs):
  207. if not opentracing:
  208. return ret
  209. if not opentracing.tracer.active_span:
  210. logger.error(
  211. "There was no active span when trying to %s."
  212. " Did you forget to start one or did a context slip?",
  213. message,
  214. )
  215. return ret
  216. return func(*args, **kwargs)
  217. return ensure_active_span_inner_2
  218. return ensure_active_span_inner_1
  219. @contextlib.contextmanager
  220. def _noop_context_manager(*args, **kwargs):
  221. """Does exactly what it says on the tin"""
  222. yield
  223. # Setup
  224. def init_tracer(config):
  225. """Set the whitelists and initialise the JaegerClient tracer
  226. Args:
  227. config (HomeserverConfig): The config used by the homeserver
  228. """
  229. global opentracing
  230. if not config.opentracer_enabled:
  231. # We don't have a tracer
  232. opentracing = None
  233. return
  234. if not opentracing or not JaegerConfig:
  235. raise ConfigError(
  236. "The server has been configured to use opentracing but opentracing is not "
  237. "installed."
  238. )
  239. # Include the worker name
  240. name = config.worker_name if config.worker_name else "master"
  241. # Pull out the jaeger config if it was given. Otherwise set it to something sensible.
  242. # See https://github.com/jaegertracing/jaeger-client-python/blob/master/jaeger_client/config.py
  243. set_homeserver_whitelist(config.opentracer_whitelist)
  244. JaegerConfig(
  245. config=config.jaeger_config,
  246. service_name="{} {}".format(config.server_name, name),
  247. scope_manager=LogContextScopeManager(config),
  248. ).initialize_tracer()
  249. # Whitelisting
  250. @only_if_tracing
  251. def set_homeserver_whitelist(homeserver_whitelist):
  252. """Sets the homeserver whitelist
  253. Args:
  254. homeserver_whitelist (Iterable[str]): regex of whitelisted homeservers
  255. """
  256. global _homeserver_whitelist
  257. if homeserver_whitelist:
  258. # Makes a single regex which accepts all passed in regexes in the list
  259. _homeserver_whitelist = re.compile(
  260. "({})".format(")|(".join(homeserver_whitelist))
  261. )
  262. @only_if_tracing
  263. def whitelisted_homeserver(destination):
  264. """Checks if a destination matches the whitelist
  265. Args:
  266. destination (str)
  267. """
  268. if _homeserver_whitelist:
  269. return _homeserver_whitelist.match(destination)
  270. return False
  271. # Start spans and scopes
  272. # Could use kwargs but I want these to be explicit
  273. def start_active_span(
  274. operation_name,
  275. child_of=None,
  276. references=None,
  277. tags=None,
  278. start_time=None,
  279. ignore_active_span=False,
  280. finish_on_close=True,
  281. ):
  282. """Starts an active opentracing span. Note, the scope doesn't become active
  283. until it has been entered, however, the span starts from the time this
  284. message is called.
  285. Args:
  286. See opentracing.tracer
  287. Returns:
  288. scope (Scope) or noop_context_manager
  289. """
  290. if opentracing is None:
  291. return _noop_context_manager()
  292. return opentracing.tracer.start_active_span(
  293. operation_name,
  294. child_of=child_of,
  295. references=references,
  296. tags=tags,
  297. start_time=start_time,
  298. ignore_active_span=ignore_active_span,
  299. finish_on_close=finish_on_close,
  300. )
  301. def start_active_span_follows_from(operation_name, contexts):
  302. if opentracing is None:
  303. return _noop_context_manager()
  304. references = [opentracing.follows_from(context) for context in contexts]
  305. scope = start_active_span(operation_name, references=references)
  306. return scope
  307. def start_active_span_from_request(
  308. request,
  309. operation_name,
  310. references=None,
  311. tags=None,
  312. start_time=None,
  313. ignore_active_span=False,
  314. finish_on_close=True,
  315. ):
  316. """
  317. Extracts a span context from a Twisted Request.
  318. args:
  319. headers (twisted.web.http.Request)
  320. For the other args see opentracing.tracer
  321. returns:
  322. span_context (opentracing.span.SpanContext)
  323. """
  324. # Twisted encodes the values as lists whereas opentracing doesn't.
  325. # So, we take the first item in the list.
  326. # Also, twisted uses byte arrays while opentracing expects strings.
  327. if opentracing is None:
  328. return _noop_context_manager()
  329. header_dict = {
  330. k.decode(): v[0].decode() for k, v in request.requestHeaders.getAllRawHeaders()
  331. }
  332. context = opentracing.tracer.extract(opentracing.Format.HTTP_HEADERS, header_dict)
  333. return opentracing.tracer.start_active_span(
  334. operation_name,
  335. child_of=context,
  336. references=references,
  337. tags=tags,
  338. start_time=start_time,
  339. ignore_active_span=ignore_active_span,
  340. finish_on_close=finish_on_close,
  341. )
  342. def start_active_span_from_edu(
  343. edu_content,
  344. operation_name,
  345. references=[],
  346. tags=None,
  347. start_time=None,
  348. ignore_active_span=False,
  349. finish_on_close=True,
  350. ):
  351. """
  352. Extracts a span context from an edu and uses it to start a new active span
  353. Args:
  354. edu_content (dict): and edu_content with a `context` field whose value is
  355. canonical json for a dict which contains opentracing information.
  356. For the other args see opentracing.tracer
  357. """
  358. if opentracing is None:
  359. return _noop_context_manager()
  360. carrier = json.loads(edu_content.get("context", "{}")).get("opentracing", {})
  361. context = opentracing.tracer.extract(opentracing.Format.TEXT_MAP, carrier)
  362. _references = [
  363. opentracing.child_of(span_context_from_string(x))
  364. for x in carrier.get("references", [])
  365. ]
  366. # For some reason jaeger decided not to support the visualization of multiple parent
  367. # spans or explicitely show references. I include the span context as a tag here as
  368. # an aid to people debugging but it's really not an ideal solution.
  369. references += _references
  370. scope = opentracing.tracer.start_active_span(
  371. operation_name,
  372. child_of=context,
  373. references=references,
  374. tags=tags,
  375. start_time=start_time,
  376. ignore_active_span=ignore_active_span,
  377. finish_on_close=finish_on_close,
  378. )
  379. scope.span.set_tag("references", carrier.get("references", []))
  380. return scope
  381. # Opentracing setters for tags, logs, etc
  382. @ensure_active_span("set a tag")
  383. def set_tag(key, value):
  384. """Sets a tag on the active span"""
  385. opentracing.tracer.active_span.set_tag(key, value)
  386. @ensure_active_span("log")
  387. def log_kv(key_values, timestamp=None):
  388. """Log to the active span"""
  389. opentracing.tracer.active_span.log_kv(key_values, timestamp)
  390. @ensure_active_span("set the traces operation name")
  391. def set_operation_name(operation_name):
  392. """Sets the operation name of the active span"""
  393. opentracing.tracer.active_span.set_operation_name(operation_name)
  394. # Injection and extraction
  395. @ensure_active_span("inject the span into a header")
  396. def inject_active_span_twisted_headers(headers, destination, check_destination=True):
  397. """
  398. Injects a span context into twisted headers in-place
  399. Args:
  400. headers (twisted.web.http_headers.Headers)
  401. destination (str): address of entity receiving the span context. If check_destination
  402. is true the context will only be injected if the destination matches the
  403. opentracing whitelist
  404. check_destination (bool): If false, destination will be ignored and the context
  405. will always be injected.
  406. span (opentracing.Span)
  407. Returns:
  408. In-place modification of headers
  409. Note:
  410. The headers set by the tracer are custom to the tracer implementation which
  411. should be unique enough that they don't interfere with any headers set by
  412. synapse or twisted. If we're still using jaeger these headers would be those
  413. here:
  414. https://github.com/jaegertracing/jaeger-client-python/blob/master/jaeger_client/constants.py
  415. """
  416. if check_destination and not whitelisted_homeserver(destination):
  417. return
  418. span = opentracing.tracer.active_span
  419. carrier = {} # type: Dict[str, str]
  420. opentracing.tracer.inject(span, opentracing.Format.HTTP_HEADERS, carrier)
  421. for key, value in carrier.items():
  422. headers.addRawHeaders(key, value)
  423. @ensure_active_span("inject the span into a byte dict")
  424. def inject_active_span_byte_dict(headers, destination, check_destination=True):
  425. """
  426. Injects a span context into a dict where the headers are encoded as byte
  427. strings
  428. Args:
  429. headers (dict)
  430. destination (str): address of entity receiving the span context. If check_destination
  431. is true the context will only be injected if the destination matches the
  432. opentracing whitelist
  433. check_destination (bool): If false, destination will be ignored and the context
  434. will always be injected.
  435. span (opentracing.Span)
  436. Returns:
  437. In-place modification of headers
  438. Note:
  439. The headers set by the tracer are custom to the tracer implementation which
  440. should be unique enough that they don't interfere with any headers set by
  441. synapse or twisted. If we're still using jaeger these headers would be those
  442. here:
  443. https://github.com/jaegertracing/jaeger-client-python/blob/master/jaeger_client/constants.py
  444. """
  445. if check_destination and not whitelisted_homeserver(destination):
  446. return
  447. span = opentracing.tracer.active_span
  448. carrier = {} # type: Dict[str, str]
  449. opentracing.tracer.inject(span, opentracing.Format.HTTP_HEADERS, carrier)
  450. for key, value in carrier.items():
  451. headers[key.encode()] = [value.encode()]
  452. @ensure_active_span("inject the span into a text map")
  453. def inject_active_span_text_map(carrier, destination, check_destination=True):
  454. """
  455. Injects a span context into a dict
  456. Args:
  457. carrier (dict)
  458. destination (str): address of entity receiving the span context. If check_destination
  459. is true the context will only be injected if the destination matches the
  460. opentracing whitelist
  461. check_destination (bool): If false, destination will be ignored and the context
  462. will always be injected.
  463. Returns:
  464. In-place modification of carrier
  465. Note:
  466. The headers set by the tracer are custom to the tracer implementation which
  467. should be unique enough that they don't interfere with any headers set by
  468. synapse or twisted. If we're still using jaeger these headers would be those
  469. here:
  470. https://github.com/jaegertracing/jaeger-client-python/blob/master/jaeger_client/constants.py
  471. """
  472. if check_destination and not whitelisted_homeserver(destination):
  473. return
  474. opentracing.tracer.inject(
  475. opentracing.tracer.active_span, opentracing.Format.TEXT_MAP, carrier
  476. )
  477. @ensure_active_span("get the active span context as a dict", ret={})
  478. def get_active_span_text_map(destination=None):
  479. """
  480. Gets a span context as a dict. This can be used instead of manually
  481. injecting a span into an empty carrier.
  482. Args:
  483. destination (str): the name of the remote server.
  484. Returns:
  485. dict: the active span's context if opentracing is enabled, otherwise empty.
  486. """
  487. if destination and not whitelisted_homeserver(destination):
  488. return {}
  489. carrier = {} # type: Dict[str, str]
  490. opentracing.tracer.inject(
  491. opentracing.tracer.active_span, opentracing.Format.TEXT_MAP, carrier
  492. )
  493. return carrier
  494. @ensure_active_span("get the span context as a string.", ret={})
  495. def active_span_context_as_string():
  496. """
  497. Returns:
  498. The active span context encoded as a string.
  499. """
  500. carrier = {} # type: Dict[str, str]
  501. if opentracing:
  502. opentracing.tracer.inject(
  503. opentracing.tracer.active_span, opentracing.Format.TEXT_MAP, carrier
  504. )
  505. return json.dumps(carrier)
  506. @only_if_tracing
  507. def span_context_from_string(carrier):
  508. """
  509. Returns:
  510. The active span context decoded from a string.
  511. """
  512. carrier = json.loads(carrier)
  513. return opentracing.tracer.extract(opentracing.Format.TEXT_MAP, carrier)
  514. @only_if_tracing
  515. def extract_text_map(carrier):
  516. """
  517. Wrapper method for opentracing's tracer.extract for TEXT_MAP.
  518. Args:
  519. carrier (dict): a dict possibly containing a span context.
  520. Returns:
  521. The active span context extracted from carrier.
  522. """
  523. return opentracing.tracer.extract(opentracing.Format.TEXT_MAP, carrier)
  524. # Tracing decorators
  525. def trace(func=None, opname=None):
  526. """
  527. Decorator to trace a function.
  528. Sets the operation name to that of the function's or that given
  529. as operation_name. See the module's doc string for usage
  530. examples.
  531. """
  532. def decorator(func):
  533. if opentracing is None:
  534. return func
  535. _opname = opname if opname else func.__name__
  536. @wraps(func)
  537. def _trace_inner(*args, **kwargs):
  538. if opentracing is None:
  539. return func(*args, **kwargs)
  540. scope = start_active_span(_opname)
  541. scope.__enter__()
  542. try:
  543. result = func(*args, **kwargs)
  544. if isinstance(result, defer.Deferred):
  545. def call_back(result):
  546. scope.__exit__(None, None, None)
  547. return result
  548. def err_back(result):
  549. scope.span.set_tag(tags.ERROR, True)
  550. scope.__exit__(None, None, None)
  551. return result
  552. result.addCallbacks(call_back, err_back)
  553. else:
  554. scope.__exit__(None, None, None)
  555. return result
  556. except Exception as e:
  557. scope.__exit__(type(e), None, e.__traceback__)
  558. raise
  559. return _trace_inner
  560. if func:
  561. return decorator(func)
  562. else:
  563. return decorator
  564. def tag_args(func):
  565. """
  566. Tags all of the args to the active span.
  567. """
  568. if not opentracing:
  569. return func
  570. @wraps(func)
  571. def _tag_args_inner(*args, **kwargs):
  572. argspec = inspect.getargspec(func)
  573. for i, arg in enumerate(argspec.args[1:]):
  574. set_tag("ARG_" + arg, args[i])
  575. set_tag("args", args[len(argspec.args) :])
  576. set_tag("kwargs", kwargs)
  577. return func(*args, **kwargs)
  578. return _tag_args_inner
  579. def trace_servlet(servlet_name, extract_context=False):
  580. """Decorator which traces a serlet. It starts a span with some servlet specific
  581. tags such as the servlet_name and request information
  582. Args:
  583. servlet_name (str): The name to be used for the span's operation_name
  584. extract_context (bool): Whether to attempt to extract the opentracing
  585. context from the request the servlet is handling.
  586. """
  587. def _trace_servlet_inner_1(func):
  588. if not opentracing:
  589. return func
  590. @wraps(func)
  591. async def _trace_servlet_inner(request, *args, **kwargs):
  592. request_tags = {
  593. "request_id": request.get_request_id(),
  594. tags.SPAN_KIND: tags.SPAN_KIND_RPC_SERVER,
  595. tags.HTTP_METHOD: request.get_method(),
  596. tags.HTTP_URL: request.get_redacted_uri(),
  597. tags.PEER_HOST_IPV6: request.getClientIP(),
  598. }
  599. if extract_context:
  600. scope = start_active_span_from_request(
  601. request, servlet_name, tags=request_tags
  602. )
  603. else:
  604. scope = start_active_span(servlet_name, tags=request_tags)
  605. with scope:
  606. result = func(request, *args, **kwargs)
  607. if not isinstance(result, (types.CoroutineType, defer.Deferred)):
  608. # Some servlets aren't async and just return results
  609. # directly, so we handle that here.
  610. return result
  611. return await result
  612. return _trace_servlet_inner
  613. return _trace_servlet_inner_1