Skip to content

Commit

Permalink
Remove Configuration
Browse files Browse the repository at this point in the history
  • Loading branch information
ocelotl committed Jan 12, 2021
1 parent d12f67f commit 432ae70
Show file tree
Hide file tree
Showing 19 changed files with 289 additions and 73 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased](https://github.com/open-telemetry/opentelemetry-python-contrib/compare/v0.16b1...HEAD)

### Added
- Remove Configuration
([#285](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/285))
- `opentelemetry-instrumentation-sqlalchemy` Ensure spans have kind set to "CLIENT"
([#278](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/278))
- `opentelemetry-instrumentation-celery` Add support for Celery version 5.x
Expand Down Expand Up @@ -41,6 +43,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
([#273](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/273))

### Changed
- Remove Configuration
([#285](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/285))
- `opentelemetry-instrumentation-asgi`, `opentelemetry-instrumentation-wsgi` Return `None` for `CarrierGetter` if key not found
([#1374](https://github.com/open-telemetry/opentelemetry-python-contrib/pull/233))
- `opentelemetry-instrumentation-grpc` Comply with updated spec, rework tests
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,8 +84,6 @@ def _instrument(self, **kwargs):
# For exemple EC2 uses AWSQueryConnection and S3 uses
# AWSAuthConnection

# FIXME should the tracer provider be accessed via Configuration
# instead?
# pylint: disable=attribute-defined-outside-init
self._tracer = get_tracer(
__name__, __version__, kwargs.get("tracer_provider")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,10 @@
# limitations under the License.

from logging import getLogger
from os import environ

from django.conf import settings

from opentelemetry.configuration import Configuration
from opentelemetry.instrumentation.django.middleware import _DjangoMiddleware
from opentelemetry.instrumentation.django.version import __version__
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
Expand All @@ -43,11 +43,7 @@ def _instrument(self, **kwargs):

# FIXME this is probably a pattern that will show up in the rest of the
# ext. Find a better way of implementing this.
# FIXME Probably the evaluation of strings into boolean values can be
# built inside the Configuration class itself with the magic method
# __bool__

if Configuration().DJANGO_INSTRUMENT is False:
if environ.get("OTEL_PYTHON_DJANGO_INSTRUMENT") == "False":
return

# This can not be solved, but is an inherent problem of this approach:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,13 @@
# See the License for the specific language governing permissions and
# limitations under the License.

import time
from time import time
from logging import getLogger
from os import environ
from re import compile as re_compile, search

from django.conf import settings

from opentelemetry.configuration import Configuration
from opentelemetry.context import attach, detach
from opentelemetry.instrumentation.django.version import __version__
from opentelemetry.instrumentation.utils import extract_attributes_from_object
Expand Down Expand Up @@ -51,6 +52,46 @@
]


class _ExcludeList:
"""Class to exclude certain paths (given as a list of regexes) from tracing requests"""

def __init__(self, excluded_urls):
self._excluded_urls = excluded_urls
if self._excluded_urls:
self._regex = re_compile("|".join(excluded_urls))

def url_disabled(self, url: str) -> bool:
return bool(self._excluded_urls and search(self._regex, url))

_root = r"OTEL_PYTHON_{}"


def _get_traced_request_attrs():
traced_request_attrs = environ.get(
_root.format("DJANGO_TRACED_REQUEST_ATTRS"), []
)

if traced_request_attrs:
traced_request_attrs = [
traced_request_attr.strip()
for traced_request_attr in traced_request_attrs.split(",")
]

return traced_request_attrs


def _get_excluded_urls():
excluded_urls = environ.get(_root.format("DJANGO_EXCLUDED_URLS"), [])

if excluded_urls:
excluded_urls = [
excluded_url.strip()
for excluded_url in excluded_urls.split(",")
]

return _ExcludeList(excluded_urls)


class _DjangoMiddleware(MiddlewareMixin):
"""Django Middleware for OpenTelemetry"""

Expand All @@ -61,9 +102,8 @@ class _DjangoMiddleware(MiddlewareMixin):
_environ_span_key = "opentelemetry-instrumentor-django.span_key"
_environ_exception_key = "opentelemetry-instrumentor-django.exception_key"

_excluded_urls = Configuration()._excluded_urls("django")

_traced_request_attrs = Configuration()._traced_request_attrs("django")
_traced_request_attrs = _get_traced_request_attrs()
_excluded_urls = _get_excluded_urls()

@staticmethod
def _get_span_name(request):
Expand Down Expand Up @@ -111,7 +151,7 @@ def process_request(self, request):
return

# pylint:disable=W0212
request._otel_start_time = time.time()
request._otel_start_time = time()

environ = request.META

Expand Down Expand Up @@ -215,7 +255,7 @@ def process_response(self, request, response):
if metric_recorder is not None:
# pylint:disable=W0212
metric_recorder.record_server_duration_range(
request._otel_start_time, time.time(), request._otel_labels
request._otel_start_time, time(), request._otel_labels
)
except Exception as ex: # pylint: disable=W0703
_logger.warning("Error recording duration metrics: %s", ex)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,10 @@
from django.test import Client
from django.test.utils import setup_test_environment, teardown_test_environment

from opentelemetry.configuration import Configuration
from opentelemetry.instrumentation.django import DjangoInstrumentor
from opentelemetry.instrumentation.django.middleware import (
_get_excluded_urls, _get_traced_request_attrs
)
from opentelemetry.sdk.util import get_dict_as_key
from opentelemetry.test.test_base import TestBase
from opentelemetry.test.wsgitestutil import WsgiTestBase
Expand Down Expand Up @@ -64,7 +66,6 @@ def setUp(self):
super().setUp()
setup_test_environment()
_django_instrumentor.instrument()
Configuration._reset() # pylint: disable=protected-access
self.env_patch = patch.dict(
"os.environ",
{
Expand All @@ -75,11 +76,11 @@ def setUp(self):
self.env_patch.start()
self.exclude_patch = patch(
"opentelemetry.instrumentation.django.middleware._DjangoMiddleware._excluded_urls",
Configuration()._excluded_urls("django"),
_get_excluded_urls(),
)
self.traced_patch = patch(
"opentelemetry.instrumentation.django.middleware._DjangoMiddleware._traced_request_attrs",
Configuration()._traced_request_attrs("django"),
_get_traced_request_attrs(),
)
self.exclude_patch.start()
self.traced_patch.start()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,14 +43,15 @@ def on_get(self, req, resp):
---
"""

import sys
from sys import exc_info
from logging import getLogger
from re import compile as re_compile, search
from os import environ

import falcon

import opentelemetry.instrumentation.wsgi as otel_wsgi
from opentelemetry import configuration, context, propagators, trace
from opentelemetry.configuration import Configuration
from opentelemetry import context, propagators, trace
from opentelemetry.instrumentation.falcon.version import __version__
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
from opentelemetry.instrumentation.utils import (
Expand All @@ -68,8 +69,49 @@ def on_get(self, req, resp):
_ENVIRON_TOKEN = "opentelemetry-falcon.token"
_ENVIRON_EXC = "opentelemetry-falcon.exc"

cfg = configuration.Configuration()
_excluded_urls = cfg._excluded_urls("falcon")

class _ExcludeList:
"""Class to exclude certain paths (given as a list of regexes) from tracing requests"""

def __init__(self, excluded_urls):
self._excluded_urls = excluded_urls
if self._excluded_urls:
self._regex = re_compile("|".join(excluded_urls))

def url_disabled(self, url: str) -> bool:
return bool(self._excluded_urls and search(self._regex, url))

_root = r"OTEL_PYTHON_{}"


def _get_traced_request_attrs():
traced_request_attrs = environ.get(
_root.format("FALCON_TRACED_REQUEST_ATTRS"), []
)

if traced_request_attrs:
traced_request_attrs = [
traced_request_attr.strip()
for traced_request_attr in traced_request_attrs.split(",")
]

return traced_request_attrs


def _get_excluded_urls():
excluded_urls = environ.get(_root.format("FALCON_EXCLUDED_URLS"), [])

if excluded_urls:
excluded_urls = [
excluded_url.strip()
for excluded_url in excluded_urls.split(",")
]

return _ExcludeList(excluded_urls)


_excluded_urls = _get_excluded_urls()
_traced_request_attrs = _get_traced_request_attrs()


class FalconInstrumentor(BaseInstrumentor):
Expand Down Expand Up @@ -149,7 +191,7 @@ class _TraceMiddleware:

def __init__(self, tracer=None, traced_request_attrs=None):
self.tracer = tracer
self._traced_request_attrs = cfg._traced_request_attrs("falcon")
self._traced_request_attrs = _traced_request_attrs

def process_request(self, req, resp):
span = req.env.get(_ENVIRON_SPAN_KEY)
Expand Down Expand Up @@ -186,7 +228,7 @@ def process_response(
status = "404"
reason = "NotFound"

exc_type, exc, _ = sys.exc_info()
exc_type, exc, _ = exc_info()
if exc_type and not req_succeeded:
if "HTTPNotFound" in exc_type.__name__:
status = "404"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,9 @@

from falcon import testing

from opentelemetry.configuration import Configuration
from opentelemetry.instrumentation.falcon import FalconInstrumentor
from opentelemetry.instrumentation.falcon import (
FalconInstrumentor, _get_excluded_urls, _get_traced_request_attrs
)
from opentelemetry.test.test_base import TestBase
from opentelemetry.trace.status import StatusCode

Expand All @@ -30,7 +31,6 @@ def setUp(self):
FalconInstrumentor().instrument()
self.app = make_app()
# pylint: disable=protected-access
Configuration()._reset()
self.env_patch = patch.dict(
"os.environ",
{
Expand All @@ -41,15 +41,15 @@ def setUp(self):
self.env_patch.start()
self.exclude_patch = patch(
"opentelemetry.instrumentation.falcon._excluded_urls",
Configuration()._excluded_urls("falcon"),
_get_excluded_urls(),
)
middleware = self.app._middleware[0][ # pylint:disable=W0212
0
].__self__
self.traced_patch = patch.object(
middleware,
"_traced_request_attrs",
Configuration()._traced_request_attrs("falcon"),
_get_traced_request_attrs(),
)
self.exclude_patch.start()
self.traced_patch.start()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,43 @@
# 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 typing import Optional

import fastapi
from re import compile as re_compile, search
from os import environ

from starlette.routing import Match
import fastapi

from opentelemetry.configuration import Configuration
from opentelemetry.instrumentation.asgi import OpenTelemetryMiddleware
from opentelemetry.instrumentation.fastapi.version import __version__ # noqa
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor

_excluded_urls = Configuration()._excluded_urls("fastapi")

class _ExcludeList:
"""Class to exclude certain paths (given as a list of regexes) from tracing requests"""

def __init__(self, excluded_urls):
self._excluded_urls = excluded_urls
if self._excluded_urls:
self._regex = re_compile("|".join(excluded_urls))

def url_disabled(self, url: str) -> bool:
return bool(self._excluded_urls and search(self._regex, url))


def _get_excluded_urls():
excluded_urls = environ.get("OTEL_PYTHON_FASTAPI_EXCLUDED_URLS", [])

if excluded_urls:
excluded_urls = [
excluded_url.strip()
for excluded_url in excluded_urls.split(",")
]

return _ExcludeList(excluded_urls)


_excluded_urls = _get_excluded_urls()


class FastAPIInstrumentor(BaseInstrumentor):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
from fastapi.testclient import TestClient

import opentelemetry.instrumentation.fastapi as otel_fastapi
from opentelemetry.configuration import Configuration
from opentelemetry.test.test_base import TestBase


Expand All @@ -31,15 +30,14 @@ def _create_app(self):

def setUp(self):
super().setUp()
Configuration()._reset()
self.env_patch = patch.dict(
"os.environ",
{"OTEL_PYTHON_FASTAPI_EXCLUDED_URLS": "/exclude/123,healthzz"},
)
self.env_patch.start()
self.exclude_patch = patch(
"opentelemetry.instrumentation.fastapi._excluded_urls",
Configuration()._excluded_urls("fastapi"),
otel_fastapi._get_excluded_urls(),
)
self.exclude_patch.start()
self._instrumentor = otel_fastapi.FastAPIInstrumentor()
Expand Down
Loading

0 comments on commit 432ae70

Please sign in to comment.