Example #1
0
def arrange_scope_manager(scope_manager):
    if scope_manager is None:
        try:
            import sys
            if (sys.version_info[0] > 3) or (sys.version_info[0] == 3
                                             and sys.version_info[1] > 7) or (
                                                 sys.version_info[0] == 3
                                                 and sys.version_info[1] == 7
                                                 and sys.version_info[2] != 0):
                from opentracing.scope_managers.contextvars import ContextVarsScopeManager
                scope_manager = ContextVarsScopeManager()
            else:
                scope_manager = ThreadLocalScopeManager()
        except Exception:
            scope_manager = ThreadLocalScopeManager()
    return scope_manager
    def __init__(self,
                 service_name,
                 recorder,
                 scope_manager=None,
                 common_tags=None,
                 use_shared_spans=False):
        """
        Initialize a Haystack Tracer instance.
        :param service_name: The service name to which all spans will belong.
        :param recorder: The recorder (dispatcher) implementation which handles
        finished spans.
        :param scope_manager: An optional parameter to override the default
        ThreadLocal scope manager.
        :param common_tags: An optional dictionary of tags which should be
        applied to all created spans for this service
        :param use_shared_spans: A boolean indicating whether or not to use
        shared spans. This is when client/server spans share the same span id.
        Default is to use unique span ids.
        """

        scope_manager = ThreadLocalScopeManager() if scope_manager is None \
            else scope_manager
        super().__init__(scope_manager)
        self._propagators = {}
        self._common_tags = {} if common_tags is None else common_tags
        self.service_name = service_name
        self.recorder = recorder
        self.use_shared_spans = use_shared_spans
        self.register_propagator(Format.TEXT_MAP, TextPropagator())
        self.register_propagator(Format.HTTP_HEADERS, TextPropagator())
Example #3
0
    def __init__(self, service_name=None, config=None, scope_manager=None, dd_tracer=None):
        """Initialize a new Datadog opentracer.

        :param service_name: (optional) the name of the service that this
            tracer will be used with. Note if not provided, a service name will
            try to be determined based off of ``sys.argv``. If this fails a
            :class:`ddtrace.settings.ConfigException` will be raised.
        :param config: (optional) a configuration object to specify additional
            options. See the documentation for further information.
        :param scope_manager: (optional) the scope manager for this tracer to
            use. The available managers are listed in the Python OpenTracing repo
            here: https://github.com/opentracing/opentracing-python#scope-managers.
            If ``None`` is provided, defaults to
            :class:`opentracing.scope_managers.ThreadLocalScopeManager`.
        :param dd_tracer: (optional) the Datadog tracer for this tracer to use. This
            should only be passed if a custom Datadog tracer is being used. Defaults
            to the global ``ddtrace.tracer`` tracer.
        """
        # Merge the given config with the default into a new dict
        config = config or {}
        self._config = merge_dicts(DEFAULT_CONFIG, config)

        # Pull out commonly used properties for performance
        self._service_name = service_name or get_application_name()
        self._enabled = self._config.get(keys.ENABLED)
        self._debug = self._config.get(keys.DEBUG)

        if self._debug:
            # Ensure there are no typos in any of the keys
            invalid_keys = config_invalid_keys(self._config)
            if invalid_keys:
                str_invalid_keys = ','.join(invalid_keys)
                raise ConfigException('invalid key(s) given ({})'.format(str_invalid_keys))

        if not self._service_name:
            raise ConfigException(""" Cannot detect the \'service_name\'.
                                      Please set the \'service_name=\'
                                      keyword argument.
                                  """)

        self._scope_manager = scope_manager or ThreadLocalScopeManager()

        dd_context_provider = get_context_provider_for_scope_manager(self._scope_manager)

        self._dd_tracer = dd_tracer or ddtrace.tracer or DatadogTracer()
        self._dd_tracer.set_tags(self._config.get(keys.GLOBAL_TAGS))
        self._dd_tracer.configure(enabled=self._enabled,
                                  hostname=self._config.get(keys.AGENT_HOSTNAME),
                                  https=self._config.get(keys.AGENT_HTTPS),
                                  port=self._config.get(keys.AGENT_PORT),
                                  sampler=self._config.get(keys.SAMPLER),
                                  settings=self._config.get(keys.SETTINGS),
                                  priority_sampling=self._config.get(keys.PRIORITY_SAMPLING),
                                  uds_path=self._config.get(keys.UDS_PATH),
                                  context_provider=dd_context_provider,
                                  )
        self._propagators = {
            Format.HTTP_HEADERS: HTTPPropagator(),
            Format.TEXT_MAP: HTTPPropagator(),
        }
 def test_tracer_callable_str(self):
     settings.OPENTRACING_TRACER_CALLABLE = 'opentracing.mocktracer.MockTracer'
     settings.OPENTRACING_TRACER_PARAMETERS = {
             'scope_manager': ThreadLocalScopeManager()
     }
     OpenTracingMiddleware()
     assert getattr(settings, 'OPENTRACING_TRACING', None) is not None
     assert isinstance(settings.OPENTRACING_TRACING.tracer, MockTracer)
