def test_context_key(self):
     key1 = context.create_key("say")
     key2 = context.create_key("say")
     self.assertNotEqual(key1, key2)
     first = context.set_value(key1, "foo")
     second = context.set_value(key2, "bar")
     self.assertEqual(context.get_value(key1, context=first), "foo")
     self.assertEqual(context.get_value(key2, context=second), "bar")
    def test_context(self):
        key1 = context.create_key("say")
        self.assertIsNone(context.get_value(key1))
        empty = context.get_current()
        second = context.set_value(key1, "foo")
        self.assertEqual(context.get_value(key1, context=second), "foo")

        key2 = _do_work()
        self.assertEqual(context.get_value(key2), "bar")
        third = context.get_current()

        self.assertIsNone(context.get_value(key1, context=empty))
        self.assertEqual(context.get_value(key1, context=second), "foo")
        self.assertEqual(context.get_value(key2, context=third), "bar")
Beispiel #3
0
    def __init__(self, env: Env) -> None:
        self.optional_variables = [
            ("OPENTELEMETRY_ENABLED", env.bool),
            ("OTEL_TRACES_EXPORTER", env.str),
        ]
        self.configure(env)

        if not self.OPENTELEMETRY_ENABLED or self.OTEL_TRACES_EXPORTER == "none":
            raise PluginMissingConfiguration("Opentelemetry not enabled")
        if not HAS_OPENTELEMETRY:
            raise PluginMissingConfiguration("Extra packages for opentelemetry missing")

        pipeline_resource = Resource.create(
            {
                "pipeline.ci": str(settings.active_ci),
                "pipeline.commit_sha": settings.GIT_COMMIT_SHA,
                "pipeline.commit_ref_name": settings.GIT_COMMIT_REF_NAME,
                "pipeline.environment": settings.ENVIRONMENT_SLUG,
                "pipeline.id": settings.JOB_PIPELINE_ID,
                "pipeline.job_id": settings.JOB_ID,
                "pipeline.job_name": settings.JOB_NAME,
                "pipeline.pr_id": settings.PR_ID,
                "pipeline.project_id": settings.PROJECT_ID,
                "service.name": "kolga",
                # "service.version": "settings.KOLGA_VERSION",
            },
        )

        tracer_provider = TracerProvider(resource=pipeline_resource)
        span_processor = BatchSpanProcessor(self._get_exporter())
        tracer_provider.add_span_processor(span_processor)
        trace.set_tracer_provider(tracer_provider)
        tracer = trace.get_tracer(__name__)

        self.context_detach_tokens: List[str] = []
        self.lifecycle_key = context.create_key("kolga_lifecycle")
        self.known_exceptions: Set[int] = set()
        self.tracer = tracer

        # FIXME: We would like to get sub-traces from buildkit but at the time of writing it
        #        segfaults when OTEL is detected: https://github.com/docker/buildx/pull/925.
        for key in os.environ:
            if key.startswith("OTEL_"):
                del os.environ[key]
Beispiel #4
0
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
from opentelemetry.instrumentation.requests.package import _instruments
from opentelemetry.instrumentation.requests.version import __version__
from opentelemetry.instrumentation.utils import (
    _SUPPRESS_INSTRUMENTATION_KEY,
    http_status_to_status_code,
)
from opentelemetry.propagate import inject
from opentelemetry.semconv.trace import SpanAttributes
from opentelemetry.trace import SpanKind, get_tracer
from opentelemetry.trace.status import Status
from opentelemetry.util.http import remove_url_credentials

# A key to a context variable to avoid creating duplicate spans when instrumenting
# both, Session.request and Session.send, since Session.request calls into Session.send
_SUPPRESS_HTTP_INSTRUMENTATION_KEY = context.create_key(
    "suppress_http_instrumentation")


