def test_get_env(self): # ensure `get_env` returns a default value if environment variables # are not set value = get_env("django", "distributed_tracing") self.assertIsNone(value) value = get_env("django", "distributed_tracing", default=False) self.assertFalse(value)
def get_trace_agent_timeout(): # type: () -> float return float( get_env("trace", "agent", "timeout", "seconds", default=DEFAULT_TIMEOUT)) # type: ignore[arg-type]
def update_patched_modules(): modules_to_patch = get_env("patch", "modules") if not modules_to_patch: return modules = parse_tags_str(modules_to_patch) for module, should_patch in modules.items(): EXTRA_PATCHED_MODULES[module] = asbool(should_patch)
def test_get_env_found_legacy(self): # ensure `get_env` returns a value if legacy environment variables # are used, raising a Deprecation warning with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") os.environ["DATADOG_REQUESTS_DISTRIBUTED_TRACING"] = "1" value = get_env("requests", "distributed_tracing") self.assertEqual(value, "1") self.assertEqual(len(w), 1) self.assertTrue(issubclass(w[-1].category, DeprecationWarning)) self.assertTrue("Use `DD_` prefix instead" in str(w[-1].message))
def get_stats_url(): # type: () -> str user_supplied_host = get_stats_hostname(None) is not None user_supplied_port = get_stats_port(None) is not None url = get_env("dogstatsd", "url", default=None) if not url: if user_supplied_host or user_supplied_port: url = "udp://{}:{}".format(get_stats_hostname(), get_stats_port()) elif os.path.exists("/var/run/datadog/dsd.socket"): url = "unix://%s" % (DEFAULT_UNIX_DSD_PATH) else: url = "udp://{}:{}".format(get_stats_hostname(), get_stats_port()) return url
def test_get_env_key_priority(self): # ensure `get_env` use `DD_` with highest priority os.environ["DD_REQUESTS_DISTRIBUTED_TRACING"] = "highest" os.environ["DATADOG_REQUESTS_DISTRIBUTED_TRACING"] = "lowest" value = get_env("requests", "distributed_tracing") self.assertEqual(value, "highest")
def test_get_env_found(self): # ensure `get_env` returns a value if the environment variable is set os.environ["DD_REQUESTS_DISTRIBUTED_TRACING"] = "1" value = get_env("requests", "distributed_tracing") self.assertEqual(value, "1")
def test_get_env_long(self): os.environ["DD_SOME_VERY_LONG_TEST_KEY"] = "1" value = get_env("some", "very", "long", "test", "key", default="2") assert value == "1"
def main(): parser = argparse.ArgumentParser( description=USAGE, prog="ddtrace-run", usage="ddtrace-run <your usual python command>", formatter_class=argparse.RawTextHelpFormatter, ) parser.add_argument("command", nargs=argparse.REMAINDER, type=str, help="Command string to execute.") parser.add_argument("-d", "--debug", help="enable debug mode (disabled by default)", action="store_true") parser.add_argument( "-i", "--info", help= ("print library info useful for debugging. Only reflects configurations made via environment " "variables, not those made in code."), action="store_true", ) parser.add_argument("-p", "--profiling", help="enable profiling (disabled by default)", action="store_true") parser.add_argument("-v", "--version", action="version", version="%(prog)s " + ddtrace.__version__) parser.add_argument("-nc", "--colorless", help="print output of command without color", action="store_true") args = parser.parse_args() if args.profiling: os.environ["DD_PROFILING_ENABLED"] = "true" debug_mode = args.debug or asbool(get_env("trace", "debug", default=False)) if debug_mode: logging.basicConfig(level=logging.DEBUG) os.environ["DD_TRACE_DEBUG"] = "true" if args.info: # Inline imports for performance. from ddtrace.internal.debug import pretty_collect print(pretty_collect(ddtrace.tracer, color=not args.colorless)) sys.exit(0) root_dir = os.path.dirname(ddtrace.__file__) log.debug("ddtrace root: %s", root_dir) bootstrap_dir = os.path.join(root_dir, "bootstrap") log.debug("ddtrace bootstrap: %s", bootstrap_dir) _add_bootstrap_to_pythonpath(bootstrap_dir) log.debug("PYTHONPATH: %s", os.environ["PYTHONPATH"]) log.debug("sys.path: %s", sys.path) if not args.command: parser.print_help() sys.exit(1) # Find the executable path executable = spawn.find_executable(args.command[0]) if not executable: print("ddtrace-run: failed to find executable '%s'.\n" % args.command[0]) parser.print_usage() sys.exit(1) log.debug("program executable: %s", executable) if os.path.basename(executable) == "uwsgi": print(( "ddtrace-run has known compatibility issues with uWSGI where the " "tracer is not started properly in uWSGI workers which can cause " "broken behavior. It is recommended you remove ddtrace-run and " "update your uWSGI configuration following " "https://ddtrace.readthedocs.io/en/stable/advanced_usage.html#uwsgi." )) try: os.execl(executable, executable, *args.command[1:]) except PermissionError: print("ddtrace-run: permission error while launching '%s'" % executable) print("Did you mean `ddtrace-run python %s`?" % executable) sys.exit(1) except Exception: print("ddtrace-run: error launching '%s'" % executable) raise sys.exit(0)
from ddtrace.internal.compat import maybe_stringify from ddtrace.internal.logger import get_logger from ddtrace.internal.utils.formats import asbool from ddtrace.internal.utils.formats import get_env from ddtrace.vendor import wrapt from . import utils from .. import trace_utils log = get_logger(__name__) config._add( "django", dict( _default_service="django", cache_service_name=get_env("django", "cache_service_name") or "django", database_service_name_prefix=get_env("django", "database_service_name_prefix", default=""), database_service_name=get_env("django", "database_service_name", default=""), trace_fetch_methods=asbool( get_env("django", "trace_fetch_methods", default=False)), distributed_tracing_enabled=True, instrument_middleware=asbool( get_env("django", "instrument_middleware", default=True)), instrument_databases=True, instrument_caches=True, analytics_enabled= None, # None allows the value to be overridden by the global config
modules_to_patch = get_env("patch", "modules") if not modules_to_patch: return modules = parse_tags_str(modules_to_patch) for module, should_patch in modules.items(): EXTRA_PATCHED_MODULES[module] = asbool(should_patch) try: from ddtrace import tracer # Respect DATADOG_* environment variables in global tracer configuration but add deprecation warning # correct prefix should be DD_* dd_hostname = get_env("trace", "agent", "hostname") hostname = os.environ.get("DD_AGENT_HOST", dd_hostname) port = get_env("trace", "agent", "port") priority_sampling = get_env("priority", "sampling") profiling = asbool(os.environ.get("DD_PROFILING_ENABLED", False)) if profiling: import ddtrace.profiling.auto # noqa: F401 if asbool(get_env("runtime_metrics", "enabled")): RuntimeWorker.enable() opts = {} # type: Dict[str, Any] dd_trace_enabled = get_env("trace", "enabled", default=True) if asbool(dd_trace_enabled):
from ddtrace import Pin from ddtrace import config from ddtrace.contrib.dbapi import TracedConnection from ddtrace.ext import db from ddtrace.ext import net from ddtrace.internal.utils.formats import asbool from ddtrace.internal.utils.formats import get_env from ddtrace.internal.utils.wrappers import unwrap from ddtrace.vendor import wrapt config._add( "mariadb", dict( trace_fetch_methods=asbool( get_env("mariadb", "trace_fetch_methods", default=False)), _default_service="mariadb", ), ) def patch(): if getattr(mariadb, "_datadog_patch", False): return setattr(mariadb, "_datadog_patch", True) wrapt.wrap_function_wrapper("mariadb", "connect", _connect) def unpatch(): if getattr(mariadb, "_datadog_patch", False): setattr(mariadb, "_datadog_patch", False)
def get_stats_port(default=DEFAULT_STATS_PORT): # type: (Union[T, int]) -> Union[T,int] v = get_env("dogstatsd", "port", default=None) if v is not None: return int(v) return default
from ddtrace.internal.utils.formats import asbool from ddtrace.internal.utils.formats import get_env from ddtrace.internal.utils.wrappers import unwrap as _u from ddtrace.pin import Pin from ddtrace.propagation.http import HTTPPropagator from ddtrace.vendor.wrapt import wrap_function_wrapper as _w if typing.TYPE_CHECKING: from ddtrace import Span from ddtrace.vendor.wrapt import BoundFunctionWrapper config._add( "httpx", { "distributed_tracing": asbool(get_env("httpx", "distributed_tracing", default=True)), "split_by_domain": asbool(get_env("httpx", "split_by_domain", default=False)), }, ) def _url_to_str(url): # type: (httpx.URL) -> str """ Helper to convert the httpx.URL parts from bytes to a str """ scheme, host, port, raw_path = url.raw url = scheme + b"://" + host if port is not None: url += b":" + ensure_binary(str(port))