Example #5
0
 def __init__(self, client_instance=None, config=None, scope_manager=None):
     self._agent = client_instance or self._zuqa_client_class(config=config)
     if scope_manager and not isinstance(scope_manager, ThreadLocalScopeManager):
         warnings.warn(
             "Currently, the ZUQA opentracing bridge only supports the ThreadLocalScopeManager. "
             "Usage of other scope managers will lead to unpredictable results."
         )
     self._scope_manager = scope_manager or ThreadLocalScopeManager()
     if self._agent.config.instrument and self._agent.config.enabled:
         instrument()
Example #6
0
    def __init__(self, scope_manager: ScopeManager = None):
        """Initialize an EventBasedTracer instance.
        Note that the returned EventBasedTracer has *no* propagators registered. The
        user should either call register_propagator() for each needed
        inject/extract format and/or the user can simply call
        register_required_propagators().
        The required formats are opt-in because of protobuf version conflicts
        with the binary carrier.
        """

        scope_manager = ThreadLocalScopeManager() \
            if scope_manager is None else scope_manager
        super(EventBasedTracer, self).__init__(scope_manager)

        self._propagators = {}
Example #7
0
    def __init__(self, scope_manager=None):
        """Initialize a MockTracer instance."""

        scope_manager = ThreadLocalScopeManager() \
            if scope_manager is None else scope_manager
        super(MockTracer, self).__init__(scope_manager)

        self._propagators = {}
        self._finished_spans = []
        self._spans_lock = Lock()

        # Simple-as-possible (consecutive for repeatability) id generation.
        self._next_id = 0
        self._next_id_lock = Lock()

        self._register_required_propagators()
Example #8
0
    def __init__(self, reporter, application_tags, global_tags=None):
        """
        Construct Wavefront Tracer.

        :param reporter: Reporter
        :type reporter: :class:`Reporter`
        :param application_tags: Application Tags
        :type application_tags: :class:`ApplicationTags`
        :param global_tags: Global tags for the tracer
        :type global_tags: list of pair
        """
        super(WavefrontTracer, self).__init__(ThreadLocalScopeManager())
        self._reporter = reporter
        self._tags = global_tags or []
        self._tags.extend(application_tags.get_as_list())
        self.registry = registry.PropagatorRegistry()
Example #9
0
def init_jaeger_tracer() -> Tracer:
    config = Config(config={
        'sampler': {
            'type': 'const',
            'param': 1,
        },
        'logging': True,
        'propagation': "b3",
        'local_agent': {
            'reporting_host': 'localhost'
        }
    },
                    service_name='service1',
                    validate=True,
                    scope_manager=ThreadLocalScopeManager())
    return config.initialize_tracer()
    def test_tracer_callable_str(self):
        tracer_callable = 'opentracing.mocktracer.MockTracer'
        tracer_parameters = {
            'scope_manager': ThreadLocalScopeManager(),
        }
        registry = DummyRegistry()
        registry.settings['ot.tracer_callable'] = tracer_callable
        registry.settings['ot.tracer_parameters'] = tracer_parameters
        self._call(registry=registry)
        self.assertIsNotNone(registry.settings.get('ot.tracing'))
        self.assertIsNotNone(registry.settings.get('ot.tracing').tracer)

        tracer = registry.settings['ot.tracing'].tracer
        self.assertTrue(isinstance(tracer, MockTracer))
        self.assertEqual(tracer_parameters['scope_manager'],
                         tracer.scope_manager)
Example #11
0
 def scope_manager(self):
     return ThreadLocalScopeManager()
