|
| 1 | +# Copyright 2021 Google |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# https://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +import contextlib |
| 16 | +import os |
| 17 | +from typing import Iterator |
| 18 | + |
| 19 | +from flask import Flask, Response, request |
| 20 | +from opentelemetry.exporter.cloud_trace import CloudTraceSpanExporter |
| 21 | +from opentelemetry.sdk.trace import TracerProvider |
| 22 | +from opentelemetry.sdk.trace.export import BatchSpanProcessor |
| 23 | +from opentelemetry.sdk.trace.sampling import ALWAYS_ON |
| 24 | +from opentelemetry.trace import Tracer |
| 25 | + |
| 26 | +TEST_ID = "test-id" |
| 27 | +INSTRUMENTING_MODULE_NAME = "opentelemetry-ops-e2e-test-server" |
| 28 | + |
| 29 | +app = Flask(__name__) |
| 30 | + |
| 31 | + |
| 32 | +@contextlib.contextmanager |
| 33 | +def common_setup() -> Iterator[tuple[str, Tracer]]: |
| 34 | + """\ |
| 35 | + Context manager with common setup for test endpoints |
| 36 | +
|
| 37 | + It extracts the test-id header, creates a tracer, and finally flushes |
| 38 | + spans created during the test |
| 39 | + """ |
| 40 | + |
| 41 | + if TEST_ID not in request.headers: |
| 42 | + raise Exception(f"{TEST_ID} header is required") |
| 43 | + test_id = request.headers[TEST_ID] |
| 44 | + |
| 45 | + tracer_provider = TracerProvider( |
| 46 | + sampler=ALWAYS_ON, |
| 47 | + active_span_processor=BatchSpanProcessor( |
| 48 | + CloudTraceSpanExporter(project_id=os.environ.get("PROJECT_ID")) |
| 49 | + ), |
| 50 | + ) |
| 51 | + tracer = tracer_provider.get_tracer(INSTRUMENTING_MODULE_NAME) |
| 52 | + |
| 53 | + try: |
| 54 | + yield test_id, tracer |
| 55 | + finally: |
| 56 | + tracer_provider.shutdown() |
| 57 | + |
| 58 | + |
| 59 | +@app.route("/health") |
| 60 | +def health(): |
| 61 | + return "OK", 200 |
| 62 | + |
| 63 | + |
| 64 | +@app.route("/basicTrace", methods=["POST"]) |
| 65 | +def basicTrace(): |
| 66 | + """Create a basic trace""" |
| 67 | + |
| 68 | + with common_setup() as (test_id, tracer): |
| 69 | + with tracer.start_span("basicTrace", attributes={TEST_ID: test_id}): |
| 70 | + pass |
| 71 | + |
| 72 | + return Response(status=200) |
0 commit comments