-
-
Notifications
You must be signed in to change notification settings - Fork 96
feat: Add OpenTelemetry instrumentation #525
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
soapun
wants to merge
11
commits into
taskiq-python:master
Choose a base branch
from
soapun:feat/add-otel-instrumentation
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 9 commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
fbe4b78
add opentelemetry instrumentation, suppress false-positive security c…
soapun b09c4f1
Merge branch 'master' into feat/add-otel-instrumentation
soapun 41eef7f
delete pytest.mark.anyio
soapun 78aa5ee
upd version from which otel is supported
soapun 2d856ee
delete pragmas
soapun e7614c9
delete unused statements
soapun e1e3bf1
fix example, change warning log to debug
soapun 4ae2e65
move span closuse to post_save,
soapun a877aa1
wrap worker_function to use sitecustomize
soapun 1b2107b
use initialize instead of sitecustomize
soapun a14150d
monkeypatch start_listen
soapun File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,157 @@ | ||
| """ | ||
| Instrument `taskiq`_ to trace Taskiq applications. | ||
|
|
||
| .. _taskiq: https://pypi.org/project/taskiq/ | ||
|
|
||
| Usage | ||
| ----- | ||
|
|
||
| * Run instrumented task | ||
|
|
||
| .. code:: python | ||
|
|
||
| import asyncio | ||
|
|
||
| from taskiq import InMemoryBroker, TaskiqEvents, TaskiqState | ||
| from taskiq.instrumentation import TaskiqInstrumentor | ||
|
|
||
| broker = InMemoryBroker() | ||
|
|
||
| @broker.task | ||
| async def add(x, y): | ||
| return x + y | ||
|
|
||
| async def main(): | ||
| TaskiqInstrumentor().instrument() | ||
| await broker.startup() | ||
| await my_task.kiq(1, 2) | ||
| await broker.shutdown() | ||
|
|
||
| if __name__ == "__main__": | ||
| asyncio.run(main()) | ||
|
|
||
| API | ||
| --- | ||
| """ | ||
|
|
||
|
|
||
| import logging | ||
| from functools import partial | ||
| from typing import Any, Callable, Collection, Optional | ||
| from weakref import WeakSet as _WeakSet | ||
|
|
||
| from taskiq.cli.worker.args import WorkerArgs | ||
|
|
||
| try: | ||
| import opentelemetry # noqa: F401 | ||
| except ImportError as exc: | ||
| raise ImportError( | ||
| "Cannot instrument. Please install 'taskiq[opentelemetry]'.", | ||
| ) from exc | ||
|
|
||
|
|
||
| from opentelemetry.instrumentation.instrumentor import ( # type: ignore[attr-defined] | ||
| BaseInstrumentor, | ||
| ) | ||
| from opentelemetry.instrumentation.utils import unwrap | ||
| from opentelemetry.metrics import MeterProvider | ||
| from opentelemetry.trace import TracerProvider | ||
| from wrapt import wrap_function_wrapper, wrap_object_attribute | ||
|
|
||
| from taskiq import AsyncBroker | ||
| from taskiq.cli.worker.process_manager import ProcessManager | ||
| from taskiq.middlewares.opentelemetry_middleware import OpenTelemetryMiddleware | ||
|
|
||
| logger = logging.getLogger("taskiq.opentelemetry") | ||
|
|
||
|
|
||
| def _worker_function_with_sitecustomize( | ||
| worker_function: Callable[[WorkerArgs], None], | ||
| *args: Any, | ||
| **kwargs: Any, | ||
| ) -> None: | ||
| import opentelemetry.instrumentation.auto_instrumentation.sitecustomize # noqa | ||
|
|
||
| return worker_function(*args, **kwargs) | ||
|
|
||
|
|
||
| def _worker_function_factory( | ||
| worker_function: Callable[[WorkerArgs], None], | ||
| ) -> Callable[[WorkerArgs], None]: | ||
| return partial(_worker_function_with_sitecustomize, worker_function) | ||
|
|
||
|
|
||
| class TaskiqInstrumentor(BaseInstrumentor): | ||
| """OpenTelemetry instrumentor for Taskiq.""" | ||
|
|
||
| _instrumented_brokers: _WeakSet[AsyncBroker] = _WeakSet() | ||
|
|
||
| def __init__(self) -> None: | ||
| super().__init__() | ||
| self._middleware = None | ||
|
|
||
| def instrument_broker( | ||
| self, | ||
| broker: AsyncBroker, | ||
| tracer_provider: Optional[TracerProvider] = None, | ||
| meter_provider: Optional[MeterProvider] = None, | ||
| ) -> None: | ||
| """Instrument broker.""" | ||
| if not hasattr(broker, "_is_instrumented_by_opentelemetry"): | ||
| broker._is_instrumented_by_opentelemetry = False # type: ignore[attr-defined] # noqa: SLF001 | ||
|
|
||
| if not getattr(broker, "is_instrumented_by_opentelemetry", False): | ||
| broker.middlewares.insert( | ||
| 0, | ||
| OpenTelemetryMiddleware( | ||
| tracer_provider=tracer_provider, | ||
| meter_provider=meter_provider, | ||
| ), | ||
| ) | ||
| broker._is_instrumented_by_opentelemetry = True # type: ignore[attr-defined] # noqa: SLF001 | ||
| if broker not in self._instrumented_brokers: | ||
| self._instrumented_brokers.add(broker) | ||
| else: | ||
| logger.warning( | ||
| "Attempting to instrument taskiq broker while already instrumented", | ||
| ) | ||
|
|
||
| def uninstrument_broker(self, broker: AsyncBroker) -> None: | ||
| """Uninstrument broker.""" | ||
| broker.middlewares = [ | ||
| middleware | ||
| for middleware in broker.middlewares | ||
| if not isinstance(middleware, OpenTelemetryMiddleware) | ||
| ] | ||
| broker._is_instrumented_by_opentelemetry = False # type: ignore[attr-defined] # noqa: SLF001 | ||
| self._instrumented_brokers.discard(broker) | ||
|
|
||
| def instrumentation_dependencies(self) -> Collection[str]: | ||
| """This function tells which library this instrumentor instruments.""" | ||
| return ("taskiq >= 0.0.1",) | ||
|
|
||
| def _instrument(self, **kwargs: Any) -> None: | ||
| def broker_init( | ||
| init: Callable[[Any], Any], | ||
| broker: AsyncBroker, | ||
| args: Any, | ||
| kwargs: Any, | ||
| ) -> None: | ||
| result = init(*args, **kwargs) | ||
| self.instrument_broker(broker) | ||
| return result | ||
|
|
||
| wrap_function_wrapper("taskiq.abc.broker", "AsyncBroker.__init__", broker_init) | ||
| wrap_object_attribute( | ||
|
||
| "taskiq.cli.worker.process_manager", | ||
| "ProcessManager.worker_function", | ||
| _worker_function_factory, | ||
| ) | ||
|
|
||
| def _uninstrument(self, **kwargs: Any) -> None: | ||
| instances_to_uninstrument = list(self._instrumented_brokers) | ||
| for broker in instances_to_uninstrument: | ||
| self.uninstrument_broker(broker) | ||
| self._instrumented_brokers.clear() | ||
| unwrap(AsyncBroker, "__init__") | ||
| delattr(ProcessManager, "worker_function") | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.