-
Notifications
You must be signed in to change notification settings - Fork 798
AWS X-Ray Remote Sampler Part 2 - Add Rules Caching, Rules Matching Logic, Rate Limiter, and Sampling Targets Poller #3761
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
jj22ee
wants to merge
3
commits into
open-telemetry:main
Choose a base branch
from
jj22ee:xray-sampler-pr1
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+2,498
−54
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
79 changes: 79 additions & 0 deletions
79
...-sdk-extension-aws/src/opentelemetry/sdk/extension/aws/trace/sampler/_fallback_sampler.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,79 @@ | ||
# Copyright The OpenTelemetry Authors | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
|
||
# Includes work from: | ||
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
# SPDX-License-Identifier: Apache-2.0 | ||
|
||
from __future__ import annotations | ||
|
||
from typing import Sequence | ||
|
||
# pylint: disable=no-name-in-module | ||
from opentelemetry.context import Context | ||
from opentelemetry.sdk.extension.aws.trace.sampler._clock import _Clock | ||
from opentelemetry.sdk.extension.aws.trace.sampler._rate_limiting_sampler import ( | ||
_RateLimitingSampler, | ||
) | ||
from opentelemetry.sdk.trace.sampling import ( | ||
Decision, | ||
Sampler, | ||
SamplingResult, | ||
TraceIdRatioBased, | ||
) | ||
from opentelemetry.trace import Link, SpanKind | ||
from opentelemetry.trace.span import TraceState | ||
from opentelemetry.util.types import Attributes | ||
|
||
|
||
class _FallbackSampler(Sampler): | ||
def __init__(self, clock: _Clock): | ||
self.__rate_limiting_sampler = _RateLimitingSampler(1, clock) | ||
self.__fixed_rate_sampler = TraceIdRatioBased(0.05) | ||
|
||
def should_sample( | ||
self, | ||
parent_context: Context | None, | ||
trace_id: int, | ||
name: str, | ||
kind: SpanKind | None = None, | ||
attributes: Attributes | None = None, | ||
links: Sequence["Link"] | None = None, | ||
trace_state: TraceState | None = None, | ||
) -> "SamplingResult": | ||
sampling_result = self.__rate_limiting_sampler.should_sample( | ||
parent_context, | ||
trace_id, | ||
name, | ||
kind=kind, | ||
attributes=attributes, | ||
links=links, | ||
trace_state=trace_state, | ||
) | ||
if sampling_result.decision is not Decision.DROP: | ||
return sampling_result | ||
return self.__fixed_rate_sampler.should_sample( | ||
parent_context, | ||
trace_id, | ||
name, | ||
kind=kind, | ||
attributes=attributes, | ||
links=links, | ||
trace_state=trace_state, | ||
) | ||
|
||
# pylint: disable=no-self-use | ||
def get_description(self) -> str: | ||
description = "FallbackSampler{fallback sampling with sampling config of 1 req/sec and 5% of additional requests}" | ||
return description |
97 changes: 97 additions & 0 deletions
97
...telemetry-sdk-extension-aws/src/opentelemetry/sdk/extension/aws/trace/sampler/_matcher.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,97 @@ | ||
# Copyright The OpenTelemetry Authors | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
|
||
# Includes work from: | ||
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
# SPDX-License-Identifier: Apache-2.0 | ||
|
||
from __future__ import annotations | ||
|
||
import re | ||
|
||
from opentelemetry.semconv.resource import CloudPlatformValues | ||
from opentelemetry.util.types import Attributes, AttributeValue | ||
|
||
cloud_platform_mapping = { | ||
CloudPlatformValues.AWS_LAMBDA.value: "AWS::Lambda::Function", | ||
CloudPlatformValues.AWS_ELASTIC_BEANSTALK.value: "AWS::ElasticBeanstalk::Environment", | ||
CloudPlatformValues.AWS_EC2.value: "AWS::EC2::Instance", | ||
CloudPlatformValues.AWS_ECS.value: "AWS::ECS::Container", | ||
CloudPlatformValues.AWS_EKS.value: "AWS::EKS::Container", | ||
} | ||
|
||
|
||
class _Matcher: | ||
@staticmethod | ||
def wild_card_match( | ||
text: AttributeValue | None = None, pattern: str | None = None | ||
) -> bool: | ||
if pattern == "*": | ||
return True | ||
if not isinstance(text, str) or pattern is None: | ||
return False | ||
if len(pattern) == 0: | ||
return len(text) == 0 | ||
for char in pattern: | ||
if char in ("*", "?"): | ||
return ( | ||
re.fullmatch(_Matcher.to_regex_pattern(pattern), text) | ||
is not None | ||
) | ||
return pattern == text | ||
|
||
@staticmethod | ||
def to_regex_pattern(rule_pattern: str) -> str: | ||
token_start = -1 | ||
regex_pattern = "" | ||
for index, char in enumerate(rule_pattern): | ||
char = rule_pattern[index] | ||
if char in ("*", "?"): | ||
if token_start != -1: | ||
regex_pattern += re.escape(rule_pattern[token_start:index]) | ||
token_start = -1 | ||
if char == "*": | ||
regex_pattern += ".*" | ||
else: | ||
regex_pattern += "." | ||
else: | ||
if token_start == -1: | ||
token_start = index | ||
if token_start != -1: | ||
regex_pattern += re.escape(rule_pattern[token_start:]) | ||
return regex_pattern | ||
|
||
@staticmethod | ||
def attribute_match( | ||
attributes: Attributes | None = None, | ||
rule_attributes: dict[str, str] | None = None, | ||
) -> bool: | ||
if rule_attributes is None or len(rule_attributes) == 0: | ||
return True | ||
if ( | ||
attributes is None | ||
or len(attributes) == 0 | ||
or len(rule_attributes) > len(attributes) | ||
): | ||
return False | ||
|
||
matched_count = 0 | ||
for key, val in attributes.items(): | ||
text_to_match = val | ||
pattern = rule_attributes.get(key, None) | ||
if pattern is None: | ||
continue | ||
if _Matcher.wild_card_match(text_to_match, pattern): | ||
matched_count += 1 | ||
return matched_count == len(rule_attributes) |
69 changes: 69 additions & 0 deletions
69
...etry-sdk-extension-aws/src/opentelemetry/sdk/extension/aws/trace/sampler/_rate_limiter.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,69 @@ | ||
# Copyright The OpenTelemetry Authors | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
|
||
# Includes work from: | ||
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
# SPDX-License-Identifier: Apache-2.0 | ||
|
||
from decimal import Decimal | ||
from threading import Lock | ||
|
||
# pylint: disable=no-name-in-module | ||
from opentelemetry.sdk.extension.aws.trace.sampler._clock import _Clock | ||
|
||
|
||
class _RateLimiter: | ||
def __init__(self, max_balance_in_seconds: int, quota: int, clock: _Clock): | ||
# max_balance_in_seconds is usually 1 | ||
# pylint: disable=invalid-name | ||
self.MAX_BALANCE_MILLIS = Decimal(max_balance_in_seconds * 1000.0) | ||
self._clock = clock | ||
|
||
self._quota = Decimal(quota) | ||
self.__wallet_floor_millis = Decimal( | ||
self._clock.now().timestamp() * 1000.0 | ||
) | ||
# current "wallet_balance" would be ceiling - floor | ||
|
||
self.__lock = Lock() | ||
|
||
def try_spend(self, cost: float) -> bool: | ||
if self._quota == 0: | ||
return False | ||
|
||
quota_per_millis = self._quota / Decimal(1000.0) | ||
|
||
# assume divide by zero not possible | ||
cost_in_millis = Decimal(cost) / quota_per_millis | ||
|
||
with self.__lock: | ||
wallet_ceiling_millis = Decimal( | ||
self._clock.now().timestamp() * 1000.0 | ||
) | ||
current_balance_millis = ( | ||
wallet_ceiling_millis - self.__wallet_floor_millis | ||
) | ||
current_balance_millis = min( | ||
current_balance_millis, self.MAX_BALANCE_MILLIS | ||
) | ||
pending_remaining_balance_millis = ( | ||
current_balance_millis - cost_in_millis | ||
) | ||
if pending_remaining_balance_millis >= 0: | ||
self.__wallet_floor_millis = ( | ||
wallet_ceiling_millis - pending_remaining_balance_millis | ||
) | ||
return True | ||
# No changes to the wallet state | ||
return False |
64 changes: 64 additions & 0 deletions
64
...extension-aws/src/opentelemetry/sdk/extension/aws/trace/sampler/_rate_limiting_sampler.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,64 @@ | ||
# Copyright The OpenTelemetry Authors | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
|
||
# Includes work from: | ||
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
# SPDX-License-Identifier: Apache-2.0 | ||
|
||
from __future__ import annotations | ||
|
||
from typing import Sequence | ||
|
||
# pylint: disable=no-name-in-module | ||
from opentelemetry.context import Context | ||
from opentelemetry.sdk.extension.aws.trace.sampler._clock import _Clock | ||
from opentelemetry.sdk.extension.aws.trace.sampler._rate_limiter import ( | ||
_RateLimiter, | ||
) | ||
from opentelemetry.sdk.trace.sampling import Decision, Sampler, SamplingResult | ||
from opentelemetry.trace import Link, SpanKind | ||
from opentelemetry.trace.span import TraceState | ||
from opentelemetry.util.types import Attributes | ||
|
||
|
||
class _RateLimitingSampler(Sampler): | ||
def __init__(self, quota: int, clock: _Clock): | ||
self.__quota = quota | ||
self.__reservoir = _RateLimiter(1, quota, clock) | ||
|
||
def should_sample( | ||
self, | ||
parent_context: Context | None, | ||
trace_id: int, | ||
name: str, | ||
kind: SpanKind | None = None, | ||
attributes: Attributes | None = None, | ||
links: Sequence["Link"] | None = None, | ||
trace_state: TraceState | None = None, | ||
) -> "SamplingResult": | ||
if self.__reservoir.try_spend(1): | ||
return SamplingResult( | ||
decision=Decision.RECORD_AND_SAMPLE, | ||
attributes=attributes, | ||
trace_state=trace_state, | ||
) | ||
return SamplingResult( | ||
decision=Decision.DROP, | ||
attributes=attributes, | ||
trace_state=trace_state, | ||
) | ||
|
||
def get_description(self) -> str: | ||
description = f"RateLimitingSampler{{rate limiting sampling with sampling config of {self.__quota} req/sec and 0% of additional requests}}" | ||
return description |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
opentelemetry-sdk-extension-aws
is released on its own and it has its own changelog insdk-extension/opentelemetry-sdk-extension-aws