opentelemetry-sampler-xray 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: a8f34d06fd34d3038149a9462867dc8a0da80a157b1ac6c2368dba99e5de4394
4
+ data.tar.gz: 7435b426cc703f56ee38ec63039835eec6ddf49d11979023c94b933cbea86aa9
5
+ SHA512:
6
+ metadata.gz: 670607e4d777d4b65e9f3b2bea16e40c1986a0b8fa0e8eb6275b11bbcf5537e9ef5ffd0bb8bc89119954c7f3e7ba8dc24c4c7836c9ba2aee51a2e6801af3dd15
7
+ data.tar.gz: 3071093a01e82e52a9a42743228f54438526c3a669ee6f1bf850cad9d22583642f3d51c872ab326a679265e703563907e9692cdfbaaaa8658561aa713584b493
data/.yardopts ADDED
@@ -0,0 +1,9 @@
1
+ --no-private
2
+ --title=OpenTelemetry Sampler XRay
3
+ --markup=markdown
4
+ --main=README.md
5
+ ./lib/opentelemetry/sampler/xray/**/*.rb
6
+ ./lib/opentelemetry/sampler/xray.rb
7
+ -
8
+ README.md
9
+ CHANGELOG.md
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ # Release History: opentelemetry-sampler-xray
2
+
3
+ ### v0.1.0 / 2025-10-11
4
+
5
+ Initial release.
data/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright OpenTelemetry Authors
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
data/README.md ADDED
@@ -0,0 +1,54 @@
1
+ # opentelemetry-sampler-xray
2
+
3
+ The `opentelemetry-sampler-xray` gem contains the AWS X-Ray Remote Sampler for OpenTelemetry.
4
+
5
+ ## What is OpenTelemetry?
6
+
7
+ [OpenTelemetry][opentelemetry-home] is an open source observability framework, providing a general-purpose API, SDK, and related tools required for the instrumentation of cloud-native software, frameworks, and libraries.
8
+
9
+ OpenTelemetry provides a single set of APIs, libraries, agents, and collector services to capture distributed traces and metrics from your application. You can analyze them using Prometheus, Jaeger, and other observability tools.
10
+
11
+ ## How does this gem fit in?
12
+
13
+ This gem can be used with any OpenTelemetry SDK implementation. This can be the official `opentelemetry-sdk` gem or any other concrete implementation.
14
+
15
+ ## How do I get started?
16
+
17
+ Install the gem using:
18
+
19
+ ```console
20
+ gem install opentelemetry-sampler-xray
21
+ ```
22
+
23
+ Or, if you use [bundler][bundler-home], include `opentelemetry-sampler-xray` in your `Gemfile`.
24
+
25
+ In your application:
26
+
27
+ ```ruby
28
+ OpenTelemetry.tracer_provider.sampler = OpenTelemetry::Sampler::XRay::AwsXRayRemoteSampler.new(
29
+ polling_interval: 300, resource: OpenTelemetry::SDK::Resources::Resource.create({
30
+ "service.name"=>"my-service-name",
31
+ "cloud.platform"=>"aws_ec2"
32
+ })
33
+ )
34
+ ```
35
+
36
+ ## How can I get involved?
37
+
38
+ The `opentelemetry-sampler-xray` gem source is [on github][repo-github], along with related gems including `opentelemetry-api` and `opentelemetry-sdk`.
39
+
40
+ The OpenTelemetry Ruby gems are maintained by the OpenTelemetry Ruby special interest group (SIG). You can get involved by joining us on our [GitHub Discussions][discussions-url], [Slack Channel][slack-channel] or attending our weekly meeting. See the [meeting calendar][community-meetings] for dates and times. For more information on this and other language SIGs, see the OpenTelemetry [community page][ruby-sig].
41
+
42
+ ## License
43
+
44
+ The `opentelemetry-sampler-xray` gem is distributed under the Apache 2.0 license. See [LICENSE][license-github] for more information.
45
+
46
+ [opentelemetry-home]: https://opentelemetry.io
47
+ [bundler-home]: https://bundler.io
48
+ [repo-github]: https://github.com/open-telemetry/opentelemetry-ruby
49
+ [license-github]: https://github.com/open-telemetry/opentelemetry-ruby-contrib/blob/main/LICENSE
50
+ [ruby-sig]: https://github.com/open-telemetry/community#ruby-sig
51
+ [community-meetings]: https://github.com/open-telemetry/community#community-meetings
52
+ [slack-channel]: https://cloud-native.slack.com/archives/C01NWKKMKMY
53
+ [discussions-url]: https://github.com/open-telemetry/opentelemetry-ruby/discussions
54
+ [aws-xray]: https://docs.aws.amazon.com/xray/latest/devguide/aws-xray.html
@@ -0,0 +1,201 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Copyright OpenTelemetry Authors
4
+ #
5
+ # SPDX-License-Identifier: Apache-2.0
6
+
7
+ require 'json'
8
+ require 'opentelemetry/sdk'
9
+ require_relative 'aws_xray_sampling_client'
10
+ require_relative 'fallback_sampler'
11
+ require_relative 'rule_cache'
12
+ require_relative 'sampling_rule'
13
+ require_relative 'sampling_rule_applier'
14
+
15
+ module OpenTelemetry
16
+ module Sampler
17
+ module XRay
18
+ # Constants
19
+ DEFAULT_RULES_POLLING_INTERVAL_SECONDS = 5 * 60
20
+ DEFAULT_TARGET_POLLING_INTERVAL_SECONDS = 10
21
+ DEFAULT_AWS_PROXY_ENDPOINT = 'http://localhost:2000'
22
+
23
+ # AWSXRayRemoteSampler is a Wrapper class to ensure that all XRay Sampler Functionality
24
+ # in InternalAWSXRayRemoteSampler uses ParentBased logic to respect the parent span's sampling decision
25
+ class AWSXRayRemoteSampler
26
+ def initialize(endpoint: '127.0.0.1:2000', polling_interval: DEFAULT_RULES_POLLING_INTERVAL_SECONDS, resource: OpenTelemetry::SDK::Resources::Resource.create)
27
+ @root = OpenTelemetry::SDK::Trace::Samplers.parent_based(
28
+ root: OpenTelemetry::Sampler::XRay::InternalAWSXRayRemoteSampler.new(endpoint: endpoint, polling_interval: polling_interval, resource: resource)
29
+ )
30
+ end
31
+
32
+ def should_sample?(trace_id:, parent_context:, links:, name:, kind:, attributes:)
33
+ @root.should_sample?(
34
+ trace_id: trace_id, parent_context: parent_context, links: links, name: name, kind: kind, attributes: attributes
35
+ )
36
+ end
37
+
38
+ def description
39
+ "AWSXRayRemoteSampler{root=#{@root.description}}"
40
+ end
41
+ end
42
+
43
+ # InternalAWSXRayRemoteSampler contains all core XRay Sampler Functionality,
44
+ # however it is NOT Parent-based (e.g. Sample logic runs for each span)
45
+ class InternalAWSXRayRemoteSampler
46
+ def initialize(endpoint: '127.0.0.1:2000', polling_interval: DEFAULT_RULES_POLLING_INTERVAL_SECONDS, resource: OpenTelemetry::SDK::Resources::Resource.create)
47
+ if polling_interval.nil? || polling_interval < 10
48
+ OpenTelemetry.logger.warn(
49
+ "'polling_interval' is undefined or too small. Defaulting to #{DEFAULT_RULES_POLLING_INTERVAL_SECONDS} seconds"
50
+ )
51
+ @rule_polling_interval_millis = DEFAULT_RULES_POLLING_INTERVAL_SECONDS * 1000
52
+ else
53
+ @rule_polling_interval_millis = polling_interval * 1000
54
+ end
55
+
56
+ @rule_polling_jitter_millis = rand * 5 * 1000
57
+ @target_polling_interval = DEFAULT_TARGET_POLLING_INTERVAL_SECONDS
58
+ @target_polling_jitter_millis = (rand / 10) * 1000
59
+
60
+ @aws_proxy_endpoint = endpoint || DEFAULT_AWS_PROXY_ENDPOINT
61
+ @fallback_sampler = OpenTelemetry::Sampler::XRay::FallbackSampler.new
62
+ @client_id = self.class.generate_client_id
63
+ @rule_cache = OpenTelemetry::Sampler::XRay::RuleCache.new(resource)
64
+
65
+ @sampling_client = OpenTelemetry::Sampler::XRay::AWSXRaySamplingClient.new(@aws_proxy_endpoint)
66
+
67
+ # Start the Sampling Rules poller
68
+ start_sampling_rules_poller
69
+
70
+ # Start the Sampling Targets poller
71
+ start_sampling_targets_poller
72
+ end
73
+
74
+ def should_sample?(trace_id:, parent_context:, links:, name:, kind:, attributes:)
75
+ if @rule_cache.expired?
76
+ OpenTelemetry.logger.debug('Rule cache is expired, so using fallback sampling strategy')
77
+ return @fallback_sampler.should_sample?(
78
+ trace_id: trace_id, parent_context: parent_context, links: links, name: name, kind: kind, attributes: attributes
79
+ )
80
+ end
81
+
82
+ matched_rule = @rule_cache.get_matched_rule(attributes)
83
+ if matched_rule
84
+ return matched_rule.should_sample?(
85
+ trace_id: trace_id, parent_context: parent_context, links: links, name: name, kind: kind, attributes: attributes
86
+ )
87
+ end
88
+
89
+ OpenTelemetry.logger.debug(
90
+ 'Using fallback sampler as no rule match was found. This is likely due to a bug, since default rule should always match'
91
+ )
92
+ @fallback_sampler.should_sample?(
93
+ trace_id: trace_id, parent_context: parent_context, links: links, name: name, kind: kind, attributes: attributes
94
+ )
95
+ end
96
+
97
+ def description
98
+ "InternalAWSXRayRemoteSampler{aws_proxy_endpoint=#{@aws_proxy_endpoint}, rule_polling_interval_millis=#{@rule_polling_interval_millis}}"
99
+ end
100
+
101
+ private
102
+
103
+ def start_sampling_rules_poller
104
+ # Execute first update
105
+ retrieve_and_update_sampling_rules
106
+
107
+ # Update sampling rules periodically
108
+ @rule_poller = Thread.new do
109
+ loop do
110
+ sleep((@rule_polling_interval_millis + @rule_polling_jitter_millis) / 1000.0)
111
+ retrieve_and_update_sampling_rules
112
+ end
113
+ end
114
+ end
115
+
116
+ def start_sampling_targets_poller
117
+ @target_poller = Thread.new do
118
+ loop do
119
+ sleep(((@target_polling_interval * 1000) + @target_polling_jitter_millis) / 1000.0)
120
+ retrieve_and_update_sampling_targets
121
+ end
122
+ end
123
+ end
124
+
125
+ def retrieve_and_update_sampling_rules
126
+ sampling_rules_response = @sampling_client.fetch_sampling_rules
127
+ if sampling_rules_response&.body && sampling_rules_response.body != ''
128
+ rules = JSON.parse(sampling_rules_response.body)
129
+ update_sampling_rules(rules)
130
+ else
131
+ OpenTelemetry.logger.error('GetSamplingRules Response is falsy')
132
+ end
133
+ rescue StandardError => e
134
+ OpenTelemetry.handle_error(exception: e, message: 'Error occurred when retrieving or updating Sampling Rules')
135
+ end
136
+
137
+ def retrieve_and_update_sampling_targets
138
+ request_body = {
139
+ SamplingStatisticsDocuments: @rule_cache.create_sampling_statistics_documents(@client_id)
140
+ }
141
+ sampling_targets_response = @sampling_client.fetch_sampling_targets(request_body)
142
+ if sampling_targets_response&.body && sampling_targets_response.body != ''
143
+ response_body = JSON.parse(sampling_targets_response.body)
144
+ update_sampling_targets(response_body)
145
+ else
146
+ OpenTelemetry.logger.debug('SamplingTargets Response is falsy')
147
+ end
148
+ end
149
+
150
+ def update_sampling_rules(response_object)
151
+ sampling_rules = []
152
+ if response_object && response_object['SamplingRuleRecords']
153
+ response_object['SamplingRuleRecords'].each do |record|
154
+ if record['SamplingRule']
155
+ sampling_rule = OpenTelemetry::Sampler::XRay::SamplingRule.new(record['SamplingRule'])
156
+ sampling_rules << SamplingRuleApplier.new(sampling_rule)
157
+ end
158
+ end
159
+ @rule_cache.update_rules(sampling_rules)
160
+ else
161
+ OpenTelemetry.logger.error('SamplingRuleRecords from GetSamplingRules request is not defined')
162
+ end
163
+ end
164
+
165
+ def update_sampling_targets(response_object)
166
+ if response_object && response_object['SamplingTargetDocuments']
167
+ target_documents = {}
168
+
169
+ response_object['SamplingTargetDocuments'].each do |new_target|
170
+ target_documents[new_target['RuleName']] = new_target
171
+ end
172
+
173
+ refresh_sampling_rules, next_polling_interval = @rule_cache.update_targets(
174
+ target_documents,
175
+ response_object['LastRuleModification']
176
+ )
177
+
178
+ @target_polling_interval = next_polling_interval
179
+
180
+ if refresh_sampling_rules
181
+ OpenTelemetry.logger.debug('Performing out-of-band sampling rule polling to fetch updated rules.')
182
+ @rule_poller&.kill
183
+ start_sampling_rules_poller
184
+ end
185
+ else
186
+ OpenTelemetry.logger.debug('SamplingTargetDocuments from SamplingTargets request is not defined')
187
+ end
188
+ rescue StandardError => e
189
+ OpenTelemetry.logger.debug("Error occurred when updating Sampling Targets: #{e}")
190
+ end
191
+
192
+ class << self
193
+ def generate_client_id
194
+ hex_chars = ('0'..'9').to_a + ('a'..'f').to_a
195
+ Array.new(24) { hex_chars.sample }.join
196
+ end
197
+ end
198
+ end
199
+ end
200
+ end
201
+ end
@@ -0,0 +1,60 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Copyright OpenTelemetry Authors
4
+ #
5
+ # SPDX-License-Identifier: Apache-2.0
6
+
7
+ require 'net/http'
8
+ require 'json'
9
+ require 'uri'
10
+
11
+ module OpenTelemetry
12
+ module Sampler
13
+ module XRay
14
+ # AWSXRaySamplingClient is responsible for making '/GetSamplingRules' and '/SamplingTargets' calls
15
+ # to AWS X-Ray to retrieve Sampling Rules and Sampling Targets respectively
16
+ class AWSXRaySamplingClient
17
+ def initialize(endpoint)
18
+ @endpoint = endpoint
19
+ @host, @port = parse_endpoint(@endpoint)
20
+
21
+ @sampling_rules_url = URI::HTTP.build(host: @host, path: '/GetSamplingRules', port: @port)
22
+ @sampling_targets_url = URI::HTTP.build(host: @host, path: '/SamplingTargets', port: @port)
23
+ @request_headers = { 'content-type': 'application/json' }
24
+ end
25
+
26
+ def fetch_sampling_rules
27
+ begin
28
+ OpenTelemetry::Common::Utilities.untraced do
29
+ return Net::HTTP.post(@sampling_rules_url, '{}', @request_headers)
30
+ end
31
+ rescue StandardError => e
32
+ OpenTelemetry.logger.debug("Error occurred when fetching Sampling Rules: #{e}")
33
+ end
34
+ nil
35
+ end
36
+
37
+ def fetch_sampling_targets(request_body)
38
+ begin
39
+ OpenTelemetry::Common::Utilities.untraced do
40
+ return Net::HTTP.post(@sampling_targets_url, request_body.to_json, @request_headers)
41
+ end
42
+ rescue StandardError => e
43
+ OpenTelemetry.logger.debug("Error occurred when fetching Sampling Targets: #{e}")
44
+ end
45
+ nil
46
+ end
47
+
48
+ private
49
+
50
+ def parse_endpoint(endpoint)
51
+ host, port = endpoint.split(':')
52
+ [host, port.to_i]
53
+ rescue StandardError => e
54
+ OpenTelemetry.handle_error(exception: e, message: "Invalid endpoint: #{endpoint}")
55
+ raise e
56
+ end
57
+ end
58
+ end
59
+ end
60
+ end
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Copyright OpenTelemetry Authors
4
+ #
5
+ # SPDX-License-Identifier: Apache-2.0
6
+
7
+ require_relative 'rate_limiting_sampler'
8
+
9
+ module OpenTelemetry
10
+ module Sampler
11
+ module XRay
12
+ # FallbackSampler samples 1 req/sec and additional 5% of requests using TraceIdRatioBasedSampler.
13
+ class FallbackSampler
14
+ def initialize
15
+ @fixed_rate_sampler = OpenTelemetry::SDK::Trace::Samplers::TraceIdRatioBased.new(0.05)
16
+ @rate_limiting_sampler = RateLimitingSampler.new(1)
17
+ end
18
+
19
+ def should_sample?(trace_id:, parent_context:, links:, name:, kind:, attributes:)
20
+ sampling_result = @rate_limiting_sampler.should_sample?(
21
+ trace_id: trace_id, parent_context: parent_context, links: links, name: name, kind: kind, attributes: attributes
22
+ )
23
+
24
+ return sampling_result if sampling_result.instance_variable_get(:@decision) != OpenTelemetry::SDK::Trace::Samplers::Decision::DROP
25
+
26
+ @fixed_rate_sampler.should_sample?(trace_id: trace_id, parent_context: parent_context, links: links, name: name, kind: kind, attributes: attributes)
27
+ end
28
+
29
+ def description
30
+ 'FallbackSampler{fallback sampling with sampling config of 1 req/sec and 5% of additional requests}'
31
+ end
32
+ end
33
+ end
34
+ end
35
+ end
@@ -0,0 +1,48 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Copyright OpenTelemetry Authors
4
+ #
5
+ # SPDX-License-Identifier: Apache-2.0
6
+
7
+ module OpenTelemetry
8
+ module Sampler
9
+ module XRay
10
+ # RateLimiter keeps track of the current reservoir quota balance available (measured via available time)
11
+ # If enough time has elapsed, the RateLimiter will allow quota balance to be consumed/taken (decrease available time)
12
+ # A RateLimitingSampler uses this RateLimiter to determine if it should sample or not based on the quota balance available.
13
+ class RateLimiter
14
+ def initialize(quota, max_balance_in_seconds = 1)
15
+ @max_balance_millis = max_balance_in_seconds * 1000.0
16
+ @quota = quota
17
+ @wallet_floor_millis = Time.now.to_f * 1000
18
+ # current "balance" would be `ceiling - floor`
19
+ @lock = Mutex.new
20
+ end
21
+
22
+ def take(cost = 1)
23
+ return false if @quota <= 0
24
+
25
+ quota_per_millis = @quota / 1000.0
26
+
27
+ # assume divide by zero not possible
28
+ cost_in_millis = cost / quota_per_millis
29
+
30
+ @lock.synchronize do
31
+ wallet_ceiling_millis = Time.now.to_f * 1000
32
+ current_balance_millis = wallet_ceiling_millis - @wallet_floor_millis
33
+ current_balance_millis = [current_balance_millis, @max_balance_millis].min
34
+ pending_remaining_balance_millis = current_balance_millis - cost_in_millis
35
+
36
+ if pending_remaining_balance_millis >= 0
37
+ @wallet_floor_millis = wallet_ceiling_millis - pending_remaining_balance_millis
38
+ return true
39
+ end
40
+
41
+ # No changes to the wallet state
42
+ false
43
+ end
44
+ end
45
+ end
46
+ end
47
+ end
48
+ end
@@ -0,0 +1,43 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Copyright OpenTelemetry Authors
4
+ #
5
+ # SPDX-License-Identifier: Apache-2.0
6
+
7
+ require_relative 'rate_limiter'
8
+
9
+ module OpenTelemetry
10
+ module Sampler
11
+ module XRay
12
+ # RateLimitingSampler is a Sampler that uses a RateLimiter to determine
13
+ # if it should sample or not based on the quota balance available.
14
+ class RateLimitingSampler
15
+ def initialize(quota)
16
+ @quota = quota
17
+ @reservoir = RateLimiter.new(quota)
18
+ end
19
+
20
+ def should_sample?(trace_id:, parent_context:, links:, name:, kind:, attributes:)
21
+ tracestate = OpenTelemetry::Trace.current_span(parent_context).context.tracestate
22
+ if @reservoir.take(1)
23
+ OpenTelemetry::SDK::Trace::Samplers::Result.new(
24
+ decision: OpenTelemetry::SDK::Trace::Samplers::Decision::RECORD_AND_SAMPLE,
25
+ tracestate: tracestate,
26
+ attributes: attributes
27
+ )
28
+ else
29
+ OpenTelemetry::SDK::Trace::Samplers::Result.new(
30
+ decision: OpenTelemetry::SDK::Trace::Samplers::Decision::DROP,
31
+ tracestate: tracestate,
32
+ attributes: attributes
33
+ )
34
+ end
35
+ end
36
+
37
+ def to_s
38
+ "RateLimitingSampler{rate limiting sampling with sampling config of #{@quota} req/sec and 0% of additional requests}"
39
+ end
40
+ end
41
+ end
42
+ end
43
+ end
@@ -0,0 +1,116 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Copyright OpenTelemetry Authors
4
+ #
5
+ # SPDX-License-Identifier: Apache-2.0
6
+
7
+ module OpenTelemetry
8
+ module Sampler
9
+ module XRay
10
+ # RuleCache stores all the Sampling Rule Appliers, each corresponding
11
+ # to the user's Sampling Rules that were retrieved from AWS X-Ray
12
+ class RuleCache
13
+ # The cache expires 1 hour after the last refresh time.
14
+ RULE_CACHE_TTL_MILLIS = 60 * 60 * 1000
15
+
16
+ def initialize(sampler_resource)
17
+ @rule_appliers = []
18
+ @sampler_resource = sampler_resource
19
+ @last_updated_epoch_millis = Time.now.to_i * 1000
20
+ @cache_lock = Mutex.new
21
+ end
22
+
23
+ def expired?
24
+ now_in_millis = Time.now.to_i * 1000
25
+ now_in_millis > @last_updated_epoch_millis + RULE_CACHE_TTL_MILLIS
26
+ end
27
+
28
+ def get_matched_rule(attributes)
29
+ @rule_appliers.find do |rule|
30
+ rule.matches?(attributes, @sampler_resource) || rule.sampling_rule.rule_name == 'Default'
31
+ end
32
+ end
33
+
34
+ def update_rules(new_rule_appliers)
35
+ old_rule_appliers_map = {}
36
+
37
+ @cache_lock.synchronize do
38
+ @rule_appliers.each do |rule|
39
+ old_rule_appliers_map[rule.sampling_rule.rule_name] = rule
40
+ end
41
+
42
+ new_rule_appliers.each_with_index do |new_rule, index|
43
+ rule_name_to_check = new_rule.sampling_rule.rule_name
44
+ next unless old_rule_appliers_map.key?(rule_name_to_check)
45
+
46
+ old_rule = old_rule_appliers_map[rule_name_to_check]
47
+ new_rule_appliers[index] = old_rule if new_rule.sampling_rule.equals?(old_rule.sampling_rule)
48
+ end
49
+
50
+ @rule_appliers = new_rule_appliers
51
+ sort_rules_by_priority
52
+ @last_updated_epoch_millis = Time.now.to_i * 1000
53
+ end
54
+ end
55
+
56
+ def create_sampling_statistics_documents(client_id)
57
+ statistics_documents = []
58
+
59
+ @cache_lock.synchronize do
60
+ @rule_appliers.each do |rule|
61
+ statistics = rule.snapshot_statistics
62
+ now_in_seconds = Time.now.to_i
63
+
64
+ sampling_statistics_doc = {
65
+ ClientID: client_id,
66
+ RuleName: rule.sampling_rule.rule_name,
67
+ Timestamp: now_in_seconds,
68
+ RequestCount: statistics.request_count,
69
+ BorrowCount: statistics.borrow_count,
70
+ SampledCount: statistics.sample_count
71
+ }
72
+
73
+ statistics_documents << sampling_statistics_doc
74
+ end
75
+ end
76
+
77
+ statistics_documents
78
+ end
79
+
80
+ def update_targets(target_documents, last_rule_modification)
81
+ min_polling_interval = nil
82
+ next_polling_interval = DEFAULT_TARGET_POLLING_INTERVAL_SECONDS
83
+
84
+ @cache_lock.synchronize do
85
+ @rule_appliers.each_with_index do |rule, index|
86
+ target = target_documents[rule.sampling_rule.rule_name]
87
+ if target
88
+ @rule_appliers[index] = rule.with_target(target)
89
+ min_polling_interval = target['Interval'] if target['Interval'] && (min_polling_interval.nil? || min_polling_interval > target['Interval'])
90
+ else
91
+ OpenTelemetry.logger.debug('Invalid sampling target: missing rule name')
92
+ end
93
+ end
94
+
95
+ next_polling_interval = min_polling_interval if min_polling_interval
96
+
97
+ refresh_sampling_rules = last_rule_modification * 1000 > @last_updated_epoch_millis
98
+ return [refresh_sampling_rules, next_polling_interval]
99
+ end
100
+ end
101
+
102
+ private
103
+
104
+ def sort_rules_by_priority
105
+ @rule_appliers.sort! do |rule1, rule2|
106
+ if rule1.sampling_rule.priority == rule2.sampling_rule.priority
107
+ rule1.sampling_rule.rule_name < rule2.sampling_rule.rule_name ? -1 : 1
108
+ else
109
+ rule1.sampling_rule.priority - rule2.sampling_rule.priority
110
+ end
111
+ end
112
+ end
113
+ end
114
+ end
115
+ end
116
+ end
@@ -0,0 +1,72 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Copyright OpenTelemetry Authors
4
+ #
5
+ # SPDX-License-Identifier: Apache-2.0
6
+
7
+ module OpenTelemetry
8
+ module Sampler
9
+ module XRay
10
+ # SamplingRule represent a Sampling Rule object for AWS X-Ray
11
+ # See: https://docs.aws.amazon.com/xray/latest/api/API_SamplingRule.html
12
+ class SamplingRule
13
+ attr_accessor :rule_name, :rule_arn, :priority, :reservoir_size, :fixed_rate,
14
+ :service_name, :service_type, :host, :http_method, :url_path,
15
+ :resource_arn, :attributes, :version
16
+
17
+ def initialize(sampling_rule)
18
+ # The AWS API docs mark `rule_name` as an optional field but in practice it seems to always be
19
+ # present, and sampling targets could not be computed without it. For now provide an arbitrary fallback just in
20
+ # case the AWS API docs are correct.
21
+ @rule_name = sampling_rule['RuleName'] || 'Default'
22
+ @rule_arn = sampling_rule['RuleARN']
23
+ @priority = sampling_rule['Priority']
24
+ @reservoir_size = sampling_rule['ReservoirSize']
25
+ @fixed_rate = sampling_rule['FixedRate']
26
+ @service_name = sampling_rule['ServiceName']
27
+ @service_type = sampling_rule['ServiceType']
28
+ @host = sampling_rule['Host']
29
+ @http_method = sampling_rule['HTTPMethod']
30
+ @url_path = sampling_rule['URLPath']
31
+ @resource_arn = sampling_rule['ResourceARN']
32
+ @version = sampling_rule['Version']
33
+ @attributes = sampling_rule['Attributes']
34
+ end
35
+
36
+ def equals?(other)
37
+ attributes_equals = if @attributes.nil? || other.attributes.nil?
38
+ @attributes == other.attributes
39
+ else
40
+ attributes_equal?(other.attributes)
41
+ end
42
+
43
+ @fixed_rate == other.fixed_rate &&
44
+ @http_method == other.http_method &&
45
+ @host == other.host &&
46
+ @priority == other.priority &&
47
+ @reservoir_size == other.reservoir_size &&
48
+ @resource_arn == other.resource_arn &&
49
+ @rule_arn == other.rule_arn &&
50
+ @rule_name == other.rule_name &&
51
+ @service_name == other.service_name &&
52
+ @service_type == other.service_type &&
53
+ @url_path == other.url_path &&
54
+ @version == other.version &&
55
+ attributes_equals
56
+ end
57
+
58
+ private
59
+
60
+ def attributes_equal?(other_attributes)
61
+ return false unless @attributes.length == other_attributes.length
62
+
63
+ other_attributes.each do |key, value|
64
+ return false unless @attributes.key?(key) && @attributes[key] == value
65
+ end
66
+
67
+ true
68
+ end
69
+ end
70
+ end
71
+ end
72
+ end
@@ -0,0 +1,165 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Copyright OpenTelemetry Authors
4
+ #
5
+ # SPDX-License-Identifier: Apache-2.0
6
+
7
+ require 'opentelemetry/sdk'
8
+ require 'opentelemetry-semantic_conventions'
9
+ require 'date'
10
+ require_relative 'sampling_rule'
11
+ require_relative 'statistics'
12
+ require_relative 'rate_limiting_sampler'
13
+ require_relative 'utils'
14
+
15
+ module OpenTelemetry
16
+ module Sampler
17
+ module XRay
18
+ # SamplingRuleApplier is responsible for applying Reservoir Sampling and Probability Sampling
19
+ # from the Sampling Rule when determining the sampling decision for spans that matched the rule
20
+ class SamplingRuleApplier
21
+ attr_reader :sampling_rule
22
+
23
+ MAX_DATE_TIME_SECONDS = Time.at(8_640_000_000_000)
24
+ SEMCONV = OpenTelemetry::SemanticConventions
25
+
26
+ def initialize(sampling_rule, statistics = OpenTelemetry::Sampler::XRay::Statistics.new, target = nil)
27
+ @sampling_rule = sampling_rule
28
+ @fixed_rate_sampler = OpenTelemetry::SDK::Trace::Samplers::TraceIdRatioBased.new(@sampling_rule.fixed_rate)
29
+
30
+ @reservoir_sampler = if @sampling_rule.reservoir_size.positive?
31
+ OpenTelemetry::Sampler::XRay::RateLimitingSampler.new(1)
32
+ else
33
+ OpenTelemetry::Sampler::XRay::RateLimitingSampler.new(0)
34
+ end
35
+
36
+ @reservoir_expiry_time = MAX_DATE_TIME_SECONDS
37
+ @statistics = statistics
38
+ @statistics_lock = Mutex.new
39
+
40
+ @statistics.reset_statistics
41
+ @borrowing_enabled = true
42
+
43
+ apply_target(target) if target
44
+ end
45
+
46
+ def with_target(target)
47
+ self.class.new(@sampling_rule, @statistics, target)
48
+ end
49
+
50
+ def matches?(attributes, resource)
51
+ http_target = nil
52
+ http_url = nil
53
+ http_method = nil
54
+ http_host = nil
55
+
56
+ unless attributes.nil?
57
+ http_target = attributes[SEMCONV::Trace::HTTP_TARGET]
58
+ http_url = attributes[SEMCONV::Trace::HTTP_URL]
59
+ http_method = attributes[SEMCONV::Trace::HTTP_METHOD]
60
+ http_host = attributes[SEMCONV::Trace::HTTP_HOST]
61
+ end
62
+
63
+ service_type = nil
64
+ resource_arn = nil
65
+
66
+ resource_hash = resource.attribute_enumerator.to_h
67
+
68
+ if resource
69
+ service_name = resource_hash[SEMCONV::Resource::SERVICE_NAME] || ''
70
+ cloud_platform = resource_hash[SEMCONV::Resource::CLOUD_PLATFORM]
71
+ service_type = OpenTelemetry::Sampler::XRay::Utils::CLOUD_PLATFORM_MAPPING[cloud_platform] if cloud_platform.is_a?(String)
72
+ resource_arn = get_arn(resource, attributes)
73
+ end
74
+
75
+ if http_target.nil? && http_url.is_a?(String)
76
+ begin
77
+ uri = URI(http_url)
78
+ http_target = uri.path.empty? ? '/' : uri.path
79
+ rescue URI::InvalidURIError
80
+ http_target = '/'
81
+ end
82
+ elsif http_target.nil? && http_url.nil?
83
+ http_target = '/'
84
+ end
85
+
86
+ OpenTelemetry::Sampler::XRay::Utils.attribute_match?(attributes, @sampling_rule.attributes) &&
87
+ OpenTelemetry::Sampler::XRay::Utils.wildcard_match(@sampling_rule.host, http_host) &&
88
+ OpenTelemetry::Sampler::XRay::Utils.wildcard_match(@sampling_rule.http_method, http_method) &&
89
+ OpenTelemetry::Sampler::XRay::Utils.wildcard_match(@sampling_rule.service_name, service_name) &&
90
+ OpenTelemetry::Sampler::XRay::Utils.wildcard_match(@sampling_rule.url_path, http_target) &&
91
+ OpenTelemetry::Sampler::XRay::Utils.wildcard_match(@sampling_rule.service_type, service_type) &&
92
+ OpenTelemetry::Sampler::XRay::Utils.wildcard_match(@sampling_rule.resource_arn, resource_arn)
93
+ end
94
+
95
+ def should_sample?(trace_id:, parent_context:, links:, name:, kind:, attributes:)
96
+ has_borrowed = false
97
+ result = OpenTelemetry::SDK::Trace::Samplers::Result.new(
98
+ decision: OpenTelemetry::SDK::Trace::Samplers::Decision::DROP,
99
+ tracestate: OpenTelemetry::Trace::Tracestate::DEFAULT
100
+ )
101
+
102
+ now = Time.now
103
+ reservoir_expired = now >= @reservoir_expiry_time
104
+
105
+ unless reservoir_expired
106
+ result = @reservoir_sampler.should_sample?(
107
+ trace_id: trace_id, parent_context: parent_context, links: links, name: name, kind: kind, attributes: attributes
108
+ )
109
+ has_borrowed = @borrowing_enabled && result.instance_variable_get(:@decision) != OpenTelemetry::SDK::Trace::Samplers::Decision::DROP
110
+ end
111
+
112
+ if result.instance_variable_get(:@decision) == OpenTelemetry::SDK::Trace::Samplers::Decision::DROP
113
+ result = @fixed_rate_sampler.should_sample?(
114
+ trace_id: trace_id, parent_context: parent_context, links: links, name: name, kind: kind, attributes: attributes
115
+ )
116
+ end
117
+
118
+ @statistics_lock.synchronize do
119
+ @statistics.sample_count += result.instance_variable_get(:@decision) == OpenTelemetry::SDK::Trace::Samplers::Decision::DROP ? 0 : 1
120
+ @statistics.borrow_count += has_borrowed ? 1 : 0
121
+ @statistics.request_count += 1
122
+ end
123
+
124
+ result
125
+ end
126
+
127
+ def snapshot_statistics
128
+ @statistics_lock.synchronize do
129
+ statistics_copy = @statistics.dup
130
+ @statistics.reset_statistics
131
+ return statistics_copy
132
+ end
133
+ end
134
+
135
+ private
136
+
137
+ def apply_target(target)
138
+ @borrowing_enabled = false
139
+
140
+ @reservoir_sampler = OpenTelemetry::Sampler::XRay::RateLimitingSampler.new(target['ReservoirQuota']) if target['ReservoirQuota']
141
+
142
+ @reservoir_expiry_time = if target['ReservoirQuotaTTL']
143
+ Time.at(target['ReservoirQuotaTTL'])
144
+ else
145
+ Time.now
146
+ end
147
+
148
+ return unless target['FixedRate']
149
+
150
+ @fixed_rate_sampler = OpenTelemetry::SDK::Trace::Samplers::TraceIdRatioBased.new(target['FixedRate'])
151
+ end
152
+
153
+ def get_arn(resource, attributes)
154
+ resource_hash = resource.attribute_enumerator.to_h
155
+ arn = resource_hash[SEMCONV::Resource::AWS_ECS_CONTAINER_ARN] ||
156
+ resource_hash[SEMCONV::Resource::AWS_ECS_CLUSTER_ARN] ||
157
+ resource_hash[SEMCONV::Resource::AWS_EKS_CLUSTER_ARN]
158
+
159
+ arn = attributes[SEMCONV::Trace::AWS_LAMBDA_INVOKED_ARN] || resource_hash[SEMCONV::Resource::FAAS_ID] if arn.nil?
160
+ arn
161
+ end
162
+ end
163
+ end
164
+ end
165
+ end
@@ -0,0 +1,36 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Copyright OpenTelemetry Authors
4
+ #
5
+ # SPDX-License-Identifier: Apache-2.0
6
+
7
+ module OpenTelemetry
8
+ module Sampler
9
+ module XRay
10
+ # Statistics contains metric counters for each sampling attempt in each Sampling Rule Applier
11
+ class Statistics
12
+ attr_accessor :request_count, :sample_count, :borrow_count
13
+
14
+ def initialize(request_count: 0, sample_count: 0, borrow_count: 0)
15
+ @request_count = request_count
16
+ @sample_count = sample_count
17
+ @borrow_count = borrow_count
18
+ end
19
+
20
+ def retrieve_statistics
21
+ {
22
+ request_count: @request_count,
23
+ sample_count: @sample_count,
24
+ borrow_count: @borrow_count
25
+ }
26
+ end
27
+
28
+ def reset_statistics
29
+ @request_count = 0
30
+ @sample_count = 0
31
+ @borrow_count = 0
32
+ end
33
+ end
34
+ end
35
+ end
36
+ end
@@ -0,0 +1,68 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Copyright OpenTelemetry Authors
4
+ #
5
+ # SPDX-License-Identifier: Apache-2.0
6
+
7
+ module OpenTelemetry
8
+ module Sampler
9
+ module XRay
10
+ # Utils contains utilities for X-Ray Sampling Rule matching logic
11
+ module Utils
12
+ module_function
13
+
14
+ CLOUD_PLATFORM_MAPPING = {
15
+ 'aws_lambda' => 'AWS::Lambda::Function',
16
+ 'aws_elastic_beanstalk' => 'AWS::ElasticBeanstalk::Environment',
17
+ 'aws_ec2' => 'AWS::EC2::Instance',
18
+ 'aws_ecs' => 'AWS::ECS::Container',
19
+ 'aws_eks' => 'AWS::EKS::Container'
20
+ }.freeze
21
+
22
+ def escape_regexp(regexp_pattern)
23
+ # Escapes special characters except * and ? to maintain wildcard functionality
24
+ regexp_pattern.gsub(/[.+^${}()|\[\]\\]/) { |match| "\\#{match}" }
25
+ end
26
+
27
+ def convert_pattern_to_regexp(pattern)
28
+ escape_regexp(pattern).gsub('*', '.*').tr('?', '.')
29
+ end
30
+
31
+ def wildcard_match(pattern = nil, text = nil)
32
+ return true if pattern == '*'
33
+ return false if pattern.nil? || !text.is_a?(String)
34
+ return text.empty? if pattern.empty?
35
+
36
+ regexp = "^#{convert_pattern_to_regexp(pattern.downcase)}$"
37
+ match = text.downcase.match?(regexp)
38
+
39
+ unless match
40
+ OpenTelemetry.logger.debug(
41
+ "WildcardMatch: no match found for #{text} against pattern #{pattern}"
42
+ )
43
+ end
44
+
45
+ match
46
+ end
47
+
48
+ def attribute_match?(attributes = nil, rule_attributes = nil)
49
+ return true if rule_attributes.nil? || rule_attributes.empty?
50
+
51
+ return false if attributes.nil? ||
52
+ attributes.empty? ||
53
+ rule_attributes.length > attributes.length
54
+
55
+ matched_count = 0
56
+ attributes.each do |key, value|
57
+ found_key = rule_attributes.keys.find { |rule_key| rule_key == key }
58
+ next if found_key.nil?
59
+
60
+ matched_count += 1 if wildcard_match(rule_attributes[found_key], value)
61
+ end
62
+
63
+ matched_count == rule_attributes.length
64
+ end
65
+ end
66
+ end
67
+ end
68
+ end
@@ -0,0 +1,13 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Copyright OpenTelemetry Authors
4
+ #
5
+ # SPDX-License-Identifier: Apache-2.0
6
+
7
+ module OpenTelemetry
8
+ module Sampler
9
+ module XRay
10
+ VERSION = '0.1.0'
11
+ end
12
+ end
13
+ end
@@ -0,0 +1,23 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Copyright OpenTelemetry Authors
4
+ #
5
+ # SPDX-License-Identifier: Apache-2.0
6
+
7
+ # OpenTelemetry is an open source observability framework, providing a
8
+ # general-purpose API, SDK, and related tools required for the instrumentation
9
+ # of cloud-native software, frameworks, and libraries.
10
+ #
11
+ # The OpenTelemetry module provides global accessors for telemetry objects.
12
+ # See the documentation for the `opentelemetry-api` gem for details.
13
+
14
+ module OpenTelemetry
15
+ module Sampler
16
+ # Namespace for OpenTelemetry XRay Sampler
17
+ module XRay
18
+ end
19
+ end
20
+ end
21
+
22
+ require_relative 'xray/version'
23
+ require_relative 'xray/aws_xray_remote_sampler'
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Copyright OpenTelemetry Authors
4
+ #
5
+ # SPDX-License-Identifier: Apache-2.0
6
+
7
+ require 'opentelemetry-api'
8
+ require_relative 'opentelemetry/sampler/xray'
metadata ADDED
@@ -0,0 +1,106 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: opentelemetry-sampler-xray
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - OpenTelemetry Authors
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2025-10-11 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: opentelemetry-common
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '0.21'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '0.21'
27
+ - !ruby/object:Gem::Dependency
28
+ name: opentelemetry-sdk
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '1.0'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '1.0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: opentelemetry-semantic_conventions
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '1.11'
48
+ type: :runtime
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '1.11'
55
+ description: XRay Remote Sampler for the OpenTelemetry framework
56
+ email:
57
+ - cncf-opentelemetry-contributors@lists.cncf.io
58
+ executables: []
59
+ extensions: []
60
+ extra_rdoc_files: []
61
+ files:
62
+ - ".yardopts"
63
+ - CHANGELOG.md
64
+ - LICENSE
65
+ - README.md
66
+ - lib/opentelemetry-sampler-xray.rb
67
+ - lib/opentelemetry/sampler/xray.rb
68
+ - lib/opentelemetry/sampler/xray/aws_xray_remote_sampler.rb
69
+ - lib/opentelemetry/sampler/xray/aws_xray_sampling_client.rb
70
+ - lib/opentelemetry/sampler/xray/fallback_sampler.rb
71
+ - lib/opentelemetry/sampler/xray/rate_limiter.rb
72
+ - lib/opentelemetry/sampler/xray/rate_limiting_sampler.rb
73
+ - lib/opentelemetry/sampler/xray/rule_cache.rb
74
+ - lib/opentelemetry/sampler/xray/sampling_rule.rb
75
+ - lib/opentelemetry/sampler/xray/sampling_rule_applier.rb
76
+ - lib/opentelemetry/sampler/xray/statistics.rb
77
+ - lib/opentelemetry/sampler/xray/utils.rb
78
+ - lib/opentelemetry/sampler/xray/version.rb
79
+ homepage: https://github.com/open-telemetry/opentelemetry-ruby-contrib
80
+ licenses:
81
+ - Apache-2.0
82
+ metadata:
83
+ changelog_uri: https://rubydoc.info/gems/opentelemetry-sampler-xray/0.1.0/file/CHANGELOG.md
84
+ source_code_uri: https://github.com/open-telemetry/opentelemetry-ruby-contrib/tree/main/sampler/xray
85
+ bug_tracker_uri: https://github.com/open-telemetry/opentelemetry-ruby-contrib/issues
86
+ documentation_uri: https://rubydoc.info/gems/opentelemetry-sampler-xray/0.1.0
87
+ post_install_message: ''
88
+ rdoc_options: []
89
+ require_paths:
90
+ - lib
91
+ required_ruby_version: !ruby/object:Gem::Requirement
92
+ requirements:
93
+ - - ">="
94
+ - !ruby/object:Gem::Version
95
+ version: '3.1'
96
+ required_rubygems_version: !ruby/object:Gem::Requirement
97
+ requirements:
98
+ - - ">="
99
+ - !ruby/object:Gem::Version
100
+ version: '0'
101
+ requirements: []
102
+ rubygems_version: 3.3.27
103
+ signing_key:
104
+ specification_version: 4
105
+ summary: XRay Remote Sampler for the OpenTelemetry framework
106
+ test_files: []