Skip to content

Commit

Permalink
Refactor implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
ocelotl committed Dec 14, 2022
1 parent 994d19e commit c6435b1
Show file tree
Hide file tree
Showing 13 changed files with 206 additions and 454 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
__version__ as opencensusexporter_exporter_version,
)
from opentelemetry.trace import SpanKind
from opentelemetry.util._entry_points import version
from opentelemetry.util._importlib_metadata import version

OPENTELEMETRY_VERSION = version("opentelemetry-api")

Expand Down
41 changes: 9 additions & 32 deletions opentelemetry-api/src/opentelemetry/context/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,11 @@
import uuid
from functools import wraps
from os import environ
from sys import version_info

# pylint: disable=wrong-import-position
from opentelemetry.context.context import Context, _RuntimeContext # noqa
from opentelemetry.environment_variables import OTEL_PYTHON_CONTEXT
from opentelemetry.util._entry_points import entry_points
from opentelemetry.util._importlib_metadata import entry_points

logger = logging.getLogger(__name__)
_RUNTIME_CONTEXT = None # type: typing.Optional[_RuntimeContext]
Expand Down Expand Up @@ -57,37 +56,15 @@ def wrapper( # type: ignore[misc]
OTEL_PYTHON_CONTEXT, default_context
) # type: str
try:
# FIXME Remove when support for 3.9 is dropped.
if version_info.minor in (8, 9):
for entry_point in entry_points()[ # type: ignore
"opentelemetry_context"
]:
if entry_point.name == configured_context: # type: ignore
_RUNTIME_CONTEXT = entry_point.load()() # type: ignore
break
else:
raise Exception(
f"No entry point found for configured_context:"
f" {configured_context}"
)
else:

try:
_RUNTIME_CONTEXT = next( # type: ignore
iter( # type: ignore
entry_points( # type: ignore
group="opentelemetry_context",
name=configured_context,
)
)
).load()()

except StopIteration:

