Пример #1
0
def test_tracer_with_extra_context():
    app = Starlette()
    mocked_tracer = MockTracer(scope_manager=ContextVarsScopeManager())

    app.add_middleware(StarletteTracingMiddleWare, tracer=mocked_tracer)

    @app.route("/foo/")
    def foo(request):
        return PlainTextResponse("Foo")

    external_tracer = MockTracer(scope_manager=ContextVarsScopeManager())
    external_tracer.start_active_span("EXTERNAL")

    # Prepare headers
    headers = {}
    external_tracer.inject(external_tracer.active_span.context,
                           opentracing.Format.TEXT_MAP, headers)
    client = TestClient(app)
    client.get("/foo", headers=headers)

    external_tracer.active_span.finish()

    spans = mocked_tracer.finished_spans()
    assert len(spans) == 2
    urls = [span.tags.get("http.url") for span in spans]
    assert "http://testserver:80/foo?b''" in urls

    # Todo: more asserts; still not sure if we should have 3 finished spans in the external tracer
    spans = external_tracer.finished_spans()
    assert len(spans) == 1
Пример #2
0
    async def test_publish_injects_tracing(self):
        app = kafkaesk.Application(kafka_servers=["foo"])
        producer = AsyncMock()
        producer.send.return_value = fut = asyncio.Future()
        fut.set_result("ok")
        app._get_producer = AsyncMock(return_value=producer)
        config = Config(
            config={
                "sampler": {
                    "type": "const",
                    "param": 1
                },
                "logging": True,
                "propagation": "b3"
            },
            service_name="test_service",
            scope_manager=ContextVarsScopeManager(),
        )
        # this call also sets opentracing.tracer
        tracer = config.initialize_tracer()

        span = tracer.start_span(operation_name="dummy")
        tracer.scope_manager.activate(span, True)

        future = await app.raw_publish("foobar", b"foobar")
        await future

        headers = producer.mock_calls[0].kwargs["headers"]
        assert str(span).startswith(headers[0][1].decode())
Пример #3
0
def init_tracer(app_name, agent_hostname, agent_port):
    tracer = Tracer(
        app_name,
        config={
            "agent_hostname": agent_hostname,
            "agent_port": agent_port
        },
        scope_manager=ContextVarsScopeManager(),
    )
    set_global_tracer(tracer)
    return tracer
Пример #4
0
def test_init_empty():
    composed_tracer = ComposedTracer([],
                                     scope_manager=ContextVarsScopeManager())

    with composed_tracer.start_active_span("foo") as scope:
        scope.span.set_tag("foo", "bar")
        scope.span.log_kv("event", "hi")

        carrier: dict = {}
        composed_tracer.inject(scope.span.context, Format.TEXT_MAP, carrier)
        assert carrier == {}
Пример #5
0
async def notify_server_started(app, loop):
    config = Config(config={
        'sampler': {
            'type': 'const',
            'param': 1,
        },
        'logging': True,
    },
                    service_name="inventory",
                    validate=True,
                    scope_manager=ContextVarsScopeManager())
    config.initialize_tracer()
Пример #6
0
    async def test_publish_injects_tracing(self):
        app = kafkaesk.Application(kafka_servers=["foo"])
        producer = AsyncMock()
        app._get_producer = AsyncMock(return_value=producer)

        tracer = opentracing.global_tracer()
        tracer._scope_manager = ContextVarsScopeManager()

        tracer.scope_manager.activate("foobar", True)

        with patch.object(tracer, "inject") as mock:
            await app.raw_publish("foobar", b"foobar")
            mock.assert_called_once()
Пример #7
0
def arrange_scope_manager(scope_manager):
    if scope_manager is None:
        try:
            import sys
            if (sys.version_info[0] > 3) or (sys.version_info[0] == 3
                                             and sys.version_info[1] > 7) or (
                                                 sys.version_info[0] == 3
                                                 and sys.version_info[1] == 7
                                                 and sys.version_info[2] != 0):
                from opentracing.scope_managers.contextvars import ContextVarsScopeManager
                scope_manager = ContextVarsScopeManager()
            else:
                scope_manager = ThreadLocalScopeManager()
        except Exception:
            scope_manager = ThreadLocalScopeManager()
    return scope_manager
Пример #8
0
def initialize_jaeger(service_name):
    install_all_patches()
    config = Config(
        config={
            "sampler": {
                "type": "const",
                "param": 1,
            },
            "logging": True,
        },
        service_name=service_name,
        validate=True,
        scope_manager=ContextVarsScopeManager(),
        metrics_factory=PrometheusMetricsFactory(namespace=service_name),
    )
    return config.initialize_tracer()
Пример #9
0
def test_init_mock():
    mock_tracer = MockTracer()
    composed_tracer = ComposedTracer([mock_tracer],
                                     scope_manager=ContextVarsScopeManager())

    with composed_tracer.start_active_span("foo") as scope:
        scope.span.set_tag("foo", "bar")
        scope.span.log_kv("event", "hi")

        carrier: dict = {}
        composed_tracer.inject(scope.span.context, Format.TEXT_MAP, carrier)
        assert carrier == {"ot-tracer-traceid": "2", "ot-tracer-spanid": "1"}

        extracted = composed_tracer.extract(Format.TEXT_MAP, carrier)
        assert len(extracted.composed_contexts) == 1
        mock_context = extracted.composed_contexts[0]
        assert mock_context.span_id == 1
        assert mock_context.trace_id == 2
Пример #10
0
def call_external_api():
    # Note: Using requests instead of httpx here so you can see the effect of `install_all_patches()`
    try:
        r = requests.get("https://api.github.com/events")
        r.raise_for_status()
    except requests.exceptions.HTTPError as err:
        return {"title": "Call external API", "content": {"error": str(err)}}
    return {"title": "Call external API", "content": r.json()}


opentracing_config = jaeger_config(
    config={
        "sampler": {
            "type": "const",
            "param": 1
        },
        "logging": False,
        "local_agent": {
            "reporting_host": "localhost"
        },
    },
    scope_manager=ContextVarsScopeManager(),
    service_name="FastAPI tracer example",
)
jaeger_tracer = opentracing_config.initialize_tracer()
install_all_patches()
app.add_middleware(StarletteTracingMiddleWare, tracer=jaeger_tracer)

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)
Пример #11
0
 def setUp(self):
     self.tracer = MockTracer(ContextVarsScopeManager())
     self.loop = asyncio.get_event_loop()
     self.client = Client(RequestHandler(self.tracer), self.loop)
Пример #12
0
 def setUp(self):
     self.tracer = MockTracer(ContextVarsScopeManager())
     self.loop = asyncio.get_event_loop()
Пример #13
0
 def setUp(self):
     self.tracer = MockTracer(ContextVarsScopeManager())
     self.queue = asyncio.Queue()
     self.loop = asyncio.get_event_loop()
     self.server = Server(tracer=self.tracer, queue=self.queue)
Пример #14
0
 def scope_manager(self):
     return ContextVarsScopeManager()