通过 OpenTelemetry Python SDK 实现进程内异步场景上下文传递

更新时间:
复制 MD 格式

接入 ARMS 应用监控后,ARMS 探针对常见 Python 异步框架自动埋点,Trace 上下文自动透传。但生产者消费者模式、线程池任务提交等场景下,上下文无法自动传递。通过 OpenTelemetry Python SDK 的 context.attach/context.detach 机制手动传递 Trace 上下文,可保证完整的调用链路。

前提条件

使用场景

接入 ARMS 应用监控后,如果应用通过以下方式实现异步编程,由于 ARMS 探针已对这些框架埋点,Trace 上下文会自动透传,无需改造代码:

  • 使用 asyncio 进行协程异步编程。

  • 使用 aiohttp、FastAPI、Starlette 等异步框架处理请求。

  • 使用 celery 进行异步任务处理。

ARMS 探针支持的组件和框架参见ARMS 应用监控支持的 Python 组件和框架。

如果应用存在以下异步处理场景,则需要通过 OpenTelemetry Python SDK 手动传递 Trace 上下文:

  • 生产者消费者场景:线程 T1 将消息放入队列后,线程 T2 从队列拉取消息处理,此时线程 T2 需要复用线程 T1 的 Trace 上下文。

  • 线程池任务提交场景:主线程将任务提交到 concurrent.futures.ThreadPoolExecutor 执行,子线程需要复用主线程的 Trace 上下文。

  • asyncio.Queue 跨协程传递场景:asyncio 常规协程调度时上下文可自动透传,但通过 asyncio.Queue 传递消息时,上下文不会自动跟随消息传递到消费侧协程,需要手动传递。

安装 OpenTelemetry Python SDK

执行以下命令安装 OpenTelemetry Python SDK,其他安装方式参见 OpenTelemetry 官方文档。

pip install opentelemetry-api
说明

ARMS Python 探针目前支持的 OpenTelemetry API 版本范围为:opentelemetry-api <= 1.39.0。确保安装的 opentelemetry-api 版本在此范围内。

场景一:生产者消费者模式(使用 queue.Queue)

以下示例展示了生产者消费者模式下的上下文传递。生产者线程将当前 Trace 上下文随事件一并放入队列,消费者线程取出事件后还原上下文。

import queue
import threading
from opentelemetry import context, trace

tracer = trace.get_tracer("manual-sdk", "1.0.0")


class Event:
    """事件实体,携带 Trace 上下文"""
    def __init__(self, ctx, msg):
        self.context = ctx  # 保存生产者的 Trace 上下文
        self.msg = msg


# 共享队列
event_queue = queue.Queue()


def produce(msg):
    """生产者:将当前 Trace 上下文一并放入事件"""
    event = Event(context.get_current(), msg)
    event_queue.put(event)


def consume():
    """消费者:取出事件并还原 Trace 上下文"""
    event = event_queue.get()

    # 还原生产者的 Trace 上下文
    token = context.attach(event.context)
    try:
        process_event(event)
    finally:
        context.detach(token)


def process_event(event):
    """处理事件,此时当前上下文为生产者的 Trace 上下文"""
    with tracer.start_as_current_span("process-event") as span:
        span.set_attribute("event.msg", event.msg)
        print(f"Processing event: {event.msg}")
        # 此 Span 将作为生产者 Span 的子 Span
        current_span = trace.get_current_span()
        print(f"traceId = {format(current_span.get_span_context().trace_id, '032x')}")

运行代码后,消费者线程中 process_event 打印的 traceId 应与生产者线程的 traceId 一致,表示上下文传递成功。

场景二:线程池任务提交

当使用 concurrent.futures.ThreadPoolExecutor 提交任务时,需要手动将 Trace 上下文传递给子线程。

import concurrent.futures
from opentelemetry import context, trace

tracer = trace.get_tracer("manual-sdk", "1.0.0")


def task_with_context(ctx, task_id):
    """在子线程中还原 Trace 上下文并执行业务逻辑"""
    token = context.attach(ctx)
    try:
        with tracer.start_as_current_span(f"thread-task-{task_id}") as span:
            span.set_attribute("task.id", task_id)
            # 此 Span 将作为主线程 Span 的子 Span
            current_span = trace.get_current_span()
            print(f"Task {task_id} traceId = {format(current_span.get_span_context().trace_id, '032x')}")
    finally:
        context.detach(token)


def submit_tasks():
    """主线程:提交任务到线程池,传递当前 Trace 上下文"""
    with tracer.start_as_current_span("submit-tasks") as span:
        # 获取当前上下文
        current_ctx = context.get_current()

        with concurrent.futures.ThreadPoolExecutor(max_workers=4) as executor:
            futures = []
            for i in range(5):
                # 将当前上下文作为参数传递给子线程
                future = executor.submit(task_with_context, current_ctx, i)
                futures.append(future)

            # 等待所有任务完成
            concurrent.futures.wait(futures)

运行代码后,每个子线程任务打印的 traceId 应与主线程(submit_tasks 中创建的 Span)的 traceId 一致,表示上下文传递成功。

场景三:asyncio 协程间手动传递上下文(使用 asyncio.Queue)

asyncio 常规协程调度时上下文可自动透传,但通过 asyncio.Queue 传递消息时,上下文不会自动跟随。以下示例展示了如何通过 asyncio.Queue 跨协程手动传递上下文。

import asyncio
from opentelemetry import context, trace

tracer = trace.get_tracer("manual-sdk", "1.0.0")


class AsyncEvent:
    def __init__(self, ctx, msg):
        self.context = ctx
        self.msg = msg


async def async_produce(async_queue, msg):
    """异步生产者"""
    event = AsyncEvent(context.get_current(), msg)
    await async_queue.put(event)


async def async_consume(async_queue):
    """异步消费者"""
    event = await async_queue.get()

    # 还原生产者的 Trace 上下文
    token = context.attach(event.context)
    try:
        with tracer.start_as_current_span("async-process-event") as span:
            span.set_attribute("event.msg", event.msg)
            print(f"Async processing: {event.msg}")
    finally:
        context.detach(token)


async def main():
    async_queue = asyncio.Queue()

    with tracer.start_as_current_span("async-producer"):
        await async_produce(async_queue, "hello async")

    await async_consume(async_queue)

运行代码后,async_consume 创建的 async-process-event Span 应作为 async-producer Span 的子 Span 出现于调用链,表示上下文传递成功。

context.attach/detach 使用约束

  1. 必须使用 context.detach(token) 恢复上下文:还原 Trace 上下文后,务必通过 finally 块调用 context.detach(token),确保上下文正确清理,避免上下文泄漏。

  2. context.get_current() 是快照操作:调用 context.get_current() 会获取调用时刻的上下文快照,后续对上下文的修改不会影响已保存的快照。确保选择正确的时机获取上下文。

  3. 避免跨进程直接传递 Context 对象:Context 对象是进程内的数据结构,不能直接序列化传递到其他进程。跨进程场景参见通过 OpenTelemetry Python SDK 实现跨进程上下文传递。