Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions src/instana/options.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
get_disable_trace_configurations_from_env,
get_disable_trace_configurations_from_local,
get_disable_trace_configurations_from_yaml,
get_disable_w3c_sampled_flag_inheritance_from_yaml,
get_http_exit_classification_from_yaml,
get_stack_trace_config_from_yaml,
is_truthy,
Expand Down Expand Up @@ -68,6 +69,10 @@ def __init__(self, **kwds: dict[str, Any]) -> None:
# Disable injection of the Server-Timing response header (tracing.global.disable-server-timing)
self.disable_server_timing = False

# Ignore the sampled flag of the incoming W3C traceparent header
# (tracing.global.disable-w3c-sampled-flag-inheritance)
self.disable_w3c_sampled_flag_inheritance = False

# Technology-specific stack trace overrides
# Format: {"kafka": {"level": "all", "length": 25}, "redis": {"level": "error", "length": 20}}
self.stack_trace_technology_config = {}
Expand Down Expand Up @@ -133,6 +138,7 @@ def set_trace_configurations(self) -> None:
self.set_disable_trace_configurations()
self.set_stack_trace_configurations()
self.set_disable_server_timing_configuration()
self.set_disable_w3c_sampled_flag_inheritance_configuration()
self.set_span_filter_configurations()

def set_http_exit_classification_configurations(self) -> None:
Expand Down Expand Up @@ -319,6 +325,37 @@ def set_disable_server_timing_configuration(self) -> None:
elif "INSTANA_CONFIG_PATH" in os.environ:
self.disable_server_timing = get_disable_server_timing_from_yaml()

@staticmethod
def _has_env_disable_w3c_sampled_flag_inheritance() -> bool:
"""
Check whether the sampled flag inheritance env var is set.

An empty INSTANA_TRACING_DISABLE_W3C_SAMPLED_FLAG_INHERITANCE is treated as
unset, so it does not take precedence over the YAML file or agent config.

:return: True if the env var is set to a non-empty value.
"""
return bool(
os.environ.get("INSTANA_TRACING_DISABLE_W3C_SAMPLED_FLAG_INHERITANCE")
)

def set_disable_w3c_sampled_flag_inheritance_configuration(self) -> None:
"""
Set disable-w3c-sampled-flag-inheritance from the environment or YAML.

Precedence: INSTANA_TRACING_DISABLE_W3C_SAMPLED_FLAG_INHERITANCE >
INSTANA_CONFIG_PATH > agent config > default (False).
The agent config is handled in StandardOptions.set_tracing().
"""
if self._has_env_disable_w3c_sampled_flag_inheritance():
self.disable_w3c_sampled_flag_inheritance = is_truthy(
os.environ["INSTANA_TRACING_DISABLE_W3C_SAMPLED_FLAG_INHERITANCE"]
)
elif "INSTANA_CONFIG_PATH" in os.environ:
self.disable_w3c_sampled_flag_inheritance = (
get_disable_w3c_sampled_flag_inheritance_from_yaml()
)

def set_disable_trace_configurations(self) -> None:
disabled_spans = []
enabled_spans = []
Expand Down Expand Up @@ -489,6 +526,7 @@ def set_tracing(self, tracing: dict[str, Any]) -> None:
self.set_stack_trace_from_agent(tracing)

self._apply_agent_disable_server_timing(tracing)
self._apply_agent_disable_w3c_sampled_flag_inheritance(tracing)

# HTTP exit 4xx classification — only apply if env var didn't already set it
if "http" in tracing and not self._has_env_http_exit_classification():
Expand All @@ -510,6 +548,28 @@ def _apply_agent_disable_server_timing(self, tracing: dict[str, Any]) -> None:
global_config["disable-server-timing"]
)

