Skip to content

Commit

Permalink
Add pre and post instrument entry points
Browse files Browse the repository at this point in the history
  • Loading branch information
ocelotl committed Aug 25, 2021
1 parent 4250078 commit f473f18
Show file tree
Hide file tree
Showing 5 changed files with 50 additions and 236 deletions.
8 changes: 0 additions & 8 deletions opentelemetry-instrumentation/README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,6 @@ Installation

This package provides a couple of commands that help automatically instruments a program:

.. note::
You need to install a distro package to get auto instrumentation working. The ``opentelemetry-distro``
package contains the default distro and automatically configures some of the common options for users.
For more info about ``opentelemetry-distro`` check `here <https://opentelemetry-python.readthedocs.io/en/latest/examples/distro/README.html>`__
::

pip install opentelemetry-distro[otlp]


opentelemetry-bootstrap
-----------------------
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,124 +12,54 @@
# See the License for the specific language governing permissions and
# limitations under the License.

import sys

from logging import getLogger
from os import environ, path
from os import environ
from os.path import abspath, dirname, pathsep
from re import sub

from pkg_resources import iter_entry_points

from opentelemetry.environment_variables import (
OTEL_PYTHON_DISABLED_INSTRUMENTATIONS,
)
from opentelemetry.instrumentation.dependencies import (
get_dist_dependency_conflicts,
)
from opentelemetry.instrumentation.distro import BaseDistro, DefaultDistro

logger = getLogger(__file__)

from opentelemetry.instrumentation.environment_variables import (
OTEL_PYTHON_DISABLED_INSTRUMENTATIONS,
)

def _load_distros() -> BaseDistro:
for entry_point in iter_entry_points("opentelemetry_distro"):
try:
distro = entry_point.load()()
if not isinstance(distro, BaseDistro):
logger.debug(
"%s is not an OpenTelemetry Distro. Skipping",
entry_point.name,
)
continue
logger.debug(
"Distribution %s will be configured", entry_point.name
)
return distro
except Exception as exc: # pylint: disable=broad-except
logger.exception(
"Distribution %s configuration failed", entry_point.name
)
raise exc
return DefaultDistro()
_logger = getLogger(__file__)


def _load_instrumentors(distro):
package_to_exclude = environ.get(OTEL_PYTHON_DISABLED_INSTRUMENTATIONS, [])
if isinstance(package_to_exclude, str):
package_to_exclude = package_to_exclude.split(",")
# to handle users entering "requests , flask" or "requests, flask" with spaces
package_to_exclude = [x.strip() for x in package_to_exclude]
for entry_point in iter_entry_points("opentelemetry-pre-instrument"):
entry_point.load()()

for entry_point in iter_entry_points("opentelemetry_instrumentor"):
if entry_point.name in package_to_exclude:
logger.debug(
"Instrumentation skipped for library %s", entry_point.name
)
continue
try:
disabled_instrumentations = set(
environ.get(OTEL_PYTHON_DISABLED_INSTRUMENTATIONS, "").split()
)

try:
conflict = get_dist_dependency_conflicts(entry_point.dist)
if conflict:
logger.debug(
"Skipping instrumentation %s: %s",
entry_point.name,
conflict,
)
continue
for entry_point in iter_entry_points("opentelemetry-instrumentor"):
if entry_point.name in disabled_instrumentations:
_logger.debug("Instrumentation skipped for %s", entry_point.name)

# tell instrumentation to not run dep checks again as we already did it above
distro.load_instrumentor(entry_point, skip_dep_check=True)
logger.debug("Instrumented %s", entry_point.name)
except Exception as exc: # pylint: disable=broad-except
logger.exception("Instrumenting of %s failed", entry_point.name)
raise exc
conflicts = get_dist_dependency_conflicts(entry_point.dist)

if conflicts is not None:

def _load_configurators():
configured = None
for entry_point in iter_entry_points("opentelemetry_configurator"):
if configured is not None:
logger.warning(
"Configuration of %s not loaded, %s already loaded",
_logger.debug(
"Skipping instrumentation %s: %s",
entry_point.name,
configured,
conflicts,
)
continue
try:
entry_point.load()().configure() # type: ignore
configured = entry_point.name
except Exception as exc: # pylint: disable=broad-except
logger.exception("Configuration of %s failed", entry_point.name)
raise exc


def initialize():
try:
distro = _load_distros()
distro.configure()
_load_configurators()
_load_instrumentors(distro)
except Exception: # pylint: disable=broad-except
logger.exception("Failed to auto initialize opentelemetry")
finally:
environ["PYTHONPATH"] = sub(
r"{}{}?".format(dirname(abspath(__file__)), pathsep),
"",
environ["PYTHONPATH"],
)


if (
hasattr(sys, "argv")
and sys.argv[0].split(path.sep)[-1] == "celery"
and "worker" in sys.argv[1:]
):
from celery.signals import worker_process_init # pylint:disable=E0401

@worker_process_init.connect(weak=False)
def init_celery(*args, **kwargs):
initialize()
entry_point.load().instrument(skip_dep_check=True)

finally:
environ["PYTHONPATH"] = sub(
r"{}{}?".format(dirname(abspath(__file__)), pathsep),
"",
environ["PYTHONPATH"],
)

else:
initialize()
for entry_point in iter_entry_points("opentelemetry-post-instrument"):
entry_point.load()()

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# 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.


OTEL_PYTHON_DISABLED_INSTRUMENTATIONS = "OTEL_PYTHON_DISABLED_INSTRUMENTATIONS"
"""
.. envvar:: OTEL_PYTHON_DISABLED_INSTRUMENTATIONS
Space-separated string of `opentelemetry-instrumentor` entry point names.
"""
58 changes: 0 additions & 58 deletions opentelemetry-instrumentation/tests/test_distro.py

This file was deleted.

0 comments on commit f473f18

Please sign in to comment.