Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add ASGI middleware #716

Merged
Merged
Show file tree
Hide file tree
Changes from 18 commits
Commits
Show all changes
44 commits
Select commit Hold shift + click to select a range
5d6df0c
ext-wsgi duplicated as ext-asgi
Skeen Feb 8, 2020
e2b85ad
Rename WSGI files
Skeen Feb 8, 2020
f729c3d
WSGI to ASGI
Skeen Feb 8, 2020
782e9b1
Fix ext/testutil
Skeen Feb 8, 2020
a343b7d
Black reformatting
Skeen Feb 8, 2020
d6ac1e2
Isort reformatting
Skeen Feb 8, 2020
8a8f726
Flake8 reformatting
Skeen Feb 8, 2020
ac7cb72
Pylint reformatting
Skeen Feb 8, 2020
2d32ef9
Documentation
Skeen Feb 8, 2020
103ff1d
ASGI only runs under Python 3.5+, fixes to tox/coverage
Skeen Feb 19, 2020
4bbc7a6
Added callback to override default span-name, default span name to HT…
Skeen Feb 21, 2020
4833891
Set send_span name immediately, instead of updating it
Skeen Feb 21, 2020
924fe35
Changed span-names to asgi.{scope["type"]}.send/receive
Skeen Feb 21, 2020
5a13e0c
Handle scope["server"] = None, by defaulting to 0.0.0.0:80
Skeen Feb 21, 2020
0df9c62
Set http.server_name based on Host header
Skeen Feb 21, 2020
c88f152
fix tests
majorgreys May 20, 2020
f0ef937
fix propagation
majorgreys May 20, 2020
b4356ac
update changelog
majorgreys May 20, 2020
c1d3cbe
add http.user_agent
majorgreys May 21, 2020
353bf27
update version
majorgreys May 21, 2020
0e48edd
add websocket, disable for lifespan
majorgreys May 21, 2020
46f3565
Apply suggestions from code review
majorgreys May 21, 2020
2f94f83
Merge branch 'majorgreys/feature/ext_asgi' of github.com:DataDog/open…
majorgreys May 21, 2020
429b8e2
add py38
majorgreys May 21, 2020
83139f0
remove py34
majorgreys May 21, 2020
3759a51
lint fix
majorgreys May 21, 2020
a4cce67
move doc
majorgreys May 21, 2020
da0a00b
method or path
majorgreys May 21, 2020
16f37f7
websocket tests
majorgreys May 21, 2020
0b9fbcd
Merge remote-tracking branch 'upstream/master' into majorgreys/featur…
majorgreys May 21, 2020
3ac4620
handle empty attributes
majorgreys May 22, 2020
9f3d5bb
fix lint
majorgreys May 22, 2020
9e00976
Merge remote-tracking branch 'upstream/master' into majorgreys/featur…
majorgreys May 22, 2020
01f9310
Merge branch 'master' into majorgreys/feature/ext_asgi
majorgreys May 22, 2020
553969c
Merge branch 'master' into majorgreys/feature/ext_asgi
majorgreys May 26, 2020
9e04228
Apply suggestions from code review
majorgreys May 26, 2020
edc6044
more review updates
majorgreys May 27, 2020
bc6f0a9
Merge remote-tracking branch 'upstream/master' into majorgreys/featur…
majorgreys May 27, 2020
3849da1
better handling for query_string
majorgreys May 27, 2020
bb8506b
added versions for install_requires
majorgreys May 27, 2020
d888a6f
at least asgiref 3.0
majorgreys May 27, 2020
25b0534
remove unused import
majorgreys May 27, 2020
8c9eded
Merge branch 'master' into majorgreys/feature/ext_asgi
majorgreys May 27, 2020
22dbe06
Merge branch 'master' into majorgreys/feature/ext_asgi
majorgreys May 27, 2020
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs-requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ sphinx-rtd-theme~=0.4
sphinx-autodoc-typehints~=1.10.2

