Skip to content

Commit

Permalink
Dynamically load patchers
Browse files Browse the repository at this point in the history
Fixes #333
  • Loading branch information
ocelotl committed Dec 18, 2019
1 parent 59b3c16 commit cb5c8e1
Show file tree
Hide file tree
Showing 8 changed files with 182 additions and 86 deletions.
9 changes: 8 additions & 1 deletion ext/opentelemetry-ext-flask/setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,11 @@
with open(VERSION_FILENAME) as f:
exec(f.read(), PACKAGE_INFO)

setuptools.setup(version=PACKAGE_INFO["__version__"])
setuptools.setup(
version=PACKAGE_INFO["__version__"],
entry_points={
'opentelemetry_patcher': [
'flask = opentelemetry.ext.flask:FlaskPatcher'
]
}
)
165 changes: 87 additions & 78 deletions ext/opentelemetry-ext-flask/src/opentelemetry/ext/flask/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import logging

import opentelemetry.ext.wsgi as otel_wsgi
from opentelemetry.patcher.base_patcher import BasePatcher
from opentelemetry import propagators, trace
from opentelemetry.util import time_ns
import flask
Expand All @@ -15,95 +16,103 @@
_ENVIRON_ACTIVATION_KEY = object()


def patch():
class FlaskPatcher(BasePatcher):

class PatchedFlask(flask.Flask):
def patch(self):

def __init__(self, *args, **kwargs):
class PatchedFlask(flask.Flask):

super().__init__(*args, **kwargs)
def __init__(self, *args, **kwargs):

# Single use variable here to avoid recursion issues.
wsgi = self.wsgi_app
super().__init__(*args, **kwargs)

def wrapped_app(environ, start_response):
# We want to measure the time for route matching, etc.
# In theory, we could start the span here and use
# update_name later but that API is "highly discouraged" so
# we better avoid it.
environ[_ENVIRON_STARTTIME_KEY] = time_ns()
# Single use variable here to avoid recursion issues.
wsgi = self.wsgi_app

def _start_response(
status, response_headers, *args, **kwargs
):
span = flask.request.environ.get(_ENVIRON_SPAN_KEY)
if span:
otel_wsgi.add_response_attributes(
span, status, response_headers
)
else:
logger.warning(
"Flask environ's OpenTelemetry span "
"missing at _start_response(%s)",
status,
)
def wrapped_app(environ, start_response):
# We want to measure the time for route matching, etc.
# In theory, we could start the span here and use
# update_name later but that API is "highly discouraged" so
# we better avoid it.
environ[_ENVIRON_STARTTIME_KEY] = time_ns()

