Skip to content

Commit

Permalink
aiohttp server
Browse files Browse the repository at this point in the history
  • Loading branch information
dmanchon authored and decko committed May 11, 2023
1 parent 8d0c504 commit 5a14c7d
Show file tree
Hide file tree
Showing 6 changed files with 156 additions and 15 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -55,4 +55,4 @@ test =

[options.entry_points]
opentelemetry_instrumentor =
aiohttp-server = opentelemetry.instrumentation.aiohttp_server:AioHttpInstrumentor
aiohttp-server = opentelemetry.instrumentation.aiohttp_server:AioHttpServerInstrumentor
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import urllib
from aiohttp import web
from guillotina.utils import get_dotted_name
from multidict import CIMultiDictProxy
from opentelemetry import context, trace
from opentelemetry.instrumentation.aiohttp_server.package import _instruments
Expand All @@ -19,7 +18,7 @@
_SUPPRESS_HTTP_INSTRUMENTATION_KEY = "suppress_http_instrumentation"

tracer = trace.get_tracer(__name__)
_excluded_urls = get_excluded_urls("FLASK")
_excluded_urls = get_excluded_urls("AIOHTTP_SERVER")


def get_default_span_details(request: web.Request) -> Tuple[str, dict]:
Expand All @@ -34,9 +33,9 @@ def get_default_span_details(request: web.Request) -> Tuple[str, dict]:


def _get_view_func(request) -> str:
"""TODO: is this only working for guillotina?"""
"""TODO: is this useful??"""
try:
return get_dotted_name(request.found_view)
return request.match_info.handler.__name__
except AttributeError:
return "unknown"

Expand Down Expand Up @@ -139,7 +138,7 @@ async def middleware(request, handler):
if (
context.get_value("suppress_instrumentation")
or context.get_value(_SUPPRESS_HTTP_INSTRUMENTATION_KEY)
or not _excluded_urls.url_disabled(request.url)
or _excluded_urls.url_disabled(request.url)
):
return await handler(request)

Expand Down Expand Up @@ -173,7 +172,7 @@ def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)


