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

Remove Tornado upper bound #115

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
3 changes: 2 additions & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
dist: xenial
dist: bionic
addons:
apt:
packages:
Expand All @@ -11,6 +11,7 @@ python:
- '3.5'
- '3.6'
- '3.7'
- '3.8'

install:
- pip install tox-travis coveralls
Expand Down
2 changes: 1 addition & 1 deletion docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ services:
- "3306:3306"

localstack:
image: localstack/localstack
image: localstack/localstack:0.10.9
environment:
- SERVICES=dynamodb,s3
ports:
Expand Down
2 changes: 1 addition & 1 deletion opentracing_instrumentation/client_hooks/boto3.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@
import logging

from opentracing.ext import tags
from tornado.stack_context import wrap as keep_stack_context

from opentracing_instrumentation import utils
from ..request_context import get_current_span, span_in_stack_context
from ._patcher import Patcher


try:
from tornado.stack_context import wrap as keep_stack_context
from boto3.resources.action import ServiceAction
from boto3.s3 import inject as s3_functions
from botocore import xform_name
Expand Down
22 changes: 16 additions & 6 deletions opentracing_instrumentation/local_span.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,13 @@
from builtins import str
import functools
import contextlib2
import tornado.concurrent
import opentracing
from opentracing.scope_managers.tornado import TornadoScopeManager
from . import tornado_context
from . import get_current_span, span_in_stack_context, span_in_context, utils

if tornado_context.is_tornado_supported():
import tornado.concurrent


def func_span(func, tags=None, require_active_trace=False):
"""
Expand Down Expand Up @@ -82,10 +84,17 @@ def __exit__(self, exc_type, exc_val, exc_tb):


def _span_in_stack_context(span):
if isinstance(opentracing.tracer.scope_manager, TornadoScopeManager):
return span_in_stack_context(span)
else:
if not tornado_context.is_tornado_supported():
return _DummyStackContext(span_in_context(span))
if not tornado_context.is_stack_context_supported():
return _DummyStackContext(span_in_context(span))
if not isinstance(
opentracing.tracer.scope_manager,
tornado_context.TornadoScopeManager
):
return _DummyStackContext(span_in_context(span))

return span_in_stack_context(span)


def traced_function(func=None, name=None, on_start=None,
Expand Down Expand Up @@ -158,7 +167,8 @@ def decorator(*args, **kwargs):
# Tornado co-routines usually return futures, so we must wait
# until the future is completed, in order to accurately
# capture the function's execution time.
if tornado.concurrent.is_future(res):
if tornado_context.is_tornado_supported() and \
tornado.concurrent.is_future(res):
def done_callback(future):
deactivate_cb()
exception = future.exception()
Expand Down
74 changes: 3 additions & 71 deletions opentracing_instrumentation/request_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,7 @@
import threading

import opentracing
from opentracing.scope_managers.tornado import TornadoScopeManager
from opentracing.scope_managers.tornado import tracer_stack_context
from opentracing.scope_managers.tornado import ThreadSafeStackContext # noqa
from .tornado_context import span_in_stack_context # noqa


class RequestContext(object):
Expand Down Expand Up @@ -94,26 +92,6 @@ def __exit__(self, *_):
return False


class _TracerEnteredStackContext(object):
"""
An entered tracer_stack_context() object.

Intended to have a ready-to-use context where
Span objects can be activated before the context
itself is returned to the user.
"""

def __init__(self, context):
self._context = context
self._deactivation_cb = context.__enter__()

def __enter__(self):
return self._deactivation_cb

def __exit__(self, type, value, traceback):
return self._context.__exit__(type, value, traceback)


def get_current_span():
"""
Access current request context and extract current Span from it.
Expand All @@ -138,6 +116,8 @@ def span_in_context(span):
request context. This function should only be used in single-threaded
applications like Flask / uWSGI.

This function also compatible with asyncio.

## Usage example in WSGI middleware:

.. code-block:: python
Expand Down Expand Up @@ -176,51 +156,3 @@ def start_response_wrapper(status, response_headers,
return opentracing.Scope(None, None)

return opentracing.tracer.scope_manager.activate(span, False)


def span_in_stack_context(span):
"""
Create Tornado's StackContext that stores the given span in the
thread-local request context. This function is intended for use
in Tornado applications based on IOLoop, although will work fine
in single-threaded apps like Flask, albeit with more overhead.

## Usage example in Tornado application

Suppose you have a method `handle_request(request)` in the http server.
Instead of calling it directly, use a wrapper:

.. code-block:: python

from opentracing_instrumentation import request_context

@tornado.gen.coroutine
def handle_request_wrapper(request, actual_handler, *args, **kwargs)

request_wrapper = TornadoRequestWrapper(request=request)
span = http_server.before_request(request=request_wrapper)

with request_context.span_in_stack_context(span):
return actual_handler(*args, **kwargs)

:param span:
:return:
Return StackContext that wraps the request context.
"""

if not isinstance(opentracing.tracer.scope_manager, TornadoScopeManager):
raise RuntimeError('scope_manager is not TornadoScopeManager')

# Enter the newly created stack context so we have
# storage available for Span activation.
context = tracer_stack_context()
entered_context = _TracerEnteredStackContext(context)

if span is None:
return entered_context

opentracing.tracer.scope_manager.activate(span, False)
assert opentracing.tracer.active_span is not None
assert opentracing.tracer.active_span is span

return entered_context
119 changes: 119 additions & 0 deletions opentracing_instrumentation/tornado_context.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
# Copyright (c) 2015 Uber Technologies, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

_tornado_supported = False
_stack_context_supported = False

import opentracing
try:
import tornado # noqa
_tornado_supported = True
from opentracing.scope_managers.tornado import TornadoScopeManager
from opentracing.scope_managers.tornado import tracer_stack_context
_stack_context_supported = True
except ImportError:
pass


def is_tornado_supported():
return _tornado_supported


def is_stack_context_supported():
return _stack_context_supported


class _TracerEnteredStackContext(object):
"""
An entered tracer_stack_context() object.

Intended to have a ready-to-use context where
Span objects can be activated before the context
itself is returned to the user.
"""

def __init__(self, context):
self._context = context
self._deactivation_cb = context.__enter__()

def __enter__(self):
return self._deactivation_cb

def __exit__(self, type, value, traceback):
return self._context.__exit__(type, value, traceback)


def span_in_stack_context(span):
"""
Create Tornado's (4.x, 5.x) StackContext that stores the given span in the
thread-local request context. This function is intended for use
in Tornado applications based on IOLoop, although will work fine
in single-threaded apps like Flask, albeit with more overhead.

StackContext has been deprecated in Tornado 6 and higher.
Because of asyncio nature of Tornado 6.x, consider using
`span_in_context` with opentracing scope manager `ContextVarScopeManager`

## Usage example in Tornado application

Suppose you have a method `handle_request(request)` in the http server.
Instead of calling it directly, use a wrapper:

.. code-block:: python

from opentracing_instrumentation import request_context

@tornado.gen.coroutine
def handle_request_wrapper(request, actual_handler, *args, **kwargs)

request_wrapper = TornadoRequestWrapper(request=request)
span = http_server.before_request(request=request_wrapper)

with request_context.span_in_stack_context(span):
return actual_handler(*args, **kwargs)

:param span:
:return:
Return StackContext that wraps the request context.
"""
if not _tornado_supported:
raise RuntimeError('span_in_stack_context requires Tornado')

if not is_stack_context_supported():
raise RuntimeError('tornado.stack_context is not supported in '
'Tornado >= 6.x')
if not isinstance(
opentracing.tracer.scope_manager, TornadoScopeManager
):
raise RuntimeError('scope_manager is not TornadoScopeManager')

# Enter the newly created stack context so we have
# storage available for Span activation.
context = tracer_stack_context()
entered_context = _TracerEnteredStackContext(context)

if span is None:
return entered_context

opentracing.tracer.scope_manager.activate(span, False)
assert opentracing.tracer.active_span is not None
assert opentracing.tracer.active_span is span

return entered_context
8 changes: 6 additions & 2 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
install_requires=[
'future',
'wrapt',
'tornado>=4.1,<6',
'tornado>=4.1',
'contextlib2',
'opentracing>=2,<3',
'six',
Expand All @@ -47,7 +47,10 @@
'flake8',
'flake8-quotes',
'mock',
'moto',
# next major version is incompatible with python 3.5 because of
# cryptography library
'moto==1.3.16; python_version=="3.5"',
'moto; python_version!="3.5"',
'MySQL-python; python_version=="2.7"',
'psycopg2-binary',
'sqlalchemy>=1.3.7',
Expand All @@ -61,6 +64,7 @@
'Sphinx',
'sphinx_rtd_theme',
'testfixtures',
'pytest-asyncio; python_version>="3.4"',
]
},
)
Loading