return start_response(
def _start_response(
status, response_headers, *args, **kwargs
):
span = flask.request.environ.get(_ENVIRON_SPAN_KEY)
if span:
otel_wsgi.add_response_attributes(
span, status, response_headers
)
else:
logger.warning(
"Flask environ's OpenTelemetry span "
"missing at _start_response(%s)",
status,
)

return start_response(
status, response_headers, *args, **kwargs
)
return wsgi(environ, _start_response)

self.wsgi_app = wrapped_app

@self.before_request
def _before_flask_request():
environ = flask.request.environ
span_name = (
flask.request.endpoint
or otel_wsgi.get_default_span_name(environ)
)
return wsgi(environ, _start_response)

self.wsgi_app = wrapped_app

@self.before_request
def _before_flask_request():
environ = flask.request.environ
span_name = (
flask.request.endpoint
or otel_wsgi.get_default_span_name(environ)
)
parent_span = propagators.extract(
otel_wsgi.get_header_from_environ, environ
)

tracer = trace.tracer()

attributes = otel_wsgi.collect_request_attributes(environ)
if flask.request.url_rule:
# For 404 that result from no route found, etc, we don't
# have a url_rule.
attributes["http.route"] = flask.request.url_rule.rule
span = tracer.start_span(
span_name,
parent_span,
kind=trace.SpanKind.SERVER,
attributes=attributes,
start_time=environ.get(_ENVIRON_STARTTIME_KEY),
)
activation = tracer.use_span(span, end_on_exit=True)
activation.__enter__()
environ[_ENVIRON_ACTIVATION_KEY] = activation
environ[_ENVIRON_SPAN_KEY] = span

@self.teardown_request
def _teardown_flask_request(exc):
activation = flask.request.environ.get(_ENVIRON_ACTIVATION_KEY)
if not activation:
logger.warning(
"Flask environ's OpenTelemetry activation missing at "
"_teardown_flask_request(%s)",
exc,
parent_span = propagators.extract(
otel_wsgi.get_header_from_environ, environ
)
return

if exc is None:
activation.__exit__(None, None, None)
else:
activation.__exit__(
type(exc), exc, getattr(exc, "__traceback__", None)
tracer = trace.tracer()

attributes = otel_wsgi.collect_request_attributes(environ)
if flask.request.url_rule:
# For 404 that result from no route found, etc, we
# don't have a url_rule.
attributes["http.route"] = flask.request.url_rule.rule
span = tracer.start_span(
span_name,
parent_span,
kind=trace.SpanKind.SERVER,
attributes=attributes,
start_time=environ.get(_ENVIRON_STARTTIME_KEY),
)
activation = tracer.use_span(span, end_on_exit=True)
activation.__enter__()
environ[_ENVIRON_ACTIVATION_KEY] = activation
environ[_ENVIRON_SPAN_KEY] = span

@self.teardown_request
def _teardown_flask_request(exc):
activation = flask.request.environ.get(
_ENVIRON_ACTIVATION_KEY
)
if not activation:
logger.warning(
"Flask environ's OpenTelemetry activation missing"
"at _teardown_flask_request(%s)",
exc,
)
return

if exc is None:
activation.__exit__(None, None, None)
else:
activation.__exit__(
type(exc), exc, getattr(exc, "__traceback__", None)
)

flask.Flask = PatchedFlask

def unpatch(self):
# FIXME this needs an actual implementation
pass

def tato(self):
pass

flask.Flask = PatchedFlask
__all__ = ["FlaskPatcher"]
3 changes: 3 additions & 0 deletions opentelemetry-api/setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,9 @@
entry_points={
"console_scripts": [
"auto_agent = opentelemetry.commands.auto_agent:run"
],
"opentelemetry_patcher": [
"no_op_patcher = opentelemetry.patcher.no_op_patcher:NoOpPatcher"
]
},
description="OpenTelemetry Python API",
Expand Down
4 changes: 2 additions & 2 deletions opentelemetry-api/src/opentelemetry/commands/auto_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ def run():
os.environ['PYTHONPATH'] = join(dirname(__file__), 'initialize')
print(os.environ['PYTHONPATH'])

python3 = find_executable('python3')
execl(python3, python3, argv[1])
python3 = find_executable(argv[1])
execl(python3, python3, *argv[2:])
exit(0)


Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,16 @@
from opentelemetry.ext.flask import patch
from pkg_resources import iter_entry_points
from logging import getLogger

try:
patch()
_LOG = getLogger(__file__)

except Exception as error:
for entry_point in iter_entry_points("opentelemetry_patcher"):
try:
entry_point.load()().patch()

print(error)
_LOG.debug("Patched {}".format(entry_point.name))

except Exception as error:

_LOG.exception(
"Patching of {} failed with: {}".format(entry_point.name, error)
)
13 changes: 13 additions & 0 deletions opentelemetry-api/src/opentelemetry/patcher/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# Copyright 2019, 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.
29 changes: 29 additions & 0 deletions opentelemetry-api/src/opentelemetry/patcher/base_patcher.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# Copyright 2019, 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.

from abc import ABC, abstractmethod


class BasePatcher(ABC):

@abstractmethod
def patch(self):
"""Patch"""

@abstractmethod
def unpatch(self):
"""Unpatch"""


__all__ = ["BasePatcher"]
27 changes: 27 additions & 0 deletions opentelemetry-api/src/opentelemetry/patcher/no_op_patcher.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# Copyright 2019, 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.

from opentelemetry.patcher.base_patcher import BasePatcher


class NoOpPatcher(BasePatcher):

def patch(self):
"""Patch"""

def unpatch(self):
"""Unpatch"""


__all__ = ["NoOpPatcher"]

0 comments on commit cb5c8e1

Please sign in to comment.