# Required by ext packages
asgiref~=3.2.3
ddtrace>=0.34.0
aiohttp ~= 3.0
Deprecated>=1.2.6
Expand Down
10 changes: 10 additions & 0 deletions docs/opentelemetry.ext.asgi.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
opentelemetry.ext.asgi package
==========================================
majorgreys marked this conversation as resolved.
Show resolved Hide resolved

Module contents
---------------

.. automodule:: opentelemetry.ext.asgi
:members:
:undoc-members:
:show-inheritance:
5 changes: 5 additions & 0 deletions ext/opentelemetry-ext-asgi/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Changelog

## Unreleased

- Add ASGI middleware ([#716](https://github.com/open-telemetry/opentelemetry-python/pull/716))
61 changes: 61 additions & 0 deletions ext/opentelemetry-ext-asgi/README.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
OpenTelemetry ASGI Middleware
=============================

|pypi|

.. |pypi| image:: https://badge.fury.io/py/opentelemetry-ext-asgi.svg
:target: https://pypi.org/project/opentelemetry-ext-asgi/


This library provides a ASGI middleware that can be used on any ASGI framework
(such as Django / Flask) to track requests timing through OpenTelemetry.
majorgreys marked this conversation as resolved.
Show resolved Hide resolved

Installation
------------

::

pip install opentelemetry-ext-asgi


Usage (Quart)
-------------

.. code-block:: python

from quart import Quart
from opentelemetry.ext.asgi import OpenTelemetryMiddleware

app = Quart(__name__)
app.asgi_app = OpenTelemetryMiddleware(app.asgi_app)

@app.route("/")
async def hello():
return "Hello!"

if __name__ == "__main__":
app.run(debug=True)


Usage (Django)
--------------

Modify the application's ``asgi.py`` file as shown below.

.. code-block:: python

import os
import django
from channels.routing import get_default_application
from opentelemetry.ext.asgi import OpenTelemetryMiddleware

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'application.settings')
django.setup()

application = get_default_application()
application = OpenTelemetryMiddleware(application)
majorgreys marked this conversation as resolved.
Show resolved Hide resolved

References
----------

* `OpenTelemetry Project <https://opentelemetry.io/>`_
49 changes: 49 additions & 0 deletions ext/opentelemetry-ext-asgi/setup.cfg
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# Copyright 2019, OpenTelemetry Authors
majorgreys marked this conversation as resolved.
Show resolved Hide resolved
#
# 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.
#
[metadata]
name = opentelemetry-ext-asgi
description = ASGI Middleware for OpenTelemetry
long_description = file: README.rst
long_description_content_type = text/x-rst
author = OpenTelemetry Authors
author_email = [email protected]
url = https://github.com/open-telemetry/opentelemetry-python/ext/opentelemetry-ext-asgi
platforms = any
license = Apache-2.0
classifiers =
Development Status :: 3 - Alpha
majorgreys marked this conversation as resolved.
Show resolved Hide resolved
Intended Audience :: Developers
License :: OSI Approved :: Apache Software License
Programming Language :: Python
Programming Language :: Python :: 3
Programming Language :: Python :: 3.5
Programming Language :: Python :: 3.6
Programming Language :: Python :: 3.7
majorgreys marked this conversation as resolved.
Show resolved Hide resolved

[options]
python_requires = >=3.5
package_dir=
=src
packages=find_namespace:
install_requires =
opentelemetry-api
majorgreys marked this conversation as resolved.
Show resolved Hide resolved
asgiref
majorgreys marked this conversation as resolved.
Show resolved Hide resolved

[options.extras_require]
test =
opentelemetry-ext-testutil

[options.packages.find]
where = src
26 changes: 26 additions & 0 deletions ext/opentelemetry-ext-asgi/setup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# Copyright 2019, OpenTelemetry Authors
majorgreys marked this conversation as resolved.
Show resolved Hide resolved
#
# 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 os

import setuptools

BASE_DIR = os.path.dirname(__file__)
VERSION_FILENAME = os.path.join(
BASE_DIR, "src", "opentelemetry", "ext", "asgi", "version.py"
)
PACKAGE_INFO = {}
with open(VERSION_FILENAME) as f:
exec(f.read(), PACKAGE_INFO)

setuptools.setup(version=PACKAGE_INFO["__version__"])
202 changes: 202 additions & 0 deletions ext/opentelemetry-ext-asgi/src/opentelemetry/ext/asgi/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,202 @@
# Copyright 2019, OpenTelemetry Authors
majorgreys marked this conversation as resolved.
Show resolved Hide resolved
#
# 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.

"""
The opentelemetry-ext-asgi package provides an ASGI middleware that can be used
on any ASGI framework (such as Django-channels / Quart) to track requests
timing through OpenTelemetry.
"""

import operator
import typing
from functools import wraps

from asgiref.compatibility import guarantee_single_callable

from opentelemetry import context, propagators, trace
from opentelemetry.ext.asgi.version import __version__ # noqa
from opentelemetry.trace.status import Status, StatusCanonicalCode

_HTTP_VERSION_PREFIX = "HTTP/"


def get_header_from_scope(scope: dict, header_name: str) -> typing.List[str]:
"""Retrieve a HTTP header value from the ASGI scope.

Returns:
A list with a single string with the header value if it exists, else an empty list.
"""
headers = scope.get("headers")
return [
value.decode("utf8")
for (key, value) in headers
if key.decode("utf8") == header_name
]


def http_status_to_canonical_code(code: int, allow_redirect: bool = True):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added an issue to track refactoring this code as it appears in at least 2 other places #735

# pylint:disable=too-many-branches,too-many-return-statements
if code < 100:
return StatusCanonicalCode.UNKNOWN
if code <= 299:
return StatusCanonicalCode.OK
if code <= 399:
if allow_redirect:
return StatusCanonicalCode.OK
return StatusCanonicalCode.DEADLINE_EXCEEDED
if code <= 499:
if code == 401: # HTTPStatus.UNAUTHORIZED:
return StatusCanonicalCode.UNAUTHENTICATED
if code == 403: # HTTPStatus.FORBIDDEN:
return StatusCanonicalCode.PERMISSION_DENIED
if code == 404: # HTTPStatus.NOT_FOUND:
return StatusCanonicalCode.NOT_FOUND
if code == 429: # HTTPStatus.TOO_MANY_REQUESTS:
return StatusCanonicalCode.RESOURCE_EXHAUSTED
return StatusCanonicalCode.INVALID_ARGUMENT
if code <= 599:
if code == 501: # HTTPStatus.NOT_IMPLEMENTED:
return StatusCanonicalCode.UNIMPLEMENTED
if code == 503: # HTTPStatus.SERVICE_UNAVAILABLE:
return StatusCanonicalCode.UNAVAILABLE
if code == 504: # HTTPStatus.GATEWAY_TIMEOUT:
return StatusCanonicalCode.DEADLINE_EXCEEDED
return StatusCanonicalCode.INTERNAL
return StatusCanonicalCode.UNKNOWN


def collect_request_attributes(scope):
"""Collects HTTP request attributes from the ASGI scope and returns a
dictionary to be used as span creation attributes."""
server = scope.get("server") or ["0.0.0.0", 80]
port = server[1]
server_host = server[0] + (":" + str(port) if port != 80 else "")
http_url = scope.get("scheme") + "://" + server_host + scope.get("path")
if scope.get("query_string"):
http_url = http_url + ("?" + scope.get("query_string").decode("utf8"))
majorgreys marked this conversation as resolved.
Show resolved Hide resolved

result = {
"component": scope.get("type"),
majorgreys marked this conversation as resolved.
Show resolved Hide resolved
"http.method": scope.get("method"),
"http.scheme": scope.get("scheme"),
"http.host": server_host,
"host.port": port,
"http.flavor": scope.get("http_version"),
"http.target": scope.get("path"),
"http.url": http_url,
}
majorgreys marked this conversation as resolved.
Show resolved Hide resolved
http_host_value = ",".join(get_header_from_scope(scope, "host"))
if http_host_value:
result["http.server_name"] = http_host_value

if "client" in scope and scope["client"] is not None:
result["net.peer.ip"] = scope.get("client")[0]
result["net.peer.port"] = scope.get("client")[1]

return result


def set_status_code(span, status_code):
"""Adds HTTP response attributes to span using the status_code argument."""
try:
status_code = int(status_code)
except ValueError:
span.set_status(
Status(
StatusCanonicalCode.UNKNOWN,
"Non-integer HTTP status: " + repr(status_code),
)
)
else:
span.set_attribute("http.status_code", status_code)
span.set_status(Status(http_status_to_canonical_code(status_code)))


def get_default_span_name(scope):
"""Default implementation for name_callback, returns HTTP {METHOD_NAME}."""
return "HTTP " + scope.get("method")
toumorokoshi marked this conversation as resolved.
Show resolved Hide resolved


class OpenTelemetryMiddleware:
"""The ASGI application middleware.

This class is an ASGI middleware that starts and annotates spans for any
requests it is invoked with.

Args:
app: The ASGI application callable to forward requests to.
name_callback: Callback which calculates a generic span name for an
incoming HTTP request based on the ASGI scope.
Optional: Defaults to get_default_span_name.
"""

def __init__(self, app, name_callback=None):
self.app = guarantee_single_callable(app)
self.tracer = trace.get_tracer(__name__, __version__)
self.name_callback = name_callback or get_default_span_name

async def __call__(self, scope, receive, send):
"""The ASGI application

Args:
scope: A ASGI environment.
receive: An awaitable callable yielding dictionaries
send: An awaitable callable taking a single dictionary as argument.
"""

token = context.attach(
propagators.extract(get_header_from_scope, scope)
)
span_name = self.name_callback(scope)
toumorokoshi marked this conversation as resolved.
Show resolved Hide resolved

try:
with self.tracer.start_as_current_span(
majorgreys marked this conversation as resolved.
Show resolved Hide resolved
span_name + " (asgi.connection)",
toumorokoshi marked this conversation as resolved.
Show resolved Hide resolved
kind=trace.SpanKind.SERVER,
attributes=collect_request_attributes(scope),
):

@wraps(receive)
async def wrapped_receive():
with self.tracer.start_as_current_span(
span_name + " (asgi." + scope["type"] + ".receive)"
) as receive_span:
payload = await receive()
majorgreys marked this conversation as resolved.
Show resolved Hide resolved
if payload["type"] == "websocket.receive":
set_status_code(receive_span, 200)
receive_span.set_attribute(
"http.status_text", payload["text"]
)
receive_span.set_attribute("type", payload["type"])
return payload

@wraps(send)
async def wrapped_send(payload):
majorgreys marked this conversation as resolved.
Show resolved Hide resolved
with self.tracer.start_as_current_span(
span_name + " (asgi." + scope["type"] + ".send)"
) as send_span:
if payload["type"] == "http.response.start":
status_code = payload["status"]
set_status_code(send_span, status_code)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does OpenTelemetry support storing response headers? If so this is a good place to do it; otherwise please ignore. :-)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not that I'm aware of and do not see it in the wsgi instrumentation.

elif payload["type"] == "websocket.send":
set_status_code(send_span, 200)
send_span.set_attribute(
"http.status_text", payload["text"]
)
send_span.set_attribute("type", payload["type"])
await send(payload)

await self.app(scope, wrapped_receive, wrapped_send)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If OpenTelemetry supports some kind of "attach a traceback to a trace", then we could also try/except around the app call; otherwise, please ignore.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The Python OpenTelemetry client does not store the traceback.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this is still up for debate in the standard. But it's a good point, and something I know is highly valuable around existing DD integration. @majorgreys thoughts? should we raise this in the spec?

finally:
context.detach(token)
15 changes: 15 additions & 0 deletions ext/opentelemetry-ext-asgi/src/opentelemetry/ext/asgi/version.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# Copyright 2019, OpenTelemetry Authors
majorgreys marked this conversation as resolved.
Show resolved Hide resolved
#
# 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.

__version__ = "0.4.dev0"
majorgreys marked this conversation as resolved.
Show resolved Hide resolved
majorgreys marked this conversation as resolved.
Show resolved Hide resolved
Empty file.
Loading