1# --------------------------------------------------------------------------
2#
3# Copyright (c) Microsoft Corporation. All rights reserved.
4#
5# The MIT License (MIT)
6#
7# Permission is hereby granted, free of charge, to any person obtaining a copy
8# of this software and associated documentation files (the ""Software""), to deal
9# in the Software without restriction, including without limitation the rights
10# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11# copies of the Software, and to permit persons to whom the Software is
12# furnished to do so, subject to the following conditions:
13#
14# The above copyright notice and this permission notice shall be included in
15# all copies or substantial portions of the Software.
16#
17# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23# THE SOFTWARE.
24#
25# --------------------------------------------------------------------------
26"""Common functions shared by both the sync and the async decorators."""
27from contextlib import contextmanager
28from typing import Any, Optional, Callable, Type, Generator
29import warnings
30
31from ._abstract_span import AbstractSpan
32from ..instrumentation import get_tracer
33from ..settings import settings
34
35
36__all__ = [
37 "change_context",
38 "with_current_context",
39]
40
41
42def get_function_and_class_name(func: Callable, *args: object) -> str:
43 """
44 Given a function and its unamed arguments, returns class_name.function_name. It assumes the first argument
45 is `self`. If there are no arguments then it only returns the function name.
46
47 :param func: the function passed in
48 :type func: callable
49 :param args: List of arguments passed into the function
50 :type args: list
51 :return: The function name with the class name
52 :rtype: str
53 """
54 try:
55 return func.__qualname__
56 except AttributeError:
57 if args:
58 return "{}.{}".format(args[0].__class__.__name__, func.__name__)
59 return func.__name__
60
61
62@contextmanager
63def change_context(span: Optional[AbstractSpan]) -> Generator:
64 """Execute this block inside the given context and restore it afterwards.
65
66 This does not start and ends the span, but just make sure all code is executed within
67 that span.
68
69 If span is None, no-op.
70
71 :param span: A span
72 :type span: AbstractSpan
73 :rtype: contextmanager
74 :return: A context manager that will run the given span in the new context
75 """
76 span_impl_type = settings.tracing_implementation()
77 if span_impl_type is None or span is None:
78 yield
79 else:
80
81 try:
82 with span_impl_type.change_context(span):
83 yield
84 except AttributeError:
85 # This plugin does not support "change_context"
86 warnings.warn(
87 'Your tracing plugin should be updated to support "change_context"',
88 DeprecationWarning,
89 )
90 original_span = span_impl_type.get_current_span()
91 try:
92 span_impl_type.set_current_span(span)
93 yield
94 finally:
95 span_impl_type.set_current_span(original_span)
96
97
98def with_current_context(func: Callable) -> Any:
99 """Passes the current spans to the new context the function will be run in.
100
101 :param func: The function that will be run in the new context
102 :type func: callable
103 :return: The func wrapped with correct context
104 :rtype: callable
105 """
106 if not settings.tracing_enabled():
107 return func
108
109 span_impl_type: Optional[Type[AbstractSpan]] = settings.tracing_implementation()
110 if span_impl_type:
111 return span_impl_type.with_current_context(func)
112
113 tracer = get_tracer()
114 if not tracer:
115 return func
116 return tracer.with_current_context(func)