def _apply_agent_disable_w3c_sampled_flag_inheritance(
self, tracing: dict[str, Any]
) -> None:
"""
Apply disable-w3c-sampled-flag-inheritance from the agent config.

This has the lowest priority: the environment variable and the YAML file
take precedence.

:param tracing: tracing configuration dictionary from the agent.
"""
global_config = tracing.get("global")
if (
not self._has_env_disable_w3c_sampled_flag_inheritance()
and "INSTANA_CONFIG_PATH" not in os.environ
and isinstance(global_config, dict)
and "disable-w3c-sampled-flag-inheritance" in global_config
):
self.disable_w3c_sampled_flag_inheritance = is_truthy(
global_config["disable-w3c-sampled-flag-inheritance"]
)

def _apply_agent_filter_config(self, filter_config: dict[str, Any]) -> None:
"""Apply span filter rules from agent config."""
parsed = parse_filter_rules(filter_config)
Expand Down
49 changes: 48 additions & 1 deletion src/instana/propagators/base_propagator.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,31 @@ def is_server_timing_disabled() -> bool:
logger.debug("is_server_timing_disabled error:", exc_info=True)
return False

@staticmethod
def is_w3c_sampled_flag_inheritance_disabled() -> bool:
"""
Check whether the incoming traceparent sampled flag is ignored.

Controlled by tracing.global.disable-w3c-sampled-flag-inheritance or
INSTANA_TRACING_DISABLE_W3C_SAMPLED_FLAG_INHERITANCE. Evaluated on every
call so runtime configuration changes are honoured.

:return: True if the flag is ignored; False (flag is inherited) otherwise,
including when the agent is unavailable.
"""
try:
# Imported here to avoid a circular import: instana.singletons
# imports the tracer, which imports the propagators.
from instana.singletons import get_agent

options = getattr(get_agent(), "options", None)
return bool(getattr(options, "disable_w3c_sampled_flag_inheritance", False))
except Exception:
logger.debug(
"is_w3c_sampled_flag_inheritance_disabled error:", exc_info=True
)
return False

