Skip to content

Commit

Permalink
Remove usage of pkg_resources
Browse files Browse the repository at this point in the history
Fixes #2927
  • Loading branch information
ocelotl committed Nov 23, 2022
1 parent 5574f7e commit a97154c
Show file tree
Hide file tree
Showing 38 changed files with 808 additions and 227 deletions.
1 change: 1 addition & 0 deletions exporter/opentelemetry-exporter-opencensus/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ dependencies = [
"opentelemetry-sdk ~= 1.3",
"protobuf ~= 3.13",
"setuptools >= 16.0",
"importlib-metadata >= 5.0.0; python_version=='3.7'"
]

[project.optional-dependencies]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,16 @@
import os
import socket
import time
from sys import version_info

import pkg_resources
# FIXME remove when support for 3.7 is dropped.
if version_info.minor == 7:
# pylint: disable=import-error
from importlib_metadata import version
else:
from importlib.metadata import version

# pylint: disable=wrong-import-position
from google.protobuf.timestamp_pb2 import Timestamp
from opencensus.proto.agent.common.v1 import common_pb2
from opencensus.proto.trace.v1 import trace_pb2
Expand All @@ -26,9 +34,7 @@
)
from opentelemetry.trace import SpanKind

OPENTELEMETRY_VERSION = pkg_resources.get_distribution(
"opentelemetry-api"
).version
OPENTELEMETRY_VERSION = version("opentelemetry-api")


def proto_timestamp_from_time_ns(time_ns):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,10 @@
)
from opentelemetry.trace import TraceFlags, format_span_id, format_trace_id

from .common_tests import TEST_SERVICE_NAME, CommonEncoderTestCases
from .common_tests import ( # pylint: disable=import-error
TEST_SERVICE_NAME,
CommonEncoderTestCases,
)


# pylint: disable=protected-access
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,10 @@
)
from opentelemetry.trace import SpanKind, TraceFlags

from .common_tests import TEST_SERVICE_NAME, CommonEncoderTestCases
from .common_tests import ( # pylint: disable=import-error
TEST_SERVICE_NAME,
CommonEncoderTestCases,
)


# pylint: disable=protected-access
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,10 @@
)
from opentelemetry.trace import SpanKind

from .common_tests import TEST_SERVICE_NAME, CommonEncoderTestCases
from .common_tests import ( # pylint: disable=import-error
TEST_SERVICE_NAME,
CommonEncoderTestCases,
)


# pylint: disable=protected-access
Expand Down
38 changes: 29 additions & 9 deletions opentelemetry-api/src/opentelemetry/context/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,16 @@
import uuid
from functools import wraps
from os import environ
from sys import version_info

from pkg_resources import iter_entry_points
# FIXME remove when support for 3.7 is dropped.
if version_info.minor == 7:
# pylint: disable=import-error
from importlib_metadata import entry_points
else:
from importlib.metadata import entry_points

# pylint: disable=wrong-import-position
from opentelemetry.context.context import Context, _RuntimeContext
from opentelemetry.environment_variables import OTEL_PYTHON_CONTEXT

Expand All @@ -41,25 +48,38 @@ def _load_runtime_context(func: _F) -> _F:
@wraps(func) # type: ignore[misc]
def wrapper( # type: ignore[misc]
*args: typing.Tuple[typing.Any, typing.Any],
**kwargs: typing.Dict[typing.Any, typing.Any]
**kwargs: typing.Dict[typing.Any, typing.Any],
) -> typing.Optional[typing.Any]:
global _RUNTIME_CONTEXT # pylint: disable=global-statement

with _RUNTIME_CONTEXT_LOCK:
if _RUNTIME_CONTEXT is None:
# FIXME use a better implementation of a configuration manager to avoid having
# to get configuration values straight from environment variables
# FIXME use a better implementation of a configuration manager
# to avoid having to get configuration values straight from
# environment variables
default_context = "contextvars_context"