raise Exception(
f"No entry point found for configured_context:"
f" {configured_context}"

_RUNTIME_CONTEXT = next( # type: ignore
iter( # type: ignore
entry_points( # type: ignore
group="opentelemetry_context",
name=configured_context,
)
)
).load()()

except Exception: # pylint: disable=broad-except
logger.exception(
Expand Down
37 changes: 14 additions & 23 deletions opentelemetry-api/src/opentelemetry/propagate/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,22 +68,21 @@ def example_route():
https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/context/api-propagators.md
"""

import typing
from logging import getLogger
from os import environ
from sys import version_info
from typing import Optional

from opentelemetry.context.context import Context
from opentelemetry.environment_variables import OTEL_PROPAGATORS
from opentelemetry.propagators import composite, textmap
from opentelemetry.util._entry_points import entry_points
from opentelemetry.util._importlib_metadata import entry_points

logger = getLogger(__name__)


def extract(
carrier: textmap.CarrierT,
context: typing.Optional[Context] = None,
context: Optional[Context] = None,
getter: textmap.Getter[textmap.CarrierT] = textmap.default_getter,
) -> Context:
"""Uses the configured propagator to extract a Context from the carrier.
Expand All @@ -104,7 +103,7 @@ def extract(

def inject(
carrier: textmap.CarrierT,
context: typing.Optional[Context] = None,
context: Optional[Context] = None,
setter: textmap.Setter[textmap.CarrierT] = textmap.default_setter,
) -> None:
"""Uses the configured propagator to inject a Context into the carrier.
Expand Down Expand Up @@ -134,25 +133,17 @@ def inject(
propagator = propagator.strip()

try:
# FIXME Remove when support for 3.9 is dropped.
if version_info.minor in (8, 9):
for entry_point in entry_points().get( # type: ignore
"opentelemetry_propagator", []
):
if entry_point.name == propagator: # type: ignore
propagators.append(entry_point.load()()) # type: ignore
else:

propagators.append( # type: ignore
next( # type: ignore
iter( # type: ignore
entry_points( # type: ignore
group="opentelemetry_propagator",
name=propagator,
)

propagators.append( # type: ignore
next( # type: ignore
iter( # type: ignore
entry_points( # type: ignore
group="opentelemetry_propagator",
name=propagator,
)
).load()()
)
)
).load()()
)

except Exception: # pylint: disable=broad-except
logger.exception(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,25 @@

from sys import version_info

# FIXME remove this file when support for 3.7 is dropped.
# FIXME remove this when support for 3.7 is dropped.
if version_info.minor == 7:
# pylint: disable=import-error
from importlib_metadata import entry_points, version # type: ignore

# FIXME remove this file when support for 3.9 is dropped.
elif version_info.minor in (8, 9):
# pylint: disable=import-error
from importlib.metadata import (
entry_points as importlib_metadata_entry_points,
)
from importlib.metadata import version

def entry_points(group: str, name: str): # type: ignore
for entry_point in importlib_metadata_entry_points()[group]:
if entry_point.name == name:
yield entry_point

else:
from importlib.metadata import entry_points, version # type: ignore
from importlib.metadata import entry_points, version

__all__ = ["entry_points", "version"]
11 changes: 1 addition & 10 deletions opentelemetry-api/src/opentelemetry/util/_providers.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,9 @@

from logging import getLogger
from os import environ
from sys import version_info
from typing import TYPE_CHECKING, TypeVar, cast

from opentelemetry.util._entry_points import entry_points
from opentelemetry.util._importlib_metadata import entry_points

if TYPE_CHECKING:
from opentelemetry.metrics import MeterProvider
Expand All @@ -39,14 +38,6 @@ def _load_provider(
environ.get(provider_environment_variable, f"default_{provider}"),
)

# FIXME remove when support for 3.9 is dropped.
if version_info.minor in (8, 9):

for entry_point in entry_points()[f"opentelemetry_{provider}"]: # type: ignore
if entry_point.name == provider_name: # type: ignore
return cast(Provider, entry_point.load()()) # type: ignore
raise Exception(f"Provider {provider_name} not found")

return cast(
Provider,
next( # type: ignore
Expand Down
104 changes: 34 additions & 70 deletions opentelemetry-api/tests/propagators/test_propagators.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
from importlib import reload
from logging import ERROR
from os import environ
from sys import version_info
from unittest import TestCase
from unittest.mock import Mock, patch

Expand Down Expand Up @@ -54,79 +53,44 @@ def test_propagators(propagators):

@patch.dict(environ, {OTEL_PROPAGATORS: "a, b, c "})
@patch("opentelemetry.propagators.composite.CompositePropagator")
@patch("opentelemetry.util._entry_points.entry_points")
@patch("opentelemetry.util._importlib_metadata.entry_points")
def test_non_default_propagators(
self, mock_entry_points, mock_compositehttppropagator
):

# FIXME Remove when support for 3.9 is dropped.
if version_info.minor in (8, 9):

mock_a = Mock()
mock_a.configure_mock(
**{
"name": "a",
"load.return_value": Mock(**{"return_value": "a"}),
}
)
mock_b = Mock()
mock_b.configure_mock(
**{
"name": "b",
"load.return_value": Mock(**{"return_value": "b"}),
}
)
mock_c = Mock()
mock_c.configure_mock(
**{
"name": "c",
"load.return_value": Mock(**{"return_value": "c"}),
}
)

mock_entry_points.configure_mock(
**{
"return_value": {
"opentelemetry_propagator": [mock_a, mock_b, mock_c]
}
}
)

else:

mock_entry_points.configure_mock(
**{
"side_effect": [
[
Mock(
**{
"load.return_value": Mock(
**{"return_value": "a"}
)
}
),
],
[
Mock(
**{
"load.return_value": Mock(
**{"return_value": "b"}
)
}
)
],
[
Mock(
**{
"load.return_value": Mock(
**{"return_value": "c"}
)
}
)
],
]
}
)
mock_entry_points.configure_mock(
**{
"side_effect": [
[
Mock(
**{
"load.return_value": Mock(
**{"return_value": "a"}
)
}
),
],
[
Mock(
**{
"load.return_value": Mock(
**{"return_value": "b"}
)
}
)
],
[
Mock(
**{
"load.return_value": Mock(
**{"return_value": "c"}
)
}
)
],
]
}
)

def test_propagators(propagators):
self.assertEqual(propagators, ["a", "b", "c"])
Expand Down
34 changes: 34 additions & 0 deletions opentelemetry-api/tests/util/test__importlib_metadata.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# Copyright The 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 unittest import TestCase

from opentelemetry.metrics import MeterProvider
from opentelemetry.util._importlib_metadata import entry_points


class TestEntryPoints(TestCase):
def test_entry_points(self):

self.assertIsInstance(
next(
iter(
entry_points(
group="opentelemetry_meter_provider",
name="default_meter_provider",
)
)
).load()(),
MeterProvider,
)
Loading

0 comments on commit c6435b1

Please sign in to comment.