@staticmethod
def extract_headers_dict(carrier: CarrierT) -> Optional[Dict]:
"""
Expand Down Expand Up @@ -182,8 +207,16 @@ def _get_participating_trace_context(self, span_context: SpanContext):
tp_trace_id = span_context.trace_id
traceparent = span_context.traceparent
tracestate = span_context.tracestate
parent_id = span_context.span_id
if span_context.suppression and traceparent:
# An incoming sampled=0 is propagated with its own parent-id, not a new one.
_, _, tp_parent_id, tp_sampled = self._tp.get_traceparent_fields(
traceparent
)
if tp_sampled is False:
parent_id = tp_parent_id
traceparent = self._tp.update_traceparent(
traceparent, tp_trace_id, span_context.span_id, span_context.level
traceparent, tp_trace_id, parent_id, span_context.level
)

# In suppression mode do not update the tracestate and
Expand All @@ -197,6 +230,9 @@ def _get_participating_trace_context(self, span_context: SpanContext):
hex_id_limited(span_context.trace_id),
hex_id(span_context.span_id),
)
if self.is_w3c_sampled_flag_inheritance_disabled():
# The incoming sampling decision (th) must not reach downstream tracers.
tracestate = self._ts.remove_ot_threshold(tracestate)
return traceparent, tracestate

def __determine_span_context(
Expand Down Expand Up @@ -246,6 +282,17 @@ def __determine_span_context(
) = [None] * 9

ctx_level = self._get_ctx_level(level)
if (
not level
and not disable_w3c_trace_context
and traceparent
and not self.is_w3c_sampled_flag_inheritance_disabled()
):
# Without X-INSTANA-L the traceparent sampled flag decides.
# X-INSTANA-T/S do not influence the level.
_, _, _, sampled = self._tp.get_traceparent_fields(traceparent)
if sampled is False:
ctx_level = 0
ctx_trace_id = trace_id if ctx_level > 0 else None
ctx_span_id = span_id if ctx_level > 0 else None

Expand Down
17 changes: 8 additions & 9 deletions src/instana/propagators/binary_propagator.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,20 +51,19 @@ def inject(
traceparent, tracestate = self._get_participating_trace_context(
span_context
)
try:
traceparent = str.encode(traceparent) # type: ignore[arg-type]
tracestate = str.encode(tracestate) # type: ignore[arg-type]
except Exception:
traceparent, tracestate = [None] * 2
traceparent = str.encode(traceparent) if traceparent else None # type: ignore[assignment]
tracestate = str.encode(tracestate) if tracestate else None # type: ignore[assignment]

headers = []
if traceparent and tracestate:
if traceparent:
headers.append((self.HEADER_KEY_TRACEPARENT, traceparent))
if tracestate:
headers.append((self.HEADER_KEY_TRACESTATE, tracestate))
headers.append((self.HEADER_KEY_T, trace_id))
headers.append((self.HEADER_KEY_S, span_id))
if not span_context.suppression:
headers.append((self.HEADER_KEY_T, trace_id))
headers.append((self.HEADER_KEY_S, span_id))
headers.append((self.HEADER_KEY_L, level))
if server_timing:
if server_timing and not span_context.suppression:
headers.append((self.HEADER_SERVER_TIMING, server_timing))

if isinstance(carrier, dict) or hasattr(carrier, "__dict__"):
Expand Down
12 changes: 6 additions & 6 deletions src/instana/propagators/text_propagator.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,12 @@ def inject(
else define_server_timing(span_context.trace_id).encode()
)

headers = [
(self.LC_HEADER_KEY_T, trace_id),
(self.LC_HEADER_KEY_S, span_id),
(self.LC_HEADER_KEY_L, "1"),
]
if server_timing:
headers = []
if not span_context.suppression:
headers.append((self.LC_HEADER_KEY_T, trace_id))
headers.append((self.LC_HEADER_KEY_S, span_id))
headers.append((self.LC_HEADER_KEY_L, str(span_context.level)))
if server_timing and not span_context.suppression:
headers.append((self.LC_HEADER_KEY_SERVER_TIMING, server_timing))

if isinstance(carrier, dict) or hasattr(carrier, "__dict__"):
Expand Down
22 changes: 22 additions & 0 deletions src/instana/util/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -604,6 +604,28 @@ def get_disable_server_timing_from_yaml() -> bool:
return is_truthy(global_config.get("disable-server-timing", False))


def get_disable_w3c_sampled_flag_inheritance_from_yaml() -> bool:
"""
Get tracing.global.disable-w3c-sampled-flag-inheritance from the YAML config.

The YAML file is specified by INSTANA_CONFIG_PATH.

Returns:
True if the incoming W3C traceparent sampled flag must be ignored, False otherwise (default)
"""
config_reader = ConfigReader(os.environ.get("INSTANA_CONFIG_PATH", ""))

root_key = get_tracing_root_key(config_reader.data)
if not root_key:
return False

global_config = (config_reader.data[root_key] or {}).get("global")
if not isinstance(global_config, dict):
return False

return is_truthy(global_config.get("disable-w3c-sampled-flag-inheritance", False))


def get_http_exit_classification_from_yaml() -> Tuple[bool, List[int]]:
"""
Get HTTP exit 4xx classification configuration from the YAML file specified
Expand Down
28 changes: 28 additions & 0 deletions src/instana/w3c_trace_context/tracestate.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,3 +89,31 @@ def update_tracestate(self, tracestate, in_trace_id, in_span_id):
)

return tracestate

@staticmethod
def remove_ot_threshold(tracestate: str) -> str:
"""
Remove the OpenTelemetry sampling threshold (th) from the ot list member.

Other sub-keys (e.g. rv) and all other list members are left untouched.
The ot list member is dropped if it has no sub-keys left.

:param tracestate: tracestate header
:return: tracestate without the th sub-key of the ot list member
"""
if "ot=" not in tracestate:
return tracestate

