Skip to content

Commit

Permalink
Utils package
Browse files Browse the repository at this point in the history
  • Loading branch information
cnnradams committed May 27, 2020
1 parent 8a946b5 commit 14ad082
Show file tree
Hide file tree
Showing 27 changed files with 500 additions and 177 deletions.
1 change: 1 addition & 0 deletions eachdist.ini
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ sortfirst=
opentelemetry-api
opentelemetry-sdk
opentelemetry-auto-instrumentation
ext/opentelemetry-ext-utils
ext/opentelemetry-ext-wsgi
ext/opentelemetry-ext-dbapi
ext/*
Expand Down
1 change: 1 addition & 0 deletions ext/opentelemetry-ext-aiohttp-client/setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ package_dir=
packages=find_namespace:
install_requires =
opentelemetry-api >= 0.8.dev0
opentelemetry-ext-utils == 0.8.dev0
aiohttp ~= 3.0

[options.packages.find]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,38 +52,11 @@ def strip_query_params(url: yarl.URL) -> str:
from opentelemetry import context as context_api
from opentelemetry import propagators, trace
from opentelemetry.ext.aiohttp_client.version import __version__
from opentelemetry.ext.utils import http_status_to_canonical_code
from opentelemetry.trace import SpanKind
from opentelemetry.trace.status import Status, StatusCanonicalCode


# TODO: refactor this code to some common utility
def http_status_to_canonical_code(status: int) -> StatusCanonicalCode:
# pylint:disable=too-many-branches,too-many-return-statements
if status < 100:
return StatusCanonicalCode.UNKNOWN
if status <= 399:
return StatusCanonicalCode.OK
if status <= 499:
if status == 401: # HTTPStatus.UNAUTHORIZED:
return StatusCanonicalCode.UNAUTHENTICATED
if status == 403: # HTTPStatus.FORBIDDEN:
return StatusCanonicalCode.PERMISSION_DENIED
if status == 404: # HTTPStatus.NOT_FOUND:
return StatusCanonicalCode.NOT_FOUND
if status == 429: # HTTPStatus.TOO_MANY_REQUESTS:
return StatusCanonicalCode.RESOURCE_EXHAUSTED
return StatusCanonicalCode.INVALID_ARGUMENT
if status <= 599:
if status == 501: # HTTPStatus.NOT_IMPLEMENTED:
return StatusCanonicalCode.UNIMPLEMENTED
if status == 503: # HTTPStatus.SERVICE_UNAVAILABLE:
return StatusCanonicalCode.UNAVAILABLE
if status == 504: # HTTPStatus.GATEWAY_TIMEOUT:
return StatusCanonicalCode.DEADLINE_EXCEEDED
return StatusCanonicalCode.INTERNAL
return StatusCanonicalCode.UNKNOWN


def url_path_span_name(params: aiohttp.TraceRequestStartParams) -> str:
"""Extract a span name from the request URL path.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -98,43 +98,6 @@ async def default_handler(request):
loop = asyncio.get_event_loop()
return loop.run_until_complete(do_request())

def test_http_status_to_canonical_code(self):
for status_code, expected in (
(HTTPStatus.OK, StatusCanonicalCode.OK),
(HTTPStatus.ACCEPTED, StatusCanonicalCode.OK),
(HTTPStatus.IM_USED, StatusCanonicalCode.OK),
(HTTPStatus.MULTIPLE_CHOICES, StatusCanonicalCode.OK),
(HTTPStatus.BAD_REQUEST, StatusCanonicalCode.INVALID_ARGUMENT),
(HTTPStatus.UNAUTHORIZED, StatusCanonicalCode.UNAUTHENTICATED),
(HTTPStatus.FORBIDDEN, StatusCanonicalCode.PERMISSION_DENIED),
(HTTPStatus.NOT_FOUND, StatusCanonicalCode.NOT_FOUND),
(
HTTPStatus.UNPROCESSABLE_ENTITY,
StatusCanonicalCode.INVALID_ARGUMENT,
),
(
HTTPStatus.TOO_MANY_REQUESTS,
StatusCanonicalCode.RESOURCE_EXHAUSTED,
),
(HTTPStatus.NOT_IMPLEMENTED, StatusCanonicalCode.UNIMPLEMENTED),
(HTTPStatus.SERVICE_UNAVAILABLE, StatusCanonicalCode.UNAVAILABLE),
(
HTTPStatus.GATEWAY_TIMEOUT,
StatusCanonicalCode.DEADLINE_EXCEEDED,
),
(
HTTPStatus.HTTP_VERSION_NOT_SUPPORTED,
StatusCanonicalCode.INTERNAL,
),
(600, StatusCanonicalCode.UNKNOWN),
(99, StatusCanonicalCode.UNKNOWN),
):
with self.subTest(status_code=status_code):
actual = opentelemetry.ext.aiohttp_client.http_status_to_canonical_code(
int(status_code)
)
self.assertEqual(actual, expected, status_code)

def test_status_codes(self):
for status_code, span_status in (
(HTTPStatus.OK, StatusCanonicalCode.OK),
Expand Down
1 change: 1 addition & 0 deletions ext/opentelemetry-ext-dbapi/setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ package_dir=
packages=find_namespace:
install_requires =
opentelemetry-api == 0.8.dev0
opentelemetry-ext-utils == 0.8.dev0
wrapt >= 1.0.0, < 2.0.0

[options.extras_require]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
import wrapt

from opentelemetry.ext.dbapi.version import __version__
from opentelemetry.ext.utils import unwrap
from opentelemetry.trace import SpanKind, Tracer, TracerProvider, get_tracer
from opentelemetry.trace.status import Status, StatusCanonicalCode

Expand Down Expand Up @@ -141,9 +142,7 @@ def unwrap_connect(
connect_module: Module name where the connect method is available.
connect_method_name: The connect method name.
"""
conn = getattr(connect_module, connect_method_name, None)
if isinstance(conn, wrapt.ObjectProxy):
setattr(connect_module, connect_method_name, conn.__wrapped__)
unwrap(connect_module, connect_method_name)


def instrument_connection(
Expand Down
1 change: 1 addition & 0 deletions ext/opentelemetry-ext-jinja2/setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ packages=find_namespace:
install_requires =
opentelemetry-api == 0.8.dev0
opentelemetry-auto-instrumentation == 0.8.dev0
opentelemetry-ext-utils == 0.8.dev0
jinja2~=2.7
wrapt >= 1.0.0, < 2.0.0

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@

from opentelemetry.auto_instrumentation.instrumentor import BaseInstrumentor
from opentelemetry.ext.jinja2.version import __version__
from opentelemetry.ext.utils import unwrap
from opentelemetry.trace import SpanKind, get_tracer
from opentelemetry.trace.status import Status, StatusCanonicalCode

Expand Down Expand Up @@ -115,12 +116,6 @@ def _wrap_load_template(tracer, wrapped, _, args, kwargs):
)


def _unwrap(obj, attr):
func = getattr(obj, attr, None)
if func and isinstance(func, ObjectProxy) and hasattr(func, "__wrapped__"):
setattr(obj, attr, func.__wrapped__)


class Jinja2Instrumentor(BaseInstrumentor):
"""An instrumentor for jinja2
Expand All @@ -141,7 +136,7 @@ def _instrument(self, **kwargs):
)

def _uninstrument(self, **kwargs):
_unwrap(jinja2.Template, "render")
_unwrap(jinja2.Template, "generate")
_unwrap(jinja2.Environment, "compile")
_unwrap(jinja2.Environment, "_load_template")
unwrap(jinja2.Template, "render")
unwrap(jinja2.Template, "generate")
unwrap(jinja2.Environment, "compile")
unwrap(jinja2.Environment, "_load_template")
1 change: 1 addition & 0 deletions ext/opentelemetry-ext-redis/setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ package_dir=
packages=find_namespace:
install_requires =
opentelemetry-api == 0.8.dev0
opentelemetry-ext-utils == 0.8.dev0
opentelemetry-auto-instrumentation == 0.8.dev0
redis >= 2.6
wrapt >= 1.12.1
Expand Down
25 changes: 10 additions & 15 deletions ext/opentelemetry-ext-redis/src/opentelemetry/ext/redis/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@
_format_command_args,
)
from opentelemetry.ext.redis.version import __version__
from opentelemetry.ext.utils import unwrap

_DEFAULT_SERVICE = "redis"
_RAWCMD = "db.statement"
Expand All @@ -68,12 +69,6 @@ def _set_connection_attributes(span, conn):
span.set_attribute(key, value)


def _unwrap(obj, attr):
func = getattr(obj, attr, None)
if isinstance(func, ObjectProxy) and hasattr(func, "__wrapped__"):
setattr(obj, attr, func.__wrapped__)


def _traced_execute_command(func, instance, args, kwargs):
tracer = getattr(redis, "_opentelemetry_tracer")
query = _format_command_args(args)
Expand Down Expand Up @@ -145,19 +140,19 @@ def _instrument(self, **kwargs):

def _uninstrument(self, **kwargs):
if redis.VERSION < (3, 0, 0):
_unwrap(redis.StrictRedis, "execute_command")
_unwrap(redis.StrictRedis, "pipeline")
_unwrap(redis.Redis, "pipeline")
_unwrap(
unwrap(redis.StrictRedis, "execute_command")
unwrap(redis.StrictRedis, "pipeline")
unwrap(redis.Redis, "pipeline")
unwrap(
redis.client.BasePipeline, # pylint:disable=no-member
"execute",
)
_unwrap(
unwrap(
redis.client.BasePipeline, # pylint:disable=no-member
"immediate_execute_command",
)
else:
_unwrap(redis.Redis, "execute_command")
_unwrap(redis.Redis, "pipeline")
_unwrap(redis.client.Pipeline, "execute")
_unwrap(redis.client.Pipeline, "immediate_execute_command")
unwrap(redis.Redis, "execute_command")
unwrap(redis.Redis, "pipeline")
unwrap(redis.client.Pipeline, "execute")
unwrap(redis.client.Pipeline, "immediate_execute_command")
2 changes: 2 additions & 0 deletions ext/opentelemetry-ext-requests/setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -42,11 +42,13 @@ packages=find_namespace:
install_requires =
opentelemetry-api == 0.8.dev0
opentelemetry-auto-instrumentation == 0.8.dev0
opentelemetry-ext-utils == 0.8.dev0
requests ~= 2.0

[options.extras_require]
test =
opentelemetry-test == 0.8.dev0
opentelemetry-ext-utils == 0.8.dev0
httpretty ~= 1.0

[options.packages.find]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,9 @@
from opentelemetry import context, propagators, trace
from opentelemetry.auto_instrumentation.instrumentor import BaseInstrumentor
from opentelemetry.ext.requests.version import __version__
from opentelemetry.ext.utils import http_status_to_canonical_code
from opentelemetry.trace import SpanKind, get_tracer
from opentelemetry.trace.status import Status, StatusCanonicalCode
from opentelemetry.trace.status import Status


# pylint: disable=unused-argument
Expand Down Expand Up @@ -99,7 +100,7 @@ def instrumented_request(self, method, url, *args, **kwargs):
span.set_attribute("http.status_code", result.status_code)
span.set_attribute("http.status_text", result.reason)
span.set_status(
Status(_http_status_to_canonical_code(result.status_code))
Status(http_status_to_canonical_code(result.status_code))
)
if span_callback is not None:
span_callback(span, result)
Expand All @@ -126,37 +127,6 @@ def _uninstrument():
Session.request = original


def _http_status_to_canonical_code(code: int, allow_redirect: bool = True):
# 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


class RequestsInstrumentor(BaseInstrumentor):
"""An instrumentor for requests
See `BaseInstrumentor`
Expand Down
1 change: 1 addition & 0 deletions ext/opentelemetry-ext-sqlalchemy/setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ packages=find_namespace:
install_requires =
opentelemetry-api == 0.8.dev0
opentelemetry-auto-instrumentation == 0.8.dev0
opentelemetry-ext-utils == 0.8.dev0
wrapt >= 1.11.2
sqlalchemy

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,16 +53,7 @@
_get_tracer,
_wrap_create_engine,
)


def _unwrap(obj, attr):
func = getattr(obj, attr, None)
if (
func
and isinstance(func, wrapt.ObjectProxy)
and hasattr(func, "__wrapped__")
):
setattr(obj, attr, func.__wrapped__)
from opentelemetry.ext.utils import unwrap


class SQLAlchemyInstrumentor(BaseInstrumentor):
Expand Down Expand Up @@ -96,5 +87,5 @@ def _instrument(self, **kwargs):
return None

def _uninstrument(self, **kwargs):
_unwrap(sqlalchemy, "create_engine")
_unwrap(sqlalchemy.engine, "create_engine")
unwrap(sqlalchemy, "create_engine")
unwrap(sqlalchemy.engine, "create_engine")
5 changes: 5 additions & 0 deletions ext/opentelemetry-ext-utils/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Changelog

## Unreleased

- Initial release
Loading

0 comments on commit 14ad082

Please sign in to comment.