class AioHttpInstrumentor(BaseInstrumentor):
class AioHttpServerInstrumentor(BaseInstrumentor):
# pylint: disable=protected-access,attribute-defined-outside-init
"""An instrumentor for aiohttp.web.Application
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
# Copyright 2020, OpenTelemetry Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import asyncio
import contextlib
import typing
import unittest
import urllib.parse
from functools import partial
from http import HTTPStatus
from unittest import mock

import aiohttp
import aiohttp.test_utils
import yarl
from pkg_resources import iter_entry_points

from opentelemetry import context
from opentelemetry.instrumentation import aiohttp_server
from opentelemetry.instrumentation.aiohttp_server import (
AioHttpServerInstrumentor,
)
from opentelemetry.instrumentation.utils import _SUPPRESS_INSTRUMENTATION_KEY
from opentelemetry.semconv.trace import SpanAttributes
from opentelemetry.test.test_base import TestBase
from opentelemetry.trace import Span, StatusCode


def run_with_test_server(
runnable: typing.Callable, url: str, handler: typing.Callable
) -> typing.Tuple[str, int]:
async def do_request():
app = aiohttp.web.Application()
parsed_url = urllib.parse.urlparse(url)
app.add_routes([aiohttp.web.get(parsed_url.path, handler)])
app.add_routes([aiohttp.web.post(parsed_url.path, handler)])
app.add_routes([aiohttp.web.patch(parsed_url.path, handler)])

with contextlib.suppress(aiohttp.ClientError):
async with aiohttp.test_utils.TestServer(app) as server:
netloc = (server.host, server.port)
await server.start_server()
await runnable(server)
return netloc

loop = asyncio.get_event_loop()
return loop.run_until_complete(do_request())


class TestAioHttpServerIntegration(TestBase):
URL = "/test-path"

def setUp(self):
super().setUp()
AioHttpServerInstrumentor().instrument()

def tearDown(self):
super().tearDown()
AioHttpServerInstrumentor().uninstrument()

@staticmethod
# pylint:disable=unused-argument
async def default_handler(request, status=200):
return aiohttp.web.Response(status=status)

def assert_spans(self, num_spans: int):
finished_spans = self.memory_exporter.get_finished_spans()
self.assertEqual(num_spans, len(finished_spans))
if num_spans == 0:
return None
if num_spans == 1:
return finished_spans[0]
return finished_spans

@staticmethod
def get_default_request(url: str = URL):
async def default_request(server: aiohttp.test_utils.TestServer):
async with aiohttp.test_utils.TestClient(server) as session:
await session.get(url)

return default_request

def test_instrument(self):
host, port = run_with_test_server(
self.get_default_request(), self.URL, self.default_handler
)
span = self.assert_spans(1)
self.assertEqual("GET", span.attributes[SpanAttributes.HTTP_METHOD])
self.assertEqual(
f"http://{host}:{port}/test-path",
span.attributes[SpanAttributes.HTTP_URL],
)
self.assertEqual(200, span.attributes[SpanAttributes.HTTP_STATUS_CODE])

def test_status_codes(self):
error_handler = partial(self.default_handler, status=400)
host, port = run_with_test_server(
self.get_default_request(), self.URL, error_handler
)
span = self.assert_spans(1)
self.assertEqual("GET", span.attributes[SpanAttributes.HTTP_METHOD])
self.assertEqual(
f"http://{host}:{port}/test-path",
span.attributes[SpanAttributes.HTTP_URL],
)
self.assertEqual(400, span.attributes[SpanAttributes.HTTP_STATUS_CODE])

def test_not_recording(self):
mock_tracer = mock.Mock()
mock_span = mock.Mock()
mock_span.is_recording.return_value = False
mock_tracer.start_span.return_value = mock_span
with mock.patch("opentelemetry.trace.get_tracer"):
# pylint: disable=W0612
host, port = run_with_test_server(
self.get_default_request(), self.URL, self.default_handler
)

self.assertFalse(mock_span.is_recording())
self.assertTrue(mock_span.is_recording.called)
self.assertFalse(mock_span.set_attribute.called)
self.assertFalse(mock_span.set_status.called)
Original file line number Diff line number Diff line change
Expand Up @@ -103,13 +103,11 @@ def _is_installed(req):

def _find_installed_libraries():
libs = default_instrumentations[:]
libs.extend(
[
v["instrumentation"]
for _, v in libraries.items()
if _is_installed(v["library"])
]
)

for _, v in libraries.items():
if _is_installed(v["library"]):
libs.extend(v["instrumentation"])

return libs


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,10 @@
},
"aiohttp": {
"library": "aiohttp ~= 3.0",
"instrumentation": "opentelemetry-instrumentation-aiohttp-client==0.39b0.dev",
"instrumentation": [
"opentelemetry-instrumentation-aiohttp-client==0.39b0.dev",
"opentelemetry-instrumentation-aiohttp-server==0.39b0.dev",
],
},
"aiopg": {
"library": "aiopg >= 0.13.0, < 2.0.0",
Expand Down
8 changes: 8 additions & 0 deletions tox.ini
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,10 @@ envlist =
py3{7,8,9,10,11}-test-instrumentation-aiohttp-client
pypy3-test-instrumentation-aiohttp-client

; opentelemetry-instrumentation-aiohttp-server
py3{6,7,8,9,10}-test-instrumentation-aiohttp-server
pypy3-test-instrumentation-aiohttp-server

; opentelemetry-instrumentation-aiopg
py3{7,8,9,10,11}-test-instrumentation-aiopg
; instrumentation-aiopg intentionally excluded from pypy3
Expand Down Expand Up @@ -287,6 +291,7 @@ changedir =
test-opentelemetry-instrumentation: opentelemetry-instrumentation/tests
test-instrumentation-aio-pika: instrumentation/opentelemetry-instrumentation-aio-pika/tests
test-instrumentation-aiohttp-client: instrumentation/opentelemetry-instrumentation-aiohttp-client/tests
test-instrumentation-aiohttp-server: instrumentation/opentelemetry-instrumentation-aiohttp-server/tests
test-instrumentation-aiopg: instrumentation/opentelemetry-instrumentation-aiopg/tests
test-instrumentation-asgi: instrumentation/opentelemetry-instrumentation-asgi/tests
test-instrumentation-asyncpg: instrumentation/opentelemetry-instrumentation-asyncpg/tests
Expand Down Expand Up @@ -425,6 +430,8 @@ commands_pre =

aiohttp-client: pip install {toxinidir}/instrumentation/opentelemetry-instrumentation-aiohttp-client[test]

aiohttp-server: pip install {toxinidir}/instrumentation/opentelemetry-instrumentation-aiohttp-server[test]

aiopg: pip install {toxinidir}/instrumentation/opentelemetry-instrumentation-dbapi pip install {toxinidir}/instrumentation/opentelemetry-instrumentation-aiopg[test]

richconsole: pip install flaky {toxinidir}/exporter/opentelemetry-exporter-richconsole[test]
Expand Down Expand Up @@ -527,6 +534,7 @@ commands_pre =
python -m pip install -e {toxinidir}/instrumentation/opentelemetry-instrumentation-pymemcache[test]
python -m pip install -e {toxinidir}/instrumentation/opentelemetry-instrumentation-psycopg2[test]
python -m pip install -e {toxinidir}/instrumentation/opentelemetry-instrumentation-aiohttp-client[test]
python -m pip install -e {toxinidir}/instrumentation/opentelemetry-instrumentation-aiohttp-server[test]
python -m pip install -e {toxinidir}/instrumentation/opentelemetry-instrumentation-aiopg[test]
python -m pip install -e {toxinidir}/instrumentation/opentelemetry-instrumentation-sqlite3[test]
python -m pip install -e {toxinidir}/instrumentation/opentelemetry-instrumentation-pyramid[test]
Expand Down

0 comments on commit 5a14c7d

Please sign in to comment.