list_members = []
for member in tracestate.split(","):
if member.strip().startswith("ot="):
sub_keys = [
sub_key
for sub_key in member.strip()[len("ot=") :].split(";")
if sub_key and not sub_key.startswith("th:")
]
if not sub_keys:
continue
member = f"ot={';'.join(sub_keys)}"
list_members.append(member)
return ",".join(list_members)
75 changes: 75 additions & 0 deletions tests/frameworks/test_fastapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -855,3 +855,78 @@ def test_w3c_traceparent_upstream_context(self) -> None:
assert hex_id(asgi_span.p) == upstream_span_id_hex, (
f"Expected parent_id {upstream_span_id_hex}, got {hex_id(asgi_span.p)}"
)

def test_suppression_x_instana_l_0(self) -> None:
result = self.client.get("/", headers={"X-INSTANA-L": "0"})

assert result.status_code == 200
assert result.headers["X-INSTANA-L"] == "0"
assert "X-INSTANA-T" not in result.headers
assert "X-INSTANA-S" not in result.headers
assert "Server-Timing" not in result.headers

# Only the asgi span is asserted: FastAPI >= 0.115.0 emits OTel sdk spans
# through the global provider and their suppression is out of scope here.
spans = self.recorder.queued_spans()
assert not get_spans_by_filter(spans, lambda span: span.n == "asgi")

def test_suppression_x_instana_l_0_with_traceparent_without_tracestate(
self,
) -> None:
trace_id_hex = "4bf92f3577b34da6a3ce929d0e0e4736"
parent_id_hex = "00f067aa0ba902b7"
headers = {
"X-INSTANA-L": "0",
"traceparent": f"00-{trace_id_hex}-{parent_id_hex}-00",
}

result = self.client.get("/", headers=headers)

assert result.status_code == 200
assert result.headers["X-INSTANA-L"] == "0"
assert "X-INSTANA-T" not in result.headers
assert "X-INSTANA-S" not in result.headers
assert "Server-Timing" not in result.headers
assert "tracestate" not in result.headers
assert result.headers["traceparent"].startswith(f"00-{trace_id_hex}-")
assert result.headers["traceparent"].endswith("-00")

spans = self.recorder.queued_spans()
assert not get_spans_by_filter(spans, lambda span: span.n == "asgi")

def test_suppression_traceparent_sampled_flag_0_without_x_instana_l(self) -> None:
trace_id_hex = "4bf92f3577b34da6a3ce929d0e0e4736"
parent_id_hex = "00f067aa0ba902b7"
headers = {
"traceparent": f"00-{trace_id_hex}-{parent_id_hex}-00",
"X-INSTANA-T": "1234567890abcdef",
"X-INSTANA-S": "fedcba0987654321",
}

result = self.client.get("/", headers=headers)

assert result.status_code == 200
assert result.headers["X-INSTANA-L"] == "0"
assert "X-INSTANA-T" not in result.headers
assert "X-INSTANA-S" not in result.headers
assert "Server-Timing" not in result.headers
assert "tracestate" not in result.headers
assert result.headers["traceparent"] == f"00-{trace_id_hex}-{parent_id_hex}-00"

spans = self.recorder.queued_spans()
assert not get_spans_by_filter(spans, lambda span: span.n == "asgi")

def test_traceparent_sampled_flag_1_without_x_instana_l(self) -> None:
trace_id_hex = "4bf92f3577b34da6a3ce929d0e0e4736"
parent_id_hex = "00f067aa0ba902b7"
headers = {"traceparent": f"00-{trace_id_hex}-{parent_id_hex}-01"}

result = self.client.get("/", headers=headers)

assert result.status_code == 200
assert result.headers["traceparent"].startswith(f"00-{trace_id_hex}-")
assert result.headers["traceparent"].endswith("-01")
assert result.headers["tracestate"].startswith("in=")

spans = self.recorder.queued_spans()
assert get_spans_by_filter(spans, lambda span: span.n == "asgi")
Loading
Loading