-
- 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
base: master
Are you sure you want to change the base?
Changes from 1 commit
fbe4b78 b09c4f1 41eef7f 78aa5ee 2d856ee e7614c9 e1e3bf1 4ae2e65 a877aa1 1b2107b File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
| @@ -0,0 +1,138 @@ | ||||||
| """ | ||||||
| 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.on_event(TaskiqEvents.WORKER_STARTUP) | ||||||
| async def startup(state: TaskiqState) -> None: | ||||||
| ||||||
| TaskiqInstrumentor().instrument() | ||||||
| @broker.task | ||||||
| async def add(x, y): | ||||||
| return x + y | ||||||
| async def main(): | ||||||
| await broker.startup() | ||||||
| await my_task.kiq(1, 2) | ||||||
| await broker.shutdown() | ||||||
| if __name__ == "__main__": | ||||||
| asyncio.run(main()) | ||||||
| API | ||||||
| --- | ||||||
| """ | ||||||
| | ||||||
| from __future__ import annotations | ||||||
| ||||||
| | ||||||
| import logging | ||||||
| from typing import TYPE_CHECKING, Any, Callable, Collection, Optional | ||||||
| from weakref import WeakSet as _WeakSet | ||||||
| | ||||||
| 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 | ||||||
| | ||||||
| from taskiq import AsyncBroker | ||||||
| from taskiq.middlewares.opentelemetry_middleware import OpenTelemetryMiddleware | ||||||
| | ||||||
| if TYPE_CHECKING: | ||||||
s3rius marked this conversation as resolved. Outdated Show resolved Hide resolved | ||||||
| pass | ||||||
| | ||||||
| logger = logging.getLogger("taskiq.opentelemetry") | ||||||
| | ||||||
| | ||||||
| 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", "AsyncBroker.__init__", broker_init) | ||||||
| ||||||
| wrap_function_wrapper("taskiq", "AsyncBroker.__init__", broker_init) | |
| wrap_function_wrapper("taskiq.abc.broker", "AsyncBroker.__init__", broker_init) |
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.
Why
pragma: allowlist secretis here?As I see, we already exclude this file from
detect-secretspre-commit hook check. Is some other linter checks fails on this lines?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.
even with exclusion in
.pre-commit-config.yaml, still seeing this without pragmasThere 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.
Thats strange...
I checked on my fork and anything seems to be fine:
Are you sure that you run
poetry install --all-extras && pre-commit installafter rebase? I don't really know that else can be a problemUh oh!
There was an error while loading. Please reload this page.
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.
In any case - it's not a blocker to merge this MR. I will deal with it later if we don't find the root cause of this strange pre-commit hook behaviour.
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.
I guess the root cause is me commiting from windows :)
On mac the exclusions are working as expected
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.
rollbacked the file