Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
>>> with self.override_global_config(dict(name=value,...)):
# Your test
"""
# DEV: Uses dict as interface but internally handled as attributes on Config instance
analytics_enabled_original = ddtrace.config.analytics_enabled
report_hostname_original = ddtrace.config.report_hostname
health_metrics_enabled_original = ddtrace.config.health_metrics_enabled
ddtrace.config.analytics_enabled = values.get('analytics_enabled', analytics_enabled_original)
ddtrace.config.report_hostname = values.get('report_hostname', report_hostname_original)
ddtrace.config.health_metrics_enabled = values.get('health_metrics_enabled', health_metrics_enabled_original)
try:
yield
finally:
ddtrace.config.analytics_enabled = analytics_enabled_original
ddtrace.config.report_hostname = report_hostname_original
ddtrace.config.health_metrics_enabled = health_metrics_enabled_original
def test_configuration_set(self):
# ensure the configuration can be updated in the Pin
instance = self.Klass()
cfg = config.get_from(instance)
cfg['distributed_tracing'] = True
ok_(config.get_from(instance)['distributed_tracing'] is True)
spans = self.tracer.writer.pop()
self.assertEqual(len(spans), 1)
span = spans[0]
self.assertEqual(span.span_type, 'http')
self.assertIsNone(span.service)
self.assertEqual(span.name, self.SPAN_NAME)
self.assertEqual(span.error, 0)
assert_dict_issuperset(
span.meta,
{
'http.method': 'GET',
'http.status_code': '200',
'http.url': URL_200,
}
)
if config.httplib.trace_query_string:
assert span.get_tag(http.QUERY_STRING) == query_string
else:
assert http.QUERY_STRING not in span.meta
- method (idx 0)
- url (idx 1)
- headers (idx 3)
"""
inputs = [
(("POST", URL_200, b"payload", {"accept": "*"}), {}),
(("POST", URL_200, b"payload"), {"headers": {"accept": "*"}}),
(("POST", URL_200), {"headers": {"accept": "*"}}),
(("POST",), {"url": URL_200, "headers": {"accept": "*"}}),
((), {"method": "POST", "url": URL_200, "headers": {"accept": "*"}}),
]
for args, kwargs in inputs:
with self.override_config("urllib3", {}):
config.urllib3.http.trace_headers(["accept"])
pool = urllib3.connectionpool.HTTPConnectionPool(SOCKET)
out = pool.urlopen(*args, **kwargs)
assert out.status == 200
spans = self.tracer.writer.pop()
assert len(spans) == 1
s = spans[0]
assert s.get_tag(http.METHOD) == "POST"
assert s.get_tag(http.STATUS_CODE) == "200"
assert s.get_tag(http.URL) == URL_200
assert s.get_tag("http.request.headers.accept") == "*"
def tearDown(self):
# remove instrumentation from Celery
unpatch()
self.app = None
# restore the global configuration
config.celery.update(self._config)
self._config = None
super(CeleryBaseTestCase, self).tearDown()
import molten
from ... import Pin, config
from ...compat import urlencode
from ...constants import ANALYTICS_SAMPLE_RATE_KEY
from ...ext import AppTypes, http
from ...propagation.http import HTTPPropagator
from ...utils.formats import asbool, get_env
from ...utils.importlib import func_name
from ...utils.wrappers import unwrap as _u
from .wrappers import WrapperComponent, WrapperRenderer, WrapperMiddleware, WrapperRouter, MOLTEN_ROUTE
MOLTEN_VERSION = tuple(map(int, molten.__version__.split()[0].split('.')))
# Configure default configuration
config._add('molten', dict(
service_name=get_env('molten', 'service_name', 'molten'),
app='molten',
app_type=AppTypes.web,
distributed_tracing=asbool(get_env('molten', 'distributed_tracing', True)),
))
def patch():
"""Patch the instrumented methods
"""
if getattr(molten, '_datadog_patch', False):
return
setattr(molten, '_datadog_patch', True)
pin = Pin(
service=config.molten['service_name'],
def _patch_client():
if getattr(constants.GRPC_PIN_MODULE_CLIENT, '__datadog_patch', False):
return
setattr(constants.GRPC_PIN_MODULE_CLIENT, '__datadog_patch', True)
Pin(service=config.grpc.service_name).onto(constants.GRPC_PIN_MODULE_CLIENT)
_w('grpc', 'insecure_channel', _client_channel_interceptor)
_w('grpc', 'secure_channel', _client_channel_interceptor)
if not span:
return wrapped(*args, **kwargs)
try:
request = flask._request_ctx_stack.top.request
# DEV: This name will include the blueprint name as well (e.g. `bp.index`)
if not span.get_tag(FLASK_ENDPOINT) and request.endpoint:
span.resource = u'{} {}'.format(request.method, request.endpoint)
span.set_tag(FLASK_ENDPOINT, request.endpoint)
if not span.get_tag(FLASK_URL_RULE) and request.url_rule and request.url_rule.rule:
span.resource = u'{} {}'.format(request.method, request.url_rule.rule)
span.set_tag(FLASK_URL_RULE, request.url_rule.rule)
if not span.get_tag(FLASK_VIEW_ARGS) and request.view_args and config.flask.get('collect_view_args'):
for k, v in request.view_args.items():
span.set_tag(u'{}.{}'.format(FLASK_VIEW_ARGS, k), v)
except Exception as e:
log.debug('failed to set tags for "flask.request" span: {}'.format(e))
with pin.tracer.trace('flask.{}'.format(name), service=pin.service):
return wrapped(*args, **kwargs)
return _traced_request
import grpc
import os
from ddtrace.vendor.wrapt import wrap_function_wrapper as _w
from ddtrace import config, Pin
from ...utils.wrappers import unwrap as _u
from . import constants
from .client_interceptor import create_client_interceptor
from .server_interceptor import create_server_interceptor
config._add('grpc_server', dict(
service_name=os.environ.get('DATADOG_SERVICE_NAME', constants.GRPC_SERVICE_SERVER),
distributed_tracing_enabled=True,
))
# TODO[tbutt]: keeping name for client config unchanged to maintain backwards
# compatibility but should change in future
config._add('grpc', dict(
service_name='{}-{}'.format(
os.environ.get('DATADOG_SERVICE_NAME'), constants.GRPC_SERVICE_CLIENT
) if os.environ.get('DATADOG_SERVICE_NAME') else constants.GRPC_SERVICE_CLIENT,
distributed_tracing_enabled=True,
))
def patch():
_patch_client()
def _w_makeRecord(func, instance, args, kwargs):
record = func(*args, **kwargs)
# add correlation identifiers to LogRecord
trace_id, span_id = get_correlation_ids(tracer=config.logging.tracer)
if trace_id and span_id:
setattr(record, RECORD_ATTR_TRACE_ID, trace_id)
setattr(record, RECORD_ATTR_SPAN_ID, span_id)
else:
setattr(record, RECORD_ATTR_TRACE_ID, RECORD_ATTR_VALUE_NULL)
setattr(record, RECORD_ATTR_SPAN_ID, RECORD_ATTR_VALUE_NULL)
return record