|
| 1 | +# Copyright (c) Microsoft Corporation. |
| 2 | +# Licensed under the MIT License. |
| 3 | + |
| 4 | +"""Distributed tracing example using OpenTelemetry and Jaeger. |
| 5 | +
|
| 6 | +This example demonstrates how to configure OpenTelemetry distributed tracing |
| 7 | +with the Durable Task Python SDK. The orchestration showcases timers, |
| 8 | +activities, and a sub-orchestration, all producing correlated trace spans |
| 9 | +visible in the Jaeger UI. |
| 10 | +
|
| 11 | +Prerequisites: |
| 12 | + - DTS emulator running on localhost:8080 |
| 13 | + - Jaeger running on localhost:4317 (OTLP gRPC) / localhost:16686 (UI) |
| 14 | + - pip install -r requirements.txt |
| 15 | +""" |
| 16 | + |
| 17 | +import os |
| 18 | +import time |
| 19 | +from datetime import timedelta |
| 20 | + |
| 21 | +from opentelemetry import trace |
| 22 | +from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter |
| 23 | +from opentelemetry.sdk.resources import Resource |
| 24 | +from opentelemetry.sdk.trace import TracerProvider |
| 25 | +from opentelemetry.sdk.trace.export import BatchSpanProcessor |
| 26 | + |
| 27 | +from azure.identity import DefaultAzureCredential |
| 28 | + |
| 29 | +from durabletask import client, task |
| 30 | +from durabletask.azuremanaged.client import DurableTaskSchedulerClient |
| 31 | +from durabletask.azuremanaged.worker import DurableTaskSchedulerWorker |
| 32 | + |
| 33 | + |
| 34 | +# --------------------------------------------------------------------------- |
| 35 | +# OpenTelemetry configuration — MUST be done before any spans are created |
| 36 | +# --------------------------------------------------------------------------- |
| 37 | + |
| 38 | +OTEL_ENDPOINT = os.getenv("OTEL_EXPORTER_OTLP_ENDPOINT", "http://localhost:4317") |
| 39 | + |
| 40 | +resource = Resource.create({"service.name": "durabletask-tracing-example"}) |
| 41 | +provider = TracerProvider(resource=resource) |
| 42 | +provider.add_span_processor( |
| 43 | + BatchSpanProcessor( |
| 44 | + OTLPSpanExporter(endpoint=OTEL_ENDPOINT, insecure=True) |
| 45 | + ) |
| 46 | +) |
| 47 | +trace.set_tracer_provider(provider) |
| 48 | + |
| 49 | + |
| 50 | +# --------------------------------------------------------------------------- |
| 51 | +# Activity functions |
| 52 | +# --------------------------------------------------------------------------- |
| 53 | + |
| 54 | +def get_weather(ctx: task.ActivityContext, city: str) -> str: |
| 55 | + """Simulate fetching weather data for a city.""" |
| 56 | + # In a real app this would call an external API |
| 57 | + weather_data = { |
| 58 | + "Tokyo": "Sunny, 22°C", |
| 59 | + "Seattle": "Rainy, 12°C", |
| 60 | + "London": "Cloudy, 15°C", |
| 61 | + } |
| 62 | + result = weather_data.get(city, "Unknown") |
| 63 | + print(f" [Activity] get_weather({city}) -> {result}") |
| 64 | + return result |
| 65 | + |
| 66 | + |
| 67 | +def summarize(ctx: task.ActivityContext, reports: list) -> str: |
| 68 | + """Combine individual weather reports into a summary string.""" |
| 69 | + summary = " | ".join(reports) |
| 70 | + print(f" [Activity] summarize -> {summary}") |
| 71 | + return summary |
| 72 | + |
| 73 | + |
| 74 | +# --------------------------------------------------------------------------- |
| 75 | +# Sub-orchestration |
| 76 | +# --------------------------------------------------------------------------- |
| 77 | + |
| 78 | +def collect_weather(ctx: task.OrchestrationContext, cities: list): |
| 79 | + """Sub-orchestration that collects weather for a list of cities.""" |
| 80 | + results = [] |
| 81 | + for city in cities: |
| 82 | + weather = yield ctx.call_activity(get_weather, input=city) |
| 83 | + results.append(f"{city}: {weather}") |
| 84 | + return results |
| 85 | + |
| 86 | + |
| 87 | +# --------------------------------------------------------------------------- |
| 88 | +# Main orchestration |
| 89 | +# --------------------------------------------------------------------------- |
| 90 | + |
| 91 | +def weather_report_orchestrator(ctx: task.OrchestrationContext, cities: list): |
| 92 | + """Top-level orchestration demonstrating timers, activities, and sub-orchestrations. |
| 93 | +
|
| 94 | + Flow: |
| 95 | + 1. Wait for a short timer (simulating a scheduled delay). |
| 96 | + 2. Call a sub-orchestration to collect weather data for each city. |
| 97 | + 3. Call an activity to summarize the results. |
| 98 | + """ |
| 99 | + # Step 1 — Timer: wait briefly before starting work |
| 100 | + yield ctx.create_timer(timedelta(seconds=2)) |
| 101 | + if not ctx.is_replaying: |
| 102 | + print(" [Orchestrator] Timer fired — starting weather collection") |
| 103 | + |
| 104 | + # Step 2 — Sub-orchestration: delegate city-level work |
| 105 | + reports = yield ctx.call_sub_orchestrator(collect_weather, input=cities) |
| 106 | + |
| 107 | + # Step 3 — Activity: summarize the collected reports |
| 108 | + summary = yield ctx.call_activity(summarize, input=reports) |
| 109 | + |
| 110 | + return summary |
| 111 | + |
| 112 | + |
| 113 | +# --------------------------------------------------------------------------- |
| 114 | +# Entry point |
| 115 | +# --------------------------------------------------------------------------- |
| 116 | + |
| 117 | +if __name__ == "__main__": |
| 118 | + # Use environment variables if provided, otherwise use default emulator values |
| 119 | + taskhub_name = os.getenv("TASKHUB", "default") |
| 120 | + endpoint = os.getenv("ENDPOINT", "http://localhost:8080") |
| 121 | + |
| 122 | + print(f"Using taskhub: {taskhub_name}") |
| 123 | + print(f"Using endpoint: {endpoint}") |
| 124 | + print(f"OTLP endpoint: {OTEL_ENDPOINT}") |
| 125 | + |
| 126 | + # Set credential to None for emulator, or DefaultAzureCredential for Azure |
| 127 | + secure_channel = endpoint.startswith("https://") |
| 128 | + credential = DefaultAzureCredential() if secure_channel else None |
| 129 | + |
| 130 | + with DurableTaskSchedulerWorker( |
| 131 | + host_address=endpoint, |
| 132 | + secure_channel=secure_channel, |
| 133 | + taskhub=taskhub_name, |
| 134 | + token_credential=credential, |
| 135 | + ) as w: |
| 136 | + # Register orchestrators and activities |
| 137 | + w.add_orchestrator(weather_report_orchestrator) |
| 138 | + w.add_orchestrator(collect_weather) |
| 139 | + w.add_activity(get_weather) |
| 140 | + w.add_activity(summarize) |
| 141 | + w.start() |
| 142 | + print("Worker started.") |
| 143 | + |
| 144 | + # Create client, schedule the orchestration, and wait for completion |
| 145 | + c = DurableTaskSchedulerClient( |
| 146 | + host_address=endpoint, |
| 147 | + secure_channel=secure_channel, |
| 148 | + taskhub=taskhub_name, |
| 149 | + token_credential=credential, |
| 150 | + ) |
| 151 | + |
| 152 | + cities = ["Tokyo", "Seattle", "London"] |
| 153 | + instance_id = c.schedule_new_orchestration( |
| 154 | + weather_report_orchestrator, input=cities, |
| 155 | + ) |
| 156 | + print(f"Orchestration started: {instance_id}") |
| 157 | + |
| 158 | + state = c.wait_for_orchestration_completion(instance_id, timeout=60) |
| 159 | + if state and state.runtime_status == client.OrchestrationStatus.COMPLETED: |
| 160 | + print(f"Orchestration completed! Result: {state.serialized_output}") |
| 161 | + elif state: |
| 162 | + print(f"Orchestration failed: {state.failure_details}") |
| 163 | + |
| 164 | + # Flush any remaining spans to the exporter |
| 165 | + provider.force_flush() |
| 166 | + time.sleep(1) |
| 167 | + |
| 168 | + print("Done. Open Jaeger at http://localhost:16686 to view traces.") |
0 commit comments