Example #12
0
    def __init__(
        self, service_name, reporter, sampler, metrics=None,
        metrics_factory=None,
        trace_id_header=constants.TRACE_ID_HEADER,
        generate_128bit_trace_id=False,
        baggage_header_prefix=constants.BAGGAGE_HEADER_PREFIX,
        debug_id_header=constants.DEBUG_ID_HEADER_KEY,
        one_span_per_rpc=False, extra_codecs=None,
        tags=None,
        max_tag_value_length=constants.MAX_TAG_VALUE_LENGTH,
        max_traceback_length=constants.MAX_TRACEBACK_LENGTH,
        throttler=None,
        scope_manager=None,
    ):
        self.service_name = service_name
        self.reporter = reporter
        self.sampler = sampler
        self.metrics_factory = metrics_factory or LegacyMetricsFactory(metrics or Metrics())
        self.metrics = TracerMetrics(self.metrics_factory)
        self.random = random.Random(time.time() * (os.getpid() or 1))
        self.debug_id_header = debug_id_header
        self.one_span_per_rpc = one_span_per_rpc
        self.max_tag_value_length = max_tag_value_length
        self.max_traceback_length = max_traceback_length
        self.max_trace_id_bits = constants._max_trace_id_bits if generate_128bit_trace_id \
            else constants._max_id_bits
        self.codecs = {
            Format.TEXT_MAP: TextCodec(
                url_encoding=False,
                trace_id_header=trace_id_header,
                baggage_header_prefix=baggage_header_prefix,
                debug_id_header=debug_id_header,
            ),
            Format.HTTP_HEADERS: TextCodec(
                url_encoding=True,
                trace_id_header=trace_id_header,
                baggage_header_prefix=baggage_header_prefix,
                debug_id_header=debug_id_header,
            ),
            Format.BINARY: BinaryCodec(),
            ZipkinSpanFormat: ZipkinCodec(),
        }
        if extra_codecs:
            self.codecs.update(extra_codecs)
        self.tags = {
            constants.JAEGER_VERSION_TAG_KEY: constants.JAEGER_CLIENT_VERSION,
        }
        if tags:
            self.tags.update(tags)

        if self.tags.get(constants.JAEGER_IP_TAG_KEY) is None:
            self.tags[constants.JAEGER_IP_TAG_KEY] = local_ip()

        if self.tags.get(constants.JAEGER_HOSTNAME_TAG_KEY) is None:
            try:
                hostname = socket.gethostname()
                self.tags[constants.JAEGER_HOSTNAME_TAG_KEY] = hostname
            except socket.error:
                logger.exception('Unable to determine host name')

        self.throttler = throttler
        if self.throttler:
            client_id = random.randint(0, sys.maxsize)
            self.throttler._set_client_id(client_id)
            self.tags[constants.CLIENT_UUID_TAG_KEY] = client_id

        self.reporter.set_process(
            service_name=self.service_name,
            tags=self.tags,
            max_length=self.max_tag_value_length,
        )

        super(Tracer, self).__init__(
            scope_manager=scope_manager or ThreadLocalScopeManager()
        )
Example #13
0
 def __init__(self, service_name, port, sample_rate, transport_handler=None, scope_manager=None):
     super().__init__(service_name, scope_manager=scope_manager or ThreadLocalScopeManager())
     self._port = port
     self._sample_rate = sample_rate
     self._transport_handler = transport_handler or queued_transport
 def test_get_context_provider_for_scope_manager_thread(self):
     scope_manager = ThreadLocalScopeManager()
     ctx_prov = get_context_provider_for_scope_manager(scope_manager)
     assert isinstance(ctx_prov, ddtrace.provider.DefaultContextProvider)
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
from __future__ import absolute_import

from mock import patch

import opentracing
from opentracing.scope_managers import ThreadLocalScopeManager
from opentracing_instrumentation.local_span import func_span
from opentracing_instrumentation.client_hooks._dbapi2 import db_span, _COMMIT
from opentracing_instrumentation.client_hooks._singleton import singleton
from opentracing_instrumentation import span_in_context


@patch('opentracing.tracer', new=opentracing.Tracer(ThreadLocalScopeManager()))
def test_func_span_without_parent():
    with func_span('test', require_active_trace=False) as span:
        assert span is not None
    with func_span('test', require_active_trace=True) as span:
        assert span is None


def test_func_span():
    tracer = opentracing.tracer
    span = tracer.start_span(operation_name='parent')
    with span_in_context(span=span):
        with func_span('test') as child_span:
            assert span is child_span
        with func_span('test', tags={'x': 'y'}) as child_span:
            assert span is child_span