Skip to content

Commit e791bce

Browse files
authored
Merge branch 'main' into bump-semconv-1370
2 parents b898cfe + 31289bd commit e791bce

File tree

22 files changed

+1276
-6
lines changed

22 files changed

+1276
-6
lines changed

CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
1212
1313
## Unreleased
1414

15+
- Add experimental composite samplers
16+
([#4714](https://github.com/open-telemetry/opentelemetry-python/pull/4714))
1517
- Filter duplicate logs out of some internal `logger`'s logs on the export logs path that might otherwise endlessly log or cause a recursion depth exceeded issue in cases where logging itself results in an exception.
1618
([#4695](https://github.com/open-telemetry/opentelemetry-python/pull/4695)).
1719
- docs: linked the examples with their github source code location and added Prometheus example

docs/examples/auto-instrumentation/client.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414

15-
from sys import argv
15+
import sys
1616

1717
from requests import get
1818

@@ -31,16 +31,16 @@
3131
BatchSpanProcessor(ConsoleSpanExporter())
3232
)
3333

34-
35-
assert len(argv) == 2
34+
# Get parameter from command line argument or use default value "testing"
35+
param_value = sys.argv[1] if len(sys.argv) > 1 else "testing"
3636

3737
with tracer.start_as_current_span("client"):
3838
with tracer.start_as_current_span("client-server"):
3939
headers = {}
4040
inject(headers)
4141
requested = get(
4242
"http://localhost:8082/server_request",
43-
params={"param": argv[1]},
43+
params={"param": param_value},
4444
headers=headers,
4545
)
4646

Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
# Copyright The OpenTelemetry Authors
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
import json
16+
import os
17+
import subprocess
18+
import sys
19+
import unittest
20+
21+
22+
class TestMetrics(unittest.TestCase):
23+
def test_metrics(self):
24+
"""Test that metrics example produces expected values"""
25+
# Run the metrics example
26+
test_script = f"{os.path.dirname(os.path.realpath(__file__))}/../metrics_example.py"
27+
28+
result = subprocess.run(
29+
[sys.executable, test_script],
30+
capture_output=True,
31+
text=True,
32+
timeout=10,
33+
check=True,
34+
)
35+
36+
# Script should run successfully
37+
self.assertEqual(result.returncode, 0)
38+
39+
# Parse the JSON output
40+
output_data = json.loads(result.stdout)
41+
42+
# Get the metrics from the JSON structure
43+
metrics = output_data["resource_metrics"][0]["scope_metrics"][0][
44+
"metrics"
45+
]
46+
47+
# Create a lookup dict for easier testing
48+
metrics_by_name = {metric["name"]: metric for metric in metrics}
49+
50+
# Test Counter: should be 1 (called counter.add(1))
51+
counter_value = metrics_by_name["counter"]["data"]["data_points"][0][
52+
"value"
53+
]
54+
self.assertEqual(counter_value, 1, "Counter should have value 1")
55+
56+
# Test UpDownCounter: should be -4 (1 + (-5) = -4)
57+
updown_value = metrics_by_name["updown_counter"]["data"][
58+
"data_points"
59+
][0]["value"]
60+
self.assertEqual(
61+
updown_value, -4, "UpDownCounter should have value -4"
62+
)
63+
64+
# Test Histogram: should have count=1, sum=99.9
65+
histogram_data = metrics_by_name["histogram"]["data"]["data_points"][0]
66+
self.assertEqual(
67+
histogram_data["count"], 1, "Histogram should have count 1"
68+
)
69+
self.assertEqual(
70+
histogram_data["sum"], 99.9, "Histogram should have sum 99.9"
71+
)
72+
73+
# Test Gauge: should be 1 (last value set)
74+
gauge_value = metrics_by_name["gauge"]["data"]["data_points"][0][
75+
"value"
76+
]
77+
self.assertEqual(gauge_value, 1, "Gauge should have value 1")
78+
79+
# Test Observable Counter: should be 1 (from callback)
80+
obs_counter_value = metrics_by_name["observable_counter"]["data"][
81+
"data_points"
82+
][0]["value"]
83+
self.assertEqual(
84+
obs_counter_value, 1, "Observable counter should have value 1"
85+
)
86+
87+
# Test Observable UpDownCounter: should be -10 (from callback)
88+
obs_updown_value = metrics_by_name["observable_updown_counter"][
89+
"data"
90+
]["data_points"][0]["value"]
91+
self.assertEqual(
92+
obs_updown_value,
93+
-10,
94+
"Observable updown counter should have value -10",
95+
)
96+
97+
# Test Observable Gauge: should be 9 (from callback)
98+
obs_gauge_value = metrics_by_name["observable_gauge"]["data"][
99+
"data_points"
100+
][0]["value"]
101+
self.assertEqual(
102+
obs_gauge_value, 9, "Observable gauge should have value 9"
103+
)
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
# Copyright The OpenTelemetry Authors
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
# oltpcollector_example.py
16+
import os
17+
import subprocess
18+
import sys
19+
import unittest
20+
21+
22+
class TestOTLPCollector(unittest.TestCase):
23+
def test_otlpcollector(self):
24+
"""Test that OTLP collector example outputs 'Hello world!'"""
25+
dirpath = os.path.dirname(os.path.realpath(__file__))
26+
test_script = f"{dirpath}/../otlpcollector_example.py"
27+
28+
# Run the script with a short timeout since it will retry forever
29+
with subprocess.Popen(
30+
[sys.executable, test_script],
31+
stdout=subprocess.PIPE,
32+
stderr=subprocess.PIPE,
33+
text=True,
34+
) as process:
35+
# Wait 2 seconds then kill it (enough time to print "Hello world!")
36+
try:
37+
stdout, _ = process.communicate(timeout=2)
38+
except subprocess.TimeoutExpired:
39+
process.kill()
40+
stdout, _ = process.communicate()
41+
42+
# Check that it printed the expected message
43+
self.assertIn("Hello world!", stdout)
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# Copyright The OpenTelemetry Authors
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
__all__ = [
16+
"ComposableSampler",
17+
"SamplingIntent",
18+
"composable_always_off",
19+
"composable_always_on",
20+
"composable_parent_threshold",
21+
"composable_traceid_ratio_based",
22+
"composite_sampler",
23+
]
24+
25+
26+
from ._always_off import composable_always_off
27+
from ._always_on import composable_always_on
28+
from ._composable import ComposableSampler, SamplingIntent
29+
from ._parent_threshold import composable_parent_threshold
30+
from ._sampler import composite_sampler
31+
from ._traceid_ratio import composable_traceid_ratio_based
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
# Copyright The OpenTelemetry Authors
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
from __future__ import annotations
16+
17+
from typing import Sequence
18+
19+
from opentelemetry.context import Context
20+
from opentelemetry.trace import Link, SpanKind, TraceState
21+
from opentelemetry.util.types import Attributes
22+
23+
from ._composable import ComposableSampler, SamplingIntent
24+
from ._util import INVALID_THRESHOLD
25+
26+
_intent = SamplingIntent(threshold=INVALID_THRESHOLD, threshold_reliable=False)
27+
28+
29+
class _ComposableAlwaysOffSampler(ComposableSampler):
30+
def sampling_intent(
31+
self,
32+
parent_ctx: Context | None,
33+
name: str,
34+
span_kind: SpanKind | None,
35+
attributes: Attributes,
36+
links: Sequence[Link] | None,
37+
trace_state: TraceState | None = None,
38+
) -> SamplingIntent:
39+
return _intent
40+
41+
def get_description(self) -> str:
42+
return "ComposableAlwaysOff"
43+
44+
45+
_always_off = _ComposableAlwaysOffSampler()
46+
47+
48+
def composable_always_off() -> ComposableSampler:
49+
"""Returns a composable sampler that does not sample any span.
50+
51+
- Always returns a SamplingIntent with no threshold, indicating all spans should be dropped
52+
- Sets threshold_reliable to false
53+
- Does not add any attributes
54+
"""
55+
return _always_off
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
# Copyright The OpenTelemetry Authors
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
from __future__ import annotations
16+
17+
from typing import Sequence
18+
19+
from opentelemetry.context import Context
20+
from opentelemetry.trace import Link, SpanKind, TraceState
21+
from opentelemetry.util.types import Attributes
22+
23+
from ._composable import ComposableSampler, SamplingIntent
24+
from ._util import MIN_THRESHOLD
25+
26+
_intent = SamplingIntent(threshold=MIN_THRESHOLD)
27+
28+
29+
class _ComposableAlwaysOnSampler(ComposableSampler):
30+
def sampling_intent(
31+
self,
32+
parent_ctx: Context | None,
33+
name: str,
34+
span_kind: SpanKind | None,
35+
attributes: Attributes,
36+
links: Sequence[Link] | None,
37+
trace_state: TraceState | None = None,
38+
) -> SamplingIntent:
39+
return _intent
40+
41+
def get_description(self) -> str:
42+
return "ComposableAlwaysOn"
43+
44+
45+
_always_on = _ComposableAlwaysOnSampler()
46+
47+
48+
def composable_always_on() -> ComposableSampler:
49+
"""Returns a composable sampler that samples all spans.
50+
51+
- Always returns a SamplingIntent with threshold set to sample all spans (threshold = 0)
52+
- Sets threshold_reliable to true
53+
- Does not add any attributes
54+
"""
55+
return _always_on
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
# Copyright The OpenTelemetry Authors
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
from __future__ import annotations
16+
17+
from dataclasses import dataclass, field
18+
from typing import Callable, Protocol, Sequence
19+
20+
from opentelemetry.context import Context
21+
from opentelemetry.trace import Link, SpanKind, TraceState
22+
from opentelemetry.util.types import Attributes
23+
24+
25+
@dataclass(frozen=True)
26+
class SamplingIntent:
27+
"""Information to make a consistent sampling decision."""
28+
29+
threshold: int
30+
"""The sampling threshold value. A lower threshold increases the likelihood of sampling."""
31+
32+
threshold_reliable: bool = field(default=True)
33+
"""Indicates whether the threshold is reliable for Span-to-Metrics estimation."""
34+
35+
attributes: Attributes = field(default=None)
36+
"""Any attributes to be added to a sampled span."""
37+
38+
update_trace_state: Callable[[TraceState], TraceState] = field(
39+
default=lambda ts: ts
40+
)
41+
"""Any updates to be made to trace state."""
42+
43+
44+
class ComposableSampler(Protocol):
45+
"""A sampler that can be composed to make a final sampling decision."""
46+
47+
def sampling_intent(
48+
self,
49+
parent_ctx: Context | None,
50+
name: str,
51+
span_kind: SpanKind | None,
52+
attributes: Attributes,
53+
links: Sequence[Link] | None,
54+
trace_state: TraceState | None,
55+
) -> SamplingIntent:
56+
"""Returns information to make a sampling decision."""
57+
... # pylint: disable=unnecessary-ellipsis
58+
59+
def get_description(self) -> str:
60+
"""Returns a description of the sampler."""
61+
... # pylint: disable=unnecessary-ellipsis

0 commit comments

Comments
 (0)