File size: 4,536 Bytes
7a3c0ee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import threading
from typing import Protocol, TypeVar, Any, Callable
from wrapt import wrap_function_wrapper
from concurrent import futures
import aworld.trace as trace
from aworld.trace.base import TraceContext, Span
from aworld.trace.propagator import get_global_trace_context
from aworld.trace.instrumentation import Instrumentor
from aworld.trace.instrumentation.utils import unwrap
from aworld.logs.util import logger


R = TypeVar("R")


class HasTraceContext(Protocol):
    _trace_context: TraceContext


class ThreadingInstrumentor(Instrumentor):
    '''
    Trace instrumentor for threading
    '''

    def instrumentation_dependencies(self) -> str:
        return ()

    def _instrument(self, **kwargs: Any):
        self._instrument_thread()
        self._instrument_timer()
        self._instrument_thread_pool()

    def _uninstrument(self, **kwargs: Any):
        self._uninstrument_thread()
        self._uninstrument_timer()
        self._uninstrument_thread_pool()

    @staticmethod
    def _instrument_thread():
        wrap_function_wrapper(
            threading.Thread,
            "start",
            ThreadingInstrumentor.__wrap_threading_start,
        )
        wrap_function_wrapper(
            threading.Thread,
            "run",
            ThreadingInstrumentor.__wrap_threading_run,
        )

    @staticmethod
    def _instrument_timer():
        wrap_function_wrapper(
            threading.Timer,
            "start",
            ThreadingInstrumentor.__wrap_threading_start,
        )
        wrap_function_wrapper(
            threading.Timer,
            "run",
            ThreadingInstrumentor.__wrap_threading_run,
        )

    @staticmethod
    def _instrument_thread_pool():
        wrap_function_wrapper(
            futures.ThreadPoolExecutor,
            "submit",
            ThreadingInstrumentor.__wrap_thread_pool_submit,
        )

    @staticmethod
    def _uninstrument_thread():
        unwrap(threading.Thread, "start")
        unwrap(threading.Thread, "run")

    @staticmethod
    def _uninstrument_timer():
        unwrap(threading.Timer, "start")
        unwrap(threading.Timer, "run")

    @staticmethod
    def _uninstrument_thread_pool():
        unwrap(futures.ThreadPoolExecutor, "submit")

    @staticmethod
    def __wrap_threading_start(
        call_wrapped: Callable[[], None],
        instance: HasTraceContext,
        args: tuple[()],
        kwargs: dict[str, Any],
    ) -> None:
        span: Span = trace.get_current_span()
        if span:
            instance._trace_context = TraceContext(
                trace_id=span.get_trace_id(), span_id=span.get_span_id())
        return call_wrapped(*args, **kwargs)

    @staticmethod
    def __wrap_threading_run(
        call_wrapped: Callable[..., R],
        instance: HasTraceContext,
        args: tuple[Any, ...],
        kwargs: dict[str, Any],
    ) -> R:

        token = None
        try:
            if hasattr(instance, "_trace_context"):
                if instance._trace_context:
                    token = get_global_trace_context().set(instance._trace_context)
            return call_wrapped(*args, **kwargs)
        finally:
            if token:
                get_global_trace_context().reset(token)

    @staticmethod
    def __wrap_thread_pool_submit(
        call_wrapped: Callable[..., R],
        instance: futures.ThreadPoolExecutor,
        args: tuple[Callable[..., Any], ...],
        kwargs: dict[str, Any],
    ) -> R:
        # obtain the original function and wrapped kwargs
        original_func = args[0]
        trace_context = None
        span: Span = trace.get_current_span()
        if span and span.get_trace_id() != "":
            trace_context = TraceContext(
                trace_id=span.get_trace_id(), span_id=span.get_span_id())

        def wrapped_func(*func_args: Any, **func_kwargs: Any) -> R:
            token = None
            try:
                if trace_context:
                    token = get_global_trace_context().set(trace_context)
                return original_func(*func_args, **func_kwargs)
            finally:
                if token:
                    get_global_trace_context().reset(token)

        # replace the original function with the wrapped function
        new_args: tuple[Callable[..., Any], ...] = (wrapped_func,) + args[1:]
        return call_wrapped(*new_args, **kwargs)


def instrument_theading(**kwargs: Any) -> None:
    ThreadingInstrumentor().instrument(**kwargs)
    logger.info("Threading instrumented")