Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,21 @@


![pyversions](https://img.shields.io/pypi/pyversions/connect-extension-runner.svg) [![PyPi Status](https://img.shields.io/pypi/v/connect-extension-runner.svg)](https://pypi.org/project/connect-extension-runner/) [![Build Connect Reports Core](https://github.com/cloudblue/connect-extension-runner/actions/workflows/build.yml/badge.svg)](https://github.com/cloudblue/connect-extension-runner/actions/workflows/build.yml) [![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=cloudblue_connect-extension-runner&metric=alert_status)](https://sonarcloud.io/dashboard?id=cloudblue_connect-extension-runner) [![Coverage](https://sonarcloud.io/api/project_badges/measure?project=cloudblue_connect-extension-runner&metric=coverage)](https://sonarcloud.io/dashboard?id=cloudblue_connect-extension-runner) [![Maintainability Rating](https://sonarcloud.io/api/project_badges/measure?project=cloudblue_connect-extension-runner&metric=sqale_rating)](https://sonarcloud.io/dashboard?id=cloudblue_connect-extension-runner)![Docker Image Version (latest semver)](https://img.shields.io/docker/v/cloudblueconnect/connect-extension-runner?label=docker%20version&sort=semver)![Docker Image Size (latest semver)](https://img.shields.io/docker/image-size/cloudblueconnect/connect-extension-runner?label=docker%20image%20size&sort=semver)![Docker Pulls](https://img.shields.io/docker/pulls/cloudblueconnect/connect-extension-runner)

## Interactive task tracing

To export interactive task spans from an events worker, set
`OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` to your OTLP/HTTP collector's full traces URL
(for example, `http://collector:4318/v1/traces`). The worker also supports
`OTEL_EXPORTER_OTLP_ENDPOINT` as a base URL. Configure the collector to forward to
the tracing backend used by the EaaS gateway. An existing OpenTelemetry provider
in the worker takes precedence. The runner also works without an exporter.

For a sampled task carrying a W3C traceparent in `connect_correlation_id`, find
`runner.interactive` by `eaas.task.id`. Its start to the start of
`runner.interactive.handler` includes argument preparation and scheduling.
The handler span covers the actual extension call, including synchronous calls
on executor threads. Instrumented dependencies can create children in that context.
The interval from `result.queued` to `result.dequeued` measures result queue
wait. Each `websocket.send` event marks a send attempt. The parent ends after
the result is sent, delivery fails, or the worker stops.
14 changes: 11 additions & 3 deletions connect/eaas/runner/handlers/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@
abstractmethod,
)

from opentelemetry.trace.propagation.tracecontext import (
TraceContextTextMapPropagator,
)

from connect.client import (
AsyncConnectClient,
ConnectClient,
Expand Down Expand Up @@ -142,9 +146,13 @@ def _create_client(self, event_type, task_id, method_name, api_key, connect_corr
default_headers.update(self._config.get_user_agent())

if connect_correlation_id:
operation_id = connect_correlation_id[3:34]
span_id = os.urandom(8).hex()
correlation_id = f'00-{operation_id}-{span_id}-01'
carrier = {}
TraceContextTextMapPropagator().inject(carrier)
correlation_id = carrier.get('traceparent')
if not correlation_id or correlation_id[3:35] != connect_correlation_id[3:35]:
operation_id = connect_correlation_id[3:34]
span_id = os.urandom(8).hex()
correlation_id = f'00-{operation_id}-{span_id}-01'
default_headers['ext-traceparent'] = correlation_id

return Client(
Expand Down
7 changes: 4 additions & 3 deletions connect/eaas/runner/managers/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ async def filter_collection_by_event_definition(self, client, task_data):

async def submit(self, task_data):
"""
Submit a new task for its processing.
Submit a new task. Return True when processing or an error response was scheduled.

:param task_data: Task data.
:type task_data: connect.eaas.core.proto.Task
Expand Down Expand Up @@ -137,19 +137,20 @@ async def submit(self, task_data):

logger.info(f'invoke method {method.__name__} for task {task_data.options.task_id}')
await self.invoke(task_data, method, argument)
return True
except ClientError as ce:
logger.warning(
f'Cannot retrieve object {task_data.input.object_id} '
f'for task {task_data.options.task_id}',
)
self.send_exception_response(task_data, ce)
return
return True
except Exception as e:
logger.error(
f'Exceptions while processing task {task_data.options.task_id}',
)
self.send_exception_response(task_data, e)
return
return True

def send_exception_response(self, data, e):
"""
Expand Down
6 changes: 6 additions & 0 deletions connect/eaas/runner/managers/interactive.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,19 @@
from connect.eaas.runner.managers.base import (
TasksManagerBase,
)
from connect.eaas.runner.tracing import (
traced_handler,
)


logger = logging.getLogger(__name__)


class InteractiveTasksManager(TasksManagerBase):

async def invoke(self, task_data, method, argument):
await super().invoke(task_data, traced_handler(method), argument)

def get_method_name(self, task_data, argument):
return self.handler.events[task_data.input.event_type]['method']

Expand Down
98 changes: 98 additions & 0 deletions connect/eaas/runner/tracing.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
#
# This file is part of the CloudBlue Connect EaaS Extension Runner.
#
import inspect
import os
from contextlib import (
contextmanager,
)
from functools import (
wraps,
)

from opentelemetry import (
trace,
)
from opentelemetry.context import (
Context,
)
from opentelemetry.exporter.otlp.proto.http.trace_exporter import (
OTLPSpanExporter,
)
from opentelemetry.sdk.resources import (
Resource,
)
from opentelemetry.sdk.trace import (
TracerProvider,
)
from opentelemetry.sdk.trace.export import (
BatchSpanProcessor,
)
from opentelemetry.trace.propagation.tracecontext import (
TraceContextTextMapPropagator,
)


tracer = trace.get_tracer(__name__)


def configure_worker_tracing():
"""Initialize the exporter in the event worker, after multiprocessing starts."""
if not (
os.environ.get('OTEL_EXPORTER_OTLP_TRACES_ENDPOINT')
or os.environ.get('OTEL_EXPORTER_OTLP_ENDPOINT')
):
return
if os.environ.get('OTEL_SDK_DISABLED', '').lower() == 'true':
return
if isinstance(trace.get_tracer_provider(), trace.ProxyTracerProvider):
provider = TracerProvider(resource=Resource.create({
'service.name': os.environ.get('OTEL_SERVICE_NAME', 'connect-extension-runner'),
}))
provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter()))
trace.set_tracer_provider(provider)
return provider


def start_interactive_span(task):
parent = TraceContextTextMapPropagator().extract(
{'traceparent': task.options.connect_correlation_id or ''}, context=Context(),
)
if not trace.get_current_span(parent).get_span_context().is_valid:
return
return tracer.start_span(
'runner.interactive', context=parent, kind=trace.SpanKind.CONSUMER,
attributes={'eaas.task.id': task.options.task_id},
)


@contextmanager
def handler_span(parent):
with tracer.start_as_current_span(
'runner.interactive.handler', context=trace.set_span_in_context(parent),
record_exception=False, set_status_on_exception=False,
) as span:
try:
yield
except BaseException:
span.set_status(trace.StatusCode.ERROR)
raise


def traced_handler(method):
parent = trace.get_current_span()
if not parent.is_recording():
return method

if inspect.iscoroutinefunction(method):
@wraps(method)
async def call_async(*args):
with handler_span(parent):
return await method(*args)
return call_async

@wraps(method)
def call_sync(*args):
with handler_span(parent):
return method(*args)
return call_sync
Loading