# pylint: disable=unused-argument
# pylint: disable=R0915
def _instrument(tracer, span_callback=None, name_callback=None):
    """Enables tracing of all requests calls that go through
    :code:`requests.session.Session.request` (this includes
    :code:`requests.get`, etc.)."""

    # Since
    # https://github.com/psf/requests/commit/d72d1162142d1bf8b1b5711c664fbbd674f349d1
    # (v0.7.0, Oct 23, 2011), get, post, etc are implemented via request which
    # again, is implemented via Session.request (`Session` was named `session`
    # before v1.0.0, Dec 17, 2012, see
    # https://github.com/psf/requests/commit/4e5c4a6ab7bb0195dececdd19bb8505b872fe120)
def _do_work() -> str:
    key = context.create_key("say")
    context.attach(context.set_value(key, "bar"))
    return key
# 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 typing import Dict, Sequence

from wrapt import ObjectProxy

from opentelemetry.context import create_key
from opentelemetry.trace import StatusCode

# FIXME This is a temporary location for the suppress instrumentation key.
# Once the decision around how to suppress instrumentation is made in the
# spec, this key should be moved accordingly.
_SUPPRESS_INSTRUMENTATION_KEY = create_key("suppress_instrumentation")


def extract_attributes_from_object(
        obj: any,
        attributes: Sequence[str],
        existing: Dict[str, str] = None) -> Dict[str, str]:
    extracted = {}
    if existing:
        extracted.update(existing)
    for attr in attributes:
        value = getattr(obj, attr, None)
        if value is not None:
            extracted[attr] = str(value)
    return extracted
Beispiel #7
0
from opentelemetry.shim.opentracing_shim import util
from opentelemetry.shim.opentracing_shim.version import __version__
from opentelemetry.trace import INVALID_SPAN_CONTEXT, Link, NonRecordingSpan
from opentelemetry.trace import SpanContext as OtelSpanContext
from opentelemetry.trace import Tracer as OtelTracer
from opentelemetry.trace import (
    TracerProvider,
    get_current_span,
    set_span_in_context,
    use_span,
)
from opentelemetry.util.types import Attributes

ValueT = TypeVar("ValueT", int, float, bool, str)
logger = logging.getLogger(__name__)
_SHIM_KEY = create_key("scope_shim")


def create_tracer(otel_tracer_provider: TracerProvider) -> "TracerShim":
    """Creates a :class:`TracerShim` object from the provided OpenTelemetry
    :class:`opentelemetry.trace.TracerProvider`.

    The returned :class:`TracerShim` is an implementation of
    :class:`opentracing.Tracer` using OpenTelemetry under the hood.

    Args:
        otel_tracer_provider: A tracer from this provider  will be used to
            perform the actual tracing when user code is instrumented using the
            OpenTracing API.

    Returns:
Beispiel #8
0
# limitations under the License.

from logging import getLogger
from re import compile
from types import MappingProxyType
from typing import Mapping, Optional

from opentelemetry.context import create_key, get_value, set_value
from opentelemetry.context.context import Context
from opentelemetry.util.re import (
    _BAGGAGE_PROPERTY_FORMAT,
    _KEY_FORMAT,
    _VALUE_FORMAT,
)

_BAGGAGE_KEY = create_key("baggage")
_logger = getLogger(__name__)

_KEY_PATTERN = compile(_KEY_FORMAT)
_VALUE_PATTERN = compile(_VALUE_FORMAT)
_PROPERT_PATTERN = compile(_BAGGAGE_PROPERTY_FORMAT)


def get_all(
    context: Optional[Context] = None,
) -> Mapping[str, object]:
    """Returns the name/value pairs in the Baggage

    Args:
        context: The Context to use. If not set, uses current Context
Beispiel #9
0
#
#     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 typing import Optional

from opentelemetry.context import create_key, get_value, set_value
from opentelemetry.context.context import Context
from opentelemetry.trace.span import INVALID_SPAN, Span

SPAN_KEY = "current-span"
_SPAN_KEY = create_key("current-span")


def set_span_in_context(span: Span,
                        context: Optional[Context] = None) -> Context:
    """Set the span in the given context.

    Args:
        span: The Span to set.
        context: a Context object. if one is not passed, the
            default current context is used instead.
    """
    ctx = set_value(_SPAN_KEY, span, context=context)
    return ctx