|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import inspect |
| 4 | +from typing import TYPE_CHECKING, Any |
| 5 | + |
| 6 | +from opentelemetry.instrumentation.instrumentor import ( # type:ignore[attr-defined] # Mypy has troubles with OTEL |
| 7 | + BaseInstrumentor, |
| 8 | +) |
| 9 | +from opentelemetry.instrumentation.utils import unwrap |
| 10 | +from opentelemetry.semconv.attributes.code_attributes import CODE_FUNCTION_NAME |
| 11 | +from opentelemetry.semconv.attributes.http_attributes import HTTP_REQUEST_METHOD |
| 12 | +from opentelemetry.semconv.attributes.url_attributes import URL_FULL |
| 13 | +from opentelemetry.trace import get_tracer |
| 14 | +from wrapt import wrap_function_wrapper |
| 15 | + |
| 16 | +from crawlee._utils.docs import docs_group |
| 17 | +from crawlee.crawlers import BasicCrawler, ContextPipeline |
| 18 | +from crawlee.crawlers._basic._context_pipeline import _Middleware |
| 19 | + |
| 20 | +if TYPE_CHECKING: |
| 21 | + from collections.abc import Callable |
| 22 | + |
| 23 | + from crawlee.crawlers import BasicCrawlingContext |
| 24 | + |
| 25 | + |
| 26 | +@docs_group('Classes') |
| 27 | +class CrawlerInstrumentor(BaseInstrumentor): |
| 28 | + """Helper class for instrumenting crawlers with OpenTelemetry.""" |
| 29 | + |
| 30 | + def __init__( |
| 31 | + self, *, instrument_classes: list[type] | None = None, request_handling_instrumentation: bool = True |
| 32 | + ) -> None: |
| 33 | + """Initialize the instrumentor. |
| 34 | +
|
| 35 | + Args: |
| 36 | + instrument_classes: List of classes to be instrumented - all their public methods and coroutines will be |
| 37 | + wrapped by generic instrumentation wrapper that will create spans for them. |
| 38 | + request_handling_instrumentation: Handpicked most interesting methods to instrument in the request handling |
| 39 | + pipeline. |
| 40 | + """ |
| 41 | + self._tracer = get_tracer(__name__) |
| 42 | + |
| 43 | + async def _simple_async_wrapper(wrapped: Any, _: Any, args: Any, kwargs: Any) -> Any: |
| 44 | + with self._tracer.start_as_current_span( |
| 45 | + name=wrapped.__name__, attributes={CODE_FUNCTION_NAME: wrapped.__qualname__} |
| 46 | + ): |
| 47 | + return await wrapped(*args, **kwargs) |
| 48 | + |
| 49 | + def _simple_wrapper(wrapped: Any, _: Any, args: Any, kwargs: Any) -> Any: |
| 50 | + with self._tracer.start_as_current_span( |
| 51 | + name=wrapped.__name__, attributes={CODE_FUNCTION_NAME: wrapped.__qualname__} |
| 52 | + ): |
| 53 | + return wrapped(*args, **kwargs) |
| 54 | + |
| 55 | + def _init_wrapper(wrapped: Any, _: Any, args: Any, kwargs: Any) -> None: |
| 56 | + with self._tracer.start_as_current_span( |
| 57 | + name=wrapped.__name__, attributes={CODE_FUNCTION_NAME: wrapped.__qualname__} |
| 58 | + ): |
| 59 | + wrapped(*args, **kwargs) |
| 60 | + |
| 61 | + self._instrumented: list[tuple[Any, str, Callable]] = [] |
| 62 | + self._simple_wrapper = _simple_wrapper |
| 63 | + self._simple_async_wrapper = _simple_async_wrapper |
| 64 | + self._init_wrapper = _init_wrapper |
| 65 | + |
| 66 | + if instrument_classes: |
| 67 | + for _class in instrument_classes: |
| 68 | + self._instrument_all_public_methods(on_class=_class) |
| 69 | + |
| 70 | + if request_handling_instrumentation: |
| 71 | + |
| 72 | + async def middlware_wrapper(wrapped: Any, instance: _Middleware, args: Any, kwargs: Any) -> Any: |
| 73 | + with self._tracer.start_as_current_span( |
| 74 | + name=f'{instance.generator.__name__}, {wrapped.__name__}', # type:ignore[attr-defined] # valid in our context |
| 75 | + attributes={ |
| 76 | + URL_FULL: instance.input_context.request.url, |
| 77 | + CODE_FUNCTION_NAME: instance.generator.__qualname__, # type:ignore[attr-defined] # valid in our context |
| 78 | + }, |
| 79 | + ): |
| 80 | + return await wrapped(*args, **kwargs) |
| 81 | + |
| 82 | + async def context_pipeline_wrapper( |
| 83 | + wrapped: Any, _: ContextPipeline[BasicCrawlingContext], args: Any, kwargs: Any |
| 84 | + ) -> Any: |
| 85 | + context = args[0] |
| 86 | + final_context_consumer = args[1] |
| 87 | + |
| 88 | + async def wrapped_final_consumer(*args: Any, **kwargs: Any) -> Any: |
| 89 | + with self._tracer.start_as_current_span( |
| 90 | + name='request_handler', |
| 91 | + attributes={URL_FULL: context.request.url, HTTP_REQUEST_METHOD: context.request.method}, |
| 92 | + ): |
| 93 | + return await final_context_consumer(*args, **kwargs) |
| 94 | + |
| 95 | + with self._tracer.start_as_current_span( |
| 96 | + name='ContextPipeline', |
| 97 | + attributes={URL_FULL: context.request.url, HTTP_REQUEST_METHOD: context.request.method}, |
| 98 | + ): |
| 99 | + return await wrapped(context, wrapped_final_consumer, **kwargs) |
| 100 | + |
| 101 | + async def _commit_request_handler_result_wrapper( |
| 102 | + wrapped: Callable[[Any], Any], _: BasicCrawler, args: Any, kwargs: Any |
| 103 | + ) -> Any: |
| 104 | + context = args[0] |
| 105 | + with self._tracer.start_as_current_span( |
| 106 | + name='Commit results', |
| 107 | + attributes={URL_FULL: context.request.url, HTTP_REQUEST_METHOD: context.request.method}, |
| 108 | + ): |
| 109 | + return await wrapped(*args, **kwargs) |
| 110 | + |
| 111 | + # Handpicked interesting methods to instrument |
| 112 | + self._instrumented.extend( |
| 113 | + [ |
| 114 | + (_Middleware, 'action', middlware_wrapper), |
| 115 | + (_Middleware, 'cleanup', middlware_wrapper), |
| 116 | + (ContextPipeline, '__call__', context_pipeline_wrapper), |
| 117 | + (BasicCrawler, '_BasicCrawler__run_task_function', self._simple_async_wrapper), |
| 118 | + (BasicCrawler, '_commit_request_handler_result', _commit_request_handler_result_wrapper), |
| 119 | + ] |
| 120 | + ) |
| 121 | + |
| 122 | + def instrumentation_dependencies(self) -> list[str]: |
| 123 | + """Return a list of python packages with versions that will be instrumented.""" |
| 124 | + return ['crawlee'] |
| 125 | + |
| 126 | + def _instrument_all_public_methods(self, on_class: type) -> None: |
| 127 | + public_coroutines = { |
| 128 | + name |
| 129 | + for name, member in inspect.getmembers(on_class, predicate=inspect.iscoroutinefunction) |
| 130 | + if not name.startswith('_') |
| 131 | + } |
| 132 | + public_methods = { |
| 133 | + name |
| 134 | + for name, member in inspect.getmembers(on_class, predicate=inspect.isfunction) |
| 135 | + if not name.startswith('_') |
| 136 | + } - public_coroutines |
| 137 | + |
| 138 | + for coroutine in public_coroutines: |
| 139 | + self._instrumented.append((on_class, coroutine, self._simple_async_wrapper)) |
| 140 | + |
| 141 | + for method in public_methods: |
| 142 | + self._instrumented.append((on_class, method, self._simple_wrapper)) |
| 143 | + |
| 144 | + self._instrumented.append((on_class, '__init__', self._init_wrapper)) |
| 145 | + |
| 146 | + def _instrument(self, **_: Any) -> None: |
| 147 | + for _class, method, wrapper in self._instrumented: |
| 148 | + wrap_function_wrapper(_class, method, wrapper) |
| 149 | + |
| 150 | + def _uninstrument(self, **_: Any) -> None: |
| 151 | + for _class, method, __ in self._instrumented: |
| 152 | + unwrap(_class, method) |
0 commit comments