configured_context = environ.get(
OTEL_PYTHON_CONTEXT, default_context
) # type: str
try:
_RUNTIME_CONTEXT = next(
iter_entry_points(
"opentelemetry_context", configured_context
)
).load()()
if version_info.minor <= 9:
for entry_point in entry_points()[
"opentelemetry_context"
]:
if entry_point.name == configured_context:
_RUNTIME_CONTEXT = entry_point.load()()
break
else:
raise Exception(
f"No entry point found for configured_context:"
f" {configured_context}"
)
else:
_RUNTIME_CONTEXT = entry_points(
group="opentelemetry_context",
name=configured_context,
)[0].load()()
except Exception: # pylint: disable=broad-except
logger.error(
"Failed to load context: %s", configured_context
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ def get_meter(
version: Optional. The version string of the
instrumenting library. Usually this should be the same as
``pkg_resources.get_distribution(instrumenting_library_name).version``.
``importlib.metadata.version(instrumenting_library_name)``.
schema_url: Optional. Specifies the Schema URL of the emitted telemetry.
"""
Expand Down
32 changes: 25 additions & 7 deletions opentelemetry-api/src/opentelemetry/propagate/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,13 +71,19 @@ def example_route():
import typing
from logging import getLogger
from os import environ

from pkg_resources import iter_entry_points
from sys import version_info

from opentelemetry.context.context import Context
from opentelemetry.environment_variables import OTEL_PROPAGATORS
from opentelemetry.propagators import composite, textmap

# FIXME remove when support for 3.7 is dropped.
if version_info.minor == 7:
# pylint: disable=import-error
from importlib_metadata import entry_points
else:
from importlib.metadata import entry_points

logger = getLogger(__name__)


Expand Down Expand Up @@ -129,14 +135,26 @@ def inject(
"tracecontext,baggage",
)


for propagator in environ_propagators.split(","):
propagator = propagator.strip()
try:
propagators.append( # type: ignore
next( # type: ignore
iter_entry_points("opentelemetry_propagator", propagator)
).load()()
)

if version_info.minor <= 9:

for entry_point in entry_points().get(
"opentelemetry_propagator", []
):
if entry_point.name == propagator:
propagators.append(entry_point.load()())
else:

propagators.append(
entry_points(
group="opentelemetry_propagator", name=propagator
)[0].load()()
)

except Exception: # pylint: disable=broad-except
logger.exception(
"Failed to load configured propagator `%s`", propagator
Expand Down
2 changes: 1 addition & 1 deletion opentelemetry-api/src/opentelemetry/trace/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,7 @@ def get_tracer(
instrumenting_library_version: Optional. The version string of the
instrumenting library. Usually this should be the same as
``pkg_resources.get_distribution(instrumenting_library_name).version``.
``importlib.metadata.version(instrumenting_library_name)``.
schema_url: Optional. Specifies the Schema URL of the emitted telemetry.
"""
Expand Down
39 changes: 29 additions & 10 deletions opentelemetry-api/src/opentelemetry/util/_providers.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,15 @@

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

from pkg_resources import iter_entry_points
# FIXME remove when support for 3.7 is dropped.
if version_info.minor == 7:
# pylint: disable=import-error
from importlib_metadata import entry_points
else:
from importlib.metadata import entry_points

if TYPE_CHECKING:
from opentelemetry.metrics import MeterProvider
Expand All @@ -30,23 +36,36 @@
def _load_provider(
provider_environment_variable: str, provider: str
) -> Provider:

try:
entry_point = next(
iter_entry_points(
f"opentelemetry_{provider}",

if version_info.minor <= 9:

provider_name = cast(
str,
environ.get(
provider_environment_variable, f"default_{provider}"
),
)

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

return cast(
Provider,
entry_points(
group=f"opentelemetry_{provider}",
name=cast(
str,
environ.get(
provider_environment_variable,
f"default_{provider}",
),
),
)
)
return cast(
Provider,
entry_point.load()(),
)[0].load()(),
)
except Exception: # pylint: disable=broad-except
logger.error("Failed to load configured provider %s", provider)
logger.exception("Failed to load configured provider %s", provider)
raise
9 changes: 0 additions & 9 deletions opentelemetry-api/tests/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,3 @@
# 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.
import pkg_resources

# naming the tests module as a namespace package ensures that
# relative imports will resolve properly for other test packages,
# as it enables searching for a composite of multiple test modules.
#
# only the opentelemetry-api directory needs this code, as it is
# the first tests module found by pylint during eachdist.py lint
pkg_resources.declare_namespace(__name__)
91 changes: 74 additions & 17 deletions opentelemetry-api/tests/propagators/test_propagators.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
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 @@ -51,31 +52,87 @@ def test_propagators(propagators):

reload(opentelemetry.propagate)

if version_info.minor == 7:
entry_points_path = "importlib_metadata.entry_points"
else:
entry_points_path = "importlib.metadata.entry_points"

@patch.dict(environ, {OTEL_PROPAGATORS: "a, b, c "})
@patch("opentelemetry.propagators.composite.CompositePropagator")
@patch("pkg_resources.iter_entry_points")
@patch(entry_points_path)
def test_non_default_propagators(
self, mock_iter_entry_points, mock_compositehttppropagator
self, mock_entry_points, mock_compositehttppropagator
):
def iter_entry_points_mock(_, propagator):
return iter(
[
Mock(
**{
"load.side_effect": [
Mock(**{"side_effect": [propagator]})
]
}
)
]

if version_info.minor <= 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_iter_entry_points.configure_mock(
**{"side_effect": iter_entry_points_mock}
)
mock_entry_points.configure_mock(
**{
"return_value": {
"opentelemetry_propagator": [mock_a, mock_b, mock_c]
}
}
)

def test_propagators(propagators):
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"}
)
}
)
],
]
}
)

def test_propagators(propagators):
self.assertEqual(propagators, ["a", "b", "c"])

mock_compositehttppropagator.configure_mock(
Expand Down
Loading

0 comments on commit a97154c

Please sign in to comment.