libo11y 0.2.0 → 0.3.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 +4 -4
- data/CHANGELOG.md +170 -21
- data/README.md +77 -8
- data/lib/libo11y/{proc.rb → child_process.rb} +12 -2
- data/lib/libo11y/db.rb +22 -10
- data/lib/libo11y/detached.rb +241 -29
- data/lib/libo11y/http_client.rb +48 -15
- data/lib/libo11y/internal/bridges.rb +3553 -255
- data/lib/libo11y/internal/endpoint.rb +7 -1
- data/lib/libo11y/internal/env.rb +177 -59
- data/lib/libo11y/internal/error_type.rb +17 -0
- data/lib/libo11y/internal/histogram_buckets.rb +42 -0
- data/lib/libo11y/internal/http_common.rb +2 -0
- data/lib/libo11y/internal/identity.rb +10 -1
- data/lib/libo11y/internal/injected.rb +178 -0
- data/lib/libo11y/internal/logging_device.rb +141 -32
- data/lib/libo11y/internal/path_match.rb +148 -0
- data/lib/libo11y/internal/pii.rb +185 -65
- data/lib/libo11y/internal/pipeline.rb +141 -34
- data/lib/libo11y/internal/policy.rb +556 -52
- data/lib/libo11y/internal/propagators.rb +29 -6
- data/lib/libo11y/internal/quiet_inspect.rb +20 -0
- data/lib/libo11y/internal/resource.rb +187 -52
- data/lib/libo11y/internal/sdk_load.rb +64 -0
- data/lib/libo11y/internal/sql_text.rb +365 -67
- data/lib/libo11y/internal/summary.rb +2 -1
- data/lib/libo11y/options.rb +159 -1
- data/lib/libo11y/rack.rb +257 -44
- data/lib/libo11y/record.rb +70 -7
- data/lib/libo11y/redact.rb +87 -21
- data/lib/libo11y/signals.rb +70 -29
- data/lib/libo11y/spec/app_registry.rb +97 -61
- data/lib/libo11y/spec/yaml_v3.rb +179 -111
- data/lib/libo11y/telemetry.rb +315 -53
- data/lib/libo11y/testing.rb +31 -19
- data/lib/libo11y/version.rb +1 -1
- data/lib/libo11y.rb +1 -1
- metadata +94 -39
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
|
-
require "
|
|
4
|
-
require "
|
|
5
|
-
require "
|
|
3
|
+
require "delegate"
|
|
4
|
+
require "timeout"
|
|
5
|
+
require "weakref"
|
|
6
|
+
require_relative "sdk_load"
|
|
6
7
|
require "opentelemetry/exporter/otlp"
|
|
7
8
|
require "opentelemetry/exporter/otlp_metrics"
|
|
8
9
|
require "opentelemetry/exporter/otlp_logs"
|
|
@@ -11,6 +12,7 @@ require_relative "../options"
|
|
|
11
12
|
require_relative "../spec"
|
|
12
13
|
require_relative "env"
|
|
13
14
|
require_relative "policy"
|
|
15
|
+
require_relative "quiet_inspect"
|
|
14
16
|
|
|
15
17
|
module Libo11y
|
|
16
18
|
module Internal
|
|
@@ -19,6 +21,8 @@ module Libo11y
|
|
|
19
21
|
# nothing and mint no trace identity, and an inbound trace context still
|
|
20
22
|
# passes through them.
|
|
21
23
|
class NoopTracerProvider < OpenTelemetry::Trace::TracerProvider
|
|
24
|
+
include QuietInspect
|
|
25
|
+
|
|
22
26
|
def add_span_processor(_processor); end
|
|
23
27
|
|
|
24
28
|
def force_flush(timeout: nil) # rubocop:disable Lint/UnusedMethodArgument
|
|
@@ -59,6 +63,8 @@ module Libo11y
|
|
|
59
63
|
# Wraps a span, metric or log record exporter and records every export
|
|
60
64
|
# that fails, times out or raises.
|
|
61
65
|
class ObservedExporter
|
|
66
|
+
include QuietInspect
|
|
67
|
+
|
|
62
68
|
SUCCESS = OpenTelemetry::SDK::Trace::Export::SUCCESS
|
|
63
69
|
TIMEOUT = OpenTelemetry::SDK::Trace::Export::TIMEOUT
|
|
64
70
|
|
|
@@ -70,9 +76,11 @@ module Libo11y
|
|
|
70
76
|
|
|
71
77
|
def export(data, timeout: nil)
|
|
72
78
|
result = @inner.export(data, timeout: timeout)
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
@failures.record(
|
|
79
|
+
if result.is_a?(Integer) && result == TIMEOUT
|
|
80
|
+
# Named as a timeout, so that error.type tells it from a rejection.
|
|
81
|
+
@failures.record(Timeout::Error.new("the #{@signal} export timed out"))
|
|
82
|
+
elsif !result.is_a?(Integer) || result != SUCCESS
|
|
83
|
+
@failures.record(ExporterError.new("the #{@signal} export failed"))
|
|
76
84
|
end
|
|
77
85
|
result
|
|
78
86
|
rescue StandardError => e
|
|
@@ -80,6 +88,14 @@ module Libo11y
|
|
|
80
88
|
raise
|
|
81
89
|
end
|
|
82
90
|
|
|
91
|
+
def force_flush(timeout: nil)
|
|
92
|
+
forward_lifecycle(:force_flush, timeout)
|
|
93
|
+
end
|
|
94
|
+
|
|
95
|
+
def shutdown(timeout: nil)
|
|
96
|
+
forward_lifecycle(:shutdown, timeout)
|
|
97
|
+
end
|
|
98
|
+
|
|
83
99
|
def method_missing(name, ...)
|
|
84
100
|
@inner.public_send(name, ...)
|
|
85
101
|
end
|
|
@@ -87,10 +103,21 @@ module Libo11y
|
|
|
87
103
|
def respond_to_missing?(name, include_private = false)
|
|
88
104
|
@inner.respond_to?(name, include_private)
|
|
89
105
|
end
|
|
106
|
+
|
|
107
|
+
private
|
|
108
|
+
|
|
109
|
+
def forward_lifecycle(step, timeout)
|
|
110
|
+
return SUCCESS unless @inner.respond_to?(step)
|
|
111
|
+
|
|
112
|
+
raw = Bridges.takes_timeout?(@inner, step) ? @inner.public_send(step, timeout: timeout) : @inner.public_send(step)
|
|
113
|
+
Bridges.normalize_lifecycle_status(raw)
|
|
114
|
+
end
|
|
90
115
|
end
|
|
91
116
|
|
|
92
117
|
# Wraps any span exporter so span, event, and link attributes pass through SensitivityPolicy once.
|
|
93
118
|
class PolicySpanExporter
|
|
119
|
+
include QuietInspect
|
|
120
|
+
|
|
94
121
|
def initialize(inner, policy)
|
|
95
122
|
@inner = inner
|
|
96
123
|
@policy = policy
|
|
@@ -102,301 +129,655 @@ module Libo11y
|
|
|
102
129
|
end
|
|
103
130
|
|
|
104
131
|
def force_flush(timeout: nil)
|
|
105
|
-
@inner.force_flush(timeout: timeout)
|
|
132
|
+
Bridges.takes_timeout?(@inner, :force_flush) ? @inner.force_flush(timeout: timeout) : @inner.force_flush
|
|
106
133
|
end
|
|
107
134
|
|
|
108
135
|
def shutdown(timeout: nil)
|
|
109
|
-
@inner.shutdown(timeout: timeout)
|
|
136
|
+
Bridges.takes_timeout?(@inner, :shutdown) ? @inner.shutdown(timeout: timeout) : @inner.shutdown
|
|
110
137
|
end
|
|
111
138
|
|
|
112
139
|
def self.redact_span_data(sd, policy)
|
|
140
|
+
name = Bridges.scrub_utf8(sd.name)
|
|
141
|
+
name_changed = !name.equal?(sd.name)
|
|
142
|
+
new_status, status_changed = redact_status(sd.status)
|
|
143
|
+
|
|
113
144
|
attrs, attrs_changed = policy.classify_flat(Spec::Signal::TRACES, sd.attributes)
|
|
145
|
+
scrubbed_attrs = Bridges.scrub_otel_value(attrs, homogeneous_arrays: true)
|
|
146
|
+
attrs_changed ||= !scrubbed_attrs.equal?(attrs)
|
|
147
|
+
|
|
148
|
+
new_events, events_changed = redact_events(sd.events, policy)
|
|
149
|
+
new_links, links_changed = redact_links(sd.links, policy)
|
|
150
|
+
|
|
151
|
+
return sd unless name_changed || status_changed || attrs_changed || events_changed || links_changed
|
|
114
152
|
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
153
|
+
# A copy with the modified members set, so every other member stays,
|
|
154
|
+
# also one a later SDK release adds to the struct.
|
|
155
|
+
redacted = sd.dup
|
|
156
|
+
redacted.name = name if name_changed
|
|
157
|
+
redacted.status = new_status if status_changed
|
|
158
|
+
redacted.attributes = scrubbed_attrs
|
|
159
|
+
redacted.events = new_events
|
|
160
|
+
redacted.links = new_links
|
|
161
|
+
redacted
|
|
162
|
+
end
|
|
163
|
+
|
|
164
|
+
def self.redact_status(status)
|
|
165
|
+
return [status, false] unless status
|
|
166
|
+
|
|
167
|
+
desc = Bridges.scrub_utf8(status.description)
|
|
168
|
+
return [status, false] if desc.equal?(status.description)
|
|
169
|
+
|
|
170
|
+
[rebuild_status(status, desc), true]
|
|
171
|
+
end
|
|
172
|
+
|
|
173
|
+
def self.redact_events(events, policy)
|
|
174
|
+
return [events, false] unless events
|
|
175
|
+
|
|
176
|
+
changed = false
|
|
177
|
+
updated = events.map do |ev|
|
|
178
|
+
ev_name = Bridges.scrub_utf8(ev.name)
|
|
179
|
+
ev_attrs, attr_changed = policy.classify_flat(Spec::Signal::TRACES, ev.attributes)
|
|
180
|
+
scrubbed = Bridges.scrub_otel_value(ev_attrs, homogeneous_arrays: true)
|
|
181
|
+
if attr_changed || !ev_name.equal?(ev.name) || !scrubbed.equal?(ev_attrs)
|
|
182
|
+
changed = true
|
|
183
|
+
OpenTelemetry::SDK::Trace::Event.new(ev_name, scrubbed, ev.timestamp)
|
|
121
184
|
else
|
|
122
185
|
ev
|
|
123
186
|
end
|
|
124
187
|
end
|
|
188
|
+
[updated, changed]
|
|
189
|
+
end
|
|
125
190
|
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
191
|
+
def self.redact_links(links, policy)
|
|
192
|
+
return [links, false] unless links
|
|
193
|
+
|
|
194
|
+
changed = false
|
|
195
|
+
updated = links.map do |lk|
|
|
196
|
+
lk_attrs, attr_changed = policy.classify_flat(Spec::Signal::TRACES, lk.attributes)
|
|
197
|
+
scrubbed = Bridges.scrub_otel_value(lk_attrs, homogeneous_arrays: true)
|
|
198
|
+
if attr_changed || !scrubbed.equal?(lk_attrs)
|
|
199
|
+
changed = true
|
|
200
|
+
OpenTelemetry::Trace::Link.new(lk.span_context, scrubbed)
|
|
132
201
|
else
|
|
133
202
|
lk
|
|
134
203
|
end
|
|
135
204
|
end
|
|
205
|
+
[updated, changed]
|
|
206
|
+
end
|
|
136
207
|
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
OpenTelemetry::
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
sd.parent_span_id,
|
|
144
|
-
sd.total_recorded_attributes,
|
|
145
|
-
sd.total_recorded_events,
|
|
146
|
-
sd.total_recorded_links,
|
|
147
|
-
sd.start_timestamp,
|
|
148
|
-
sd.end_timestamp,
|
|
149
|
-
attrs,
|
|
150
|
-
new_links,
|
|
151
|
-
new_events,
|
|
152
|
-
sd.resource,
|
|
153
|
-
sd.instrumentation_scope,
|
|
154
|
-
sd.span_id,
|
|
155
|
-
sd.trace_id,
|
|
156
|
-
sd.trace_flags,
|
|
157
|
-
sd.tracestate,
|
|
158
|
-
sd.parent_span_is_remote
|
|
159
|
-
)
|
|
208
|
+
def self.rebuild_status(status, description)
|
|
209
|
+
case status.code
|
|
210
|
+
when OpenTelemetry::Trace::Status::OK then OpenTelemetry::Trace::Status.ok(description)
|
|
211
|
+
when OpenTelemetry::Trace::Status::ERROR then OpenTelemetry::Trace::Status.error(description)
|
|
212
|
+
else OpenTelemetry::Trace::Status.unset(description)
|
|
213
|
+
end
|
|
160
214
|
end
|
|
215
|
+
private_class_method :redact_status, :redact_events, :redact_links, :rebuild_status
|
|
161
216
|
end
|
|
162
217
|
|
|
163
|
-
#
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
218
|
+
# Thread-local key carrying the caller's absolute monotonic deadline from
|
|
219
|
+
# Telemetry#force_flush and Telemetry#run_shutdown into providers and
|
|
220
|
+
# ReaderCoordinator so nested queues never start a second, later clock.
|
|
221
|
+
DEADLINE_KEY = :libo11y_lifecycle_deadline
|
|
222
|
+
CREATING_STREAMS_KEY = :libo11y_creating_streams
|
|
223
|
+
|
|
224
|
+
# Calls a list of injected processors so that one that raises does not
|
|
225
|
+
# keep the others from running, as the SDK's tracer provider does for
|
|
226
|
+
# its own. Shutdown and flush run concurrently under a shared deadline.
|
|
227
|
+
module ProcessorFanOut
|
|
228
|
+
# @api private
|
|
229
|
+
def lifecycle_targets
|
|
230
|
+
@processors
|
|
231
|
+
end
|
|
232
|
+
|
|
233
|
+
# @api private
|
|
234
|
+
def mark_stopped!
|
|
235
|
+
@stopped = true
|
|
236
|
+
end
|
|
237
|
+
|
|
238
|
+
private
|
|
239
|
+
|
|
240
|
+
# Calls the block with each processor. An error is kept for the
|
|
241
|
+
# signal's report, sent to OpenTelemetry's error handler, and counted
|
|
242
|
+
# as a failure. Checks @stopped before each processor as a best-effort
|
|
243
|
+
# guard so an in-progress span or log call skips later siblings once
|
|
244
|
+
# shutdown starts.
|
|
245
|
+
def each_processor(action)
|
|
246
|
+
@processors.map do |processor|
|
|
247
|
+
break if @stopped
|
|
248
|
+
|
|
249
|
+
yield processor
|
|
250
|
+
rescue StandardError => e
|
|
251
|
+
@failures&.record(e)
|
|
252
|
+
OpenTelemetry.handle_error(exception: e, message: "libo11y: #{processor.class} raised in #{action}")
|
|
253
|
+
OpenTelemetry::SDK::Trace::Export::FAILURE
|
|
254
|
+
end
|
|
255
|
+
end
|
|
256
|
+
|
|
257
|
+
def fanout_lifecycle(action, timeout, deadline: nil, &on_done)
|
|
258
|
+
mark_stopped! if action == :shutdown
|
|
259
|
+
list = @processors
|
|
260
|
+
if list.empty?
|
|
261
|
+
on_done&.call if action == :shutdown
|
|
262
|
+
return OpenTelemetry::SDK::Trace::Export::SUCCESS
|
|
263
|
+
end
|
|
264
|
+
|
|
265
|
+
if action == :shutdown
|
|
266
|
+
@fanout_coordinator.shutdown(list, timeout, deadline: deadline, on_all_done: on_done)
|
|
267
|
+
else
|
|
268
|
+
@fanout_coordinator.force_flush(list, timeout, deadline: deadline)
|
|
269
|
+
end
|
|
270
|
+
end
|
|
271
|
+
end
|
|
272
|
+
|
|
273
|
+
# One span processor of libo11y's own, the one that exports, behind
|
|
274
|
+
# the same isolation. The SDK's tracer provider stops at the first
|
|
275
|
+
# processor whose shutdown or flush raises, which would leave the
|
|
276
|
+
# injected processors after it running.
|
|
277
|
+
class IsolatedSpanProcessor
|
|
278
|
+
include ProcessorFanOut
|
|
279
|
+
include QuietInspect
|
|
280
|
+
|
|
281
|
+
def initialize(processor, failures)
|
|
282
|
+
@processors = [processor]
|
|
283
|
+
@failures = failures
|
|
284
|
+
@stopped = false
|
|
285
|
+
@fanout_coordinator = ReaderCoordinator.new(failures)
|
|
168
286
|
end
|
|
169
287
|
|
|
170
288
|
def on_start(span, parent_context)
|
|
171
|
-
@
|
|
289
|
+
return if @stopped
|
|
290
|
+
|
|
291
|
+
each_processor("on_start") { |processor| processor.on_start(span, parent_context) }
|
|
172
292
|
end
|
|
173
293
|
|
|
174
294
|
def on_finish(span)
|
|
175
|
-
|
|
176
|
-
|
|
295
|
+
return if @stopped
|
|
296
|
+
|
|
297
|
+
each_processor("on_finish") { |processor| processor.on_finish(span) }
|
|
177
298
|
end
|
|
178
299
|
|
|
179
300
|
def force_flush(timeout: nil)
|
|
180
|
-
|
|
301
|
+
fanout_lifecycle(:force_flush, timeout)
|
|
181
302
|
end
|
|
182
303
|
|
|
183
304
|
def shutdown(timeout: nil)
|
|
184
|
-
|
|
305
|
+
fanout_lifecycle(:shutdown, timeout)
|
|
185
306
|
end
|
|
186
307
|
end
|
|
187
308
|
|
|
188
|
-
#
|
|
189
|
-
#
|
|
190
|
-
#
|
|
191
|
-
class
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
@policy = policy
|
|
195
|
-
end
|
|
309
|
+
# The injected log record processors, behind one processor the SDK
|
|
310
|
+
# calls. The SDK's logger provider stops at the first processor whose
|
|
311
|
+
# shutdown raises, which would leave the others running.
|
|
312
|
+
class IsolatedLogProcessors
|
|
313
|
+
include ProcessorFanOut
|
|
314
|
+
include QuietInspect
|
|
196
315
|
|
|
197
|
-
def
|
|
198
|
-
@
|
|
316
|
+
def initialize(processors, failures)
|
|
317
|
+
@processors = processors
|
|
318
|
+
@failures = failures
|
|
319
|
+
@stopped = false
|
|
320
|
+
@fanout_coordinator = ReaderCoordinator.new(failures)
|
|
199
321
|
end
|
|
200
322
|
|
|
201
|
-
|
|
202
|
-
|
|
323
|
+
# Adds a processor to the group, once. The list is replaced and not
|
|
324
|
+
# changed, since records are emitted on other threads.
|
|
325
|
+
def add(processor)
|
|
326
|
+
@processors = [*@processors, processor] unless include?(processor)
|
|
203
327
|
end
|
|
204
328
|
|
|
205
|
-
def
|
|
206
|
-
|
|
329
|
+
def include?(processor)
|
|
330
|
+
@processors.any? do |known|
|
|
331
|
+
known.equal?(processor) || (known.is_a?(SnapshotLogRecordProcessor) && known.wraps?(processor))
|
|
332
|
+
end
|
|
207
333
|
end
|
|
208
334
|
|
|
209
|
-
def
|
|
210
|
-
|
|
335
|
+
def on_emit(log_record, context)
|
|
336
|
+
return if @stopped
|
|
337
|
+
|
|
338
|
+
each_processor("on_emit") { |processor| processor.on_emit(log_record, context) }
|
|
211
339
|
end
|
|
212
340
|
|
|
213
|
-
def
|
|
214
|
-
|
|
341
|
+
def force_flush(timeout: nil, deadline: nil)
|
|
342
|
+
fanout_lifecycle(:force_flush, timeout, deadline: deadline)
|
|
215
343
|
end
|
|
216
344
|
|
|
217
|
-
def
|
|
218
|
-
|
|
345
|
+
def shutdown(timeout: nil, deadline: nil, &on_done)
|
|
346
|
+
fanout_lifecycle(:shutdown, timeout, deadline: deadline, &on_done)
|
|
219
347
|
end
|
|
220
348
|
end
|
|
221
349
|
|
|
222
|
-
#
|
|
223
|
-
#
|
|
224
|
-
#
|
|
225
|
-
#
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
350
|
+
# Wraps an export log processor so it receives a deep-copied LogRecordData
|
|
351
|
+
# snapshot at handoff. A later application processor that enriches or
|
|
352
|
+
# mutates the mutable LogRecord cannot alter a record already queued for
|
|
353
|
+
# OTLP export.
|
|
354
|
+
class SnapshotLogRecordProcessor
|
|
355
|
+
include QuietInspect
|
|
356
|
+
|
|
357
|
+
# Delegates LogRecordData readers (body, attributes, severity_text,
|
|
358
|
+
# trace_id, span_id, etc.) while preserving the LogRecord's original
|
|
359
|
+
# Time timestamps and converting timestamp assignments to nanoseconds
|
|
360
|
+
# so BatchLogRecordProcessor subclasses that inspect or edit record
|
|
361
|
+
# fields before calling super work unchanged.
|
|
362
|
+
class Snapshot < SimpleDelegator
|
|
363
|
+
attr_reader :timestamp, :observed_timestamp
|
|
364
|
+
|
|
365
|
+
def initialize(data, timestamp:, observed_timestamp:)
|
|
366
|
+
super(data)
|
|
367
|
+
@timestamp = timestamp
|
|
368
|
+
@observed_timestamp = observed_timestamp
|
|
369
|
+
end
|
|
229
370
|
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
371
|
+
def timestamp=(value)
|
|
372
|
+
@timestamp = value
|
|
373
|
+
__getobj__.timestamp = to_integer_nanoseconds(value)
|
|
374
|
+
end
|
|
234
375
|
|
|
235
|
-
|
|
236
|
-
|
|
376
|
+
def observed_timestamp=(value)
|
|
377
|
+
@observed_timestamp = value
|
|
378
|
+
__getobj__.observed_timestamp = to_integer_nanoseconds(value)
|
|
379
|
+
end
|
|
380
|
+
|
|
381
|
+
def to_log_record_data
|
|
382
|
+
__getobj__
|
|
383
|
+
end
|
|
384
|
+
|
|
385
|
+
private
|
|
386
|
+
|
|
387
|
+
def to_integer_nanoseconds(value)
|
|
388
|
+
return (value.to_r * 1_000_000_000).to_i if value.is_a?(Time)
|
|
389
|
+
|
|
390
|
+
value
|
|
391
|
+
end
|
|
237
392
|
end
|
|
393
|
+
private_constant :Snapshot
|
|
238
394
|
|
|
239
|
-
def
|
|
240
|
-
|
|
395
|
+
def initialize(inner)
|
|
396
|
+
@inner = inner
|
|
397
|
+
end
|
|
241
398
|
|
|
242
|
-
|
|
243
|
-
|
|
399
|
+
def wraps?(processor)
|
|
400
|
+
equal?(processor) || @inner.equal?(processor)
|
|
244
401
|
end
|
|
245
402
|
|
|
246
|
-
def
|
|
247
|
-
|
|
403
|
+
def on_emit(log_record, context)
|
|
404
|
+
detached = log_record.to_log_record_data.dup
|
|
405
|
+
detached.severity_text = deep_copy(detached.severity_text)
|
|
406
|
+
detached.body = deep_copy(detached.body)
|
|
407
|
+
detached.attributes = deep_copy(detached.attributes)
|
|
408
|
+
detached.event_name = deep_copy(detached.event_name)
|
|
409
|
+
detached.trace_id = copy_binary_id(detached.trace_id)
|
|
410
|
+
detached.span_id = copy_binary_id(detached.span_id)
|
|
411
|
+
detached.instrumentation_scope = copy_scope(detached.instrumentation_scope)
|
|
412
|
+
@inner.on_emit(
|
|
413
|
+
Snapshot.new(detached, timestamp: log_record.timestamp, observed_timestamp: log_record.observed_timestamp),
|
|
414
|
+
context
|
|
415
|
+
)
|
|
248
416
|
end
|
|
249
417
|
|
|
250
|
-
def
|
|
251
|
-
|
|
418
|
+
def force_flush(timeout: nil)
|
|
419
|
+
Bridges.takes_timeout?(@inner, :force_flush) ? @inner.force_flush(timeout: timeout) : @inner.force_flush
|
|
252
420
|
end
|
|
253
|
-
end
|
|
254
421
|
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
422
|
+
def shutdown(timeout: nil)
|
|
423
|
+
Bridges.takes_timeout?(@inner, :shutdown) ? @inner.shutdown(timeout: timeout) : @inner.shutdown
|
|
424
|
+
end
|
|
425
|
+
|
|
426
|
+
private
|
|
427
|
+
|
|
428
|
+
def deep_copy(value, active = {}.compare_by_identity, depth = 0, budget = [PII::MAX_COMPOSITE_NODES])
|
|
429
|
+
case value
|
|
430
|
+
when Hash
|
|
431
|
+
copy_hash(value, active, depth, budget)
|
|
432
|
+
when Array
|
|
433
|
+
copy_array(value, active, depth, budget)
|
|
434
|
+
when String
|
|
435
|
+
copy_string(value)
|
|
436
|
+
when Integer
|
|
437
|
+
value.between?(SensitivityPolicy::INT64_MIN, SensitivityPolicy::INT64_MAX) ? value : value.to_s
|
|
438
|
+
else
|
|
439
|
+
value
|
|
440
|
+
end
|
|
263
441
|
end
|
|
264
442
|
|
|
265
|
-
def
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
443
|
+
def copy_hash(hash, active, depth, budget)
|
|
444
|
+
return {} if depth >= PII::MAX_COMPOSITE_DEPTH
|
|
445
|
+
|
|
446
|
+
budget[0] -= 1
|
|
447
|
+
return {} if budget[0].negative?
|
|
448
|
+
|
|
449
|
+
copy = {}
|
|
450
|
+
active[hash] = true
|
|
451
|
+
begin
|
|
452
|
+
hash.each do |k, v|
|
|
453
|
+
budget[0] -= 1
|
|
454
|
+
break if budget[0].negative?
|
|
455
|
+
next if (v.is_a?(Hash) || v.is_a?(Array)) && active.key?(v)
|
|
456
|
+
|
|
457
|
+
safe_key = k.is_a?(String) ? copy_string(k) : k
|
|
458
|
+
copy[safe_key] = deep_copy(v, active, depth + 1, budget)
|
|
459
|
+
end
|
|
460
|
+
ensure
|
|
461
|
+
active.delete(hash)
|
|
269
462
|
end
|
|
463
|
+
copy
|
|
270
464
|
end
|
|
271
465
|
|
|
272
|
-
def
|
|
273
|
-
|
|
466
|
+
def copy_array(list, active, depth, budget)
|
|
467
|
+
return [] if depth >= PII::MAX_COMPOSITE_DEPTH
|
|
468
|
+
|
|
469
|
+
budget[0] -= 1
|
|
470
|
+
return [] if budget[0].negative?
|
|
471
|
+
|
|
472
|
+
copy = []
|
|
473
|
+
active[list] = true
|
|
474
|
+
begin
|
|
475
|
+
list.each do |el|
|
|
476
|
+
budget[0] -= 1
|
|
477
|
+
break if budget[0].negative?
|
|
478
|
+
next if (el.is_a?(Hash) || el.is_a?(Array)) && active.key?(el)
|
|
479
|
+
|
|
480
|
+
copy << deep_copy(el, active, depth + 1, budget)
|
|
481
|
+
end
|
|
482
|
+
ensure
|
|
483
|
+
active.delete(list)
|
|
484
|
+
end
|
|
485
|
+
copy
|
|
274
486
|
end
|
|
275
487
|
|
|
276
|
-
def
|
|
277
|
-
|
|
488
|
+
def copy_string(str)
|
|
489
|
+
safe = SensitivityPolicy.utf8_safe(str)
|
|
490
|
+
return safe if safe.frozen? || !safe.equal?(str)
|
|
491
|
+
|
|
492
|
+
safe.dup
|
|
278
493
|
end
|
|
279
494
|
|
|
280
|
-
def
|
|
281
|
-
|
|
495
|
+
def copy_binary_id(raw_id)
|
|
496
|
+
return raw_id unless raw_id.is_a?(String) && !raw_id.frozen?
|
|
497
|
+
|
|
498
|
+
raw_id.dup
|
|
282
499
|
end
|
|
283
500
|
|
|
284
|
-
def
|
|
285
|
-
|
|
501
|
+
def copy_scope(scope)
|
|
502
|
+
return nil if scope.nil?
|
|
503
|
+
|
|
504
|
+
OpenTelemetry::SDK::InstrumentationScope.new(
|
|
505
|
+
copy_string(scope.name), copy_string(scope.version), deep_copy(scope.attributes)
|
|
506
|
+
)
|
|
286
507
|
end
|
|
508
|
+
end
|
|
509
|
+
|
|
510
|
+
# Hands the injected span processors each finished span as a redacted
|
|
511
|
+
# snapshot. on_start gets the live span. The span is classified once,
|
|
512
|
+
# before any processor sees it, so its violations are counted once
|
|
513
|
+
# whichever processor reads it.
|
|
514
|
+
class PolicySpanProcessor
|
|
515
|
+
include ProcessorFanOut
|
|
516
|
+
include QuietInspect
|
|
287
517
|
|
|
288
|
-
def
|
|
289
|
-
@
|
|
518
|
+
def initialize(processors, policy, failures = nil)
|
|
519
|
+
@processors = processors
|
|
520
|
+
@policy = policy
|
|
521
|
+
@failures = failures
|
|
522
|
+
@stopped = false
|
|
523
|
+
@fanout_coordinator = ReaderCoordinator.new(failures)
|
|
290
524
|
end
|
|
291
525
|
|
|
292
|
-
|
|
293
|
-
|
|
526
|
+
# Adds a processor to the group, once. The list is replaced and not
|
|
527
|
+
# changed, since spans are finishing on other threads.
|
|
528
|
+
def add(processor)
|
|
529
|
+
@processors = [*@processors, processor] unless include?(processor)
|
|
294
530
|
end
|
|
295
531
|
|
|
296
|
-
def
|
|
297
|
-
@
|
|
532
|
+
def include?(processor)
|
|
533
|
+
@processors.any? { |known| known.equal?(processor) }
|
|
298
534
|
end
|
|
299
535
|
|
|
300
|
-
def
|
|
301
|
-
@
|
|
536
|
+
def on_start(span, parent_context)
|
|
537
|
+
return if @stopped
|
|
538
|
+
|
|
539
|
+
each_processor("on_start") { |processor| processor.on_start(span, parent_context) }
|
|
302
540
|
end
|
|
303
|
-
end
|
|
304
541
|
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
542
|
+
# The SDK calls this, when a processor defines it, as a span is about
|
|
543
|
+
# to end. Like on_start it gets the live span, which the policy has
|
|
544
|
+
# not classified yet.
|
|
545
|
+
def on_finishing(span)
|
|
546
|
+
return if @stopped
|
|
547
|
+
|
|
548
|
+
each_processor("on_finishing") { |processor| processor.on_finishing(span) if processor.respond_to?(:on_finishing) }
|
|
309
549
|
end
|
|
310
550
|
|
|
311
|
-
def
|
|
312
|
-
|
|
551
|
+
def on_finish(span)
|
|
552
|
+
return if @stopped
|
|
553
|
+
|
|
554
|
+
finished = FinishedSpan.new(PolicySpanExporter.redact_span_data(span.to_span_data, @policy), span.context)
|
|
555
|
+
each_processor("on_finish") { |processor| processor.on_finish(finished) }
|
|
313
556
|
end
|
|
314
557
|
|
|
315
|
-
def
|
|
316
|
-
|
|
558
|
+
def force_flush(timeout: nil, deadline: nil)
|
|
559
|
+
fanout_lifecycle(:force_flush, timeout, deadline: deadline)
|
|
317
560
|
end
|
|
318
561
|
|
|
319
|
-
def
|
|
320
|
-
|
|
321
|
-
@inner.create_histogram(
|
|
322
|
-
name,
|
|
323
|
-
unit: unit,
|
|
324
|
-
description: description,
|
|
325
|
-
advisory: { explicit_bucket_boundaries: explicit_bucket_boundaries }
|
|
326
|
-
)
|
|
327
|
-
else
|
|
328
|
-
@inner.create_histogram(name, unit: unit, description: description)
|
|
329
|
-
end
|
|
330
|
-
PolicySyncInstrument.new(inst, @policy)
|
|
562
|
+
def shutdown(timeout: nil, deadline: nil, &on_done)
|
|
563
|
+
fanout_lifecycle(:shutdown, timeout, deadline: deadline, &on_done)
|
|
331
564
|
end
|
|
565
|
+
end
|
|
332
566
|
|
|
333
|
-
|
|
334
|
-
|
|
567
|
+
# A finished span as an injected processor sees it: the redacted span
|
|
568
|
+
# data and the span context, and nothing else. It holds neither the
|
|
569
|
+
# live span nor the policy, so inspecting it shows no value the policy
|
|
570
|
+
# removed.
|
|
571
|
+
class FinishedSpan
|
|
572
|
+
attr_reader :context
|
|
573
|
+
|
|
574
|
+
def initialize(span_data, context)
|
|
575
|
+
@span_data = span_data
|
|
576
|
+
@context = context
|
|
335
577
|
end
|
|
336
578
|
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
# observe, which the wrapper classifies.
|
|
340
|
-
def create_observable_counter(name, callback: nil, unit: nil, description: nil)
|
|
341
|
-
PolicyAsyncInstrument.new(@inner.create_observable_counter(name, callback: callback, unit: unit, description: description), @policy)
|
|
579
|
+
def to_span_data
|
|
580
|
+
@span_data
|
|
342
581
|
end
|
|
343
582
|
|
|
344
|
-
def
|
|
345
|
-
|
|
346
|
-
@inner.create_observable_up_down_counter(name, callback: callback, unit: unit, description: description), @policy
|
|
347
|
-
)
|
|
583
|
+
def recording?
|
|
584
|
+
false
|
|
348
585
|
end
|
|
349
586
|
|
|
350
|
-
def
|
|
351
|
-
|
|
587
|
+
def inspect
|
|
588
|
+
"#<#{self.class.name} name=#{@span_data.name.inspect} trace_id=#{@context.hex_trace_id} span_id=#{@context.hex_span_id}>"
|
|
352
589
|
end
|
|
353
590
|
|
|
591
|
+
# The readers of a span: name, kind, status, attributes, events, links,
|
|
592
|
+
# the timestamps, resource and instrumentation_scope.
|
|
354
593
|
def method_missing(name, ...)
|
|
355
|
-
@
|
|
594
|
+
@span_data.respond_to?(name) ? @span_data.public_send(name, ...) : super
|
|
356
595
|
end
|
|
357
596
|
|
|
358
597
|
def respond_to_missing?(name, include_private = false)
|
|
359
|
-
@
|
|
598
|
+
@span_data.respond_to?(name, include_private) || super
|
|
360
599
|
end
|
|
361
600
|
end
|
|
362
601
|
|
|
363
|
-
#
|
|
364
|
-
#
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
602
|
+
# The first processor on the logger provider. It classifies the
|
|
603
|
+
# attributes of a record that reached the provider through the
|
|
604
|
+
# OpenTelemetry Logs API, in place, so every later processor sees the
|
|
605
|
+
# classified record. A record from the libo11y logger is already
|
|
606
|
+
# classified and counted, and its context says so.
|
|
607
|
+
class PolicyLogRecordProcessor
|
|
608
|
+
include QuietInspect
|
|
609
|
+
|
|
610
|
+
CLASSIFIED_FIBER_KEY = :libo11y_log_classified
|
|
611
|
+
ORIGINAL_ATTRS_FIBER_KEY = :libo11y_original_log_attrs
|
|
612
|
+
private_constant :CLASSIFIED_FIBER_KEY, :ORIGINAL_ATTRS_FIBER_KEY
|
|
613
|
+
|
|
614
|
+
# Marks a single synchronous emission from Telemetry#logger as already
|
|
615
|
+
# classified, without attaching any bypass marker to OpenTelemetry::Context.
|
|
616
|
+
#
|
|
617
|
+
# @api private
|
|
618
|
+
def self.with_classified
|
|
619
|
+
previous = Thread.current[CLASSIFIED_FIBER_KEY]
|
|
620
|
+
Thread.current[CLASSIFIED_FIBER_KEY] = true
|
|
621
|
+
yield
|
|
622
|
+
ensure
|
|
623
|
+
Thread.current[CLASSIFIED_FIBER_KEY] = previous
|
|
624
|
+
end
|
|
625
|
+
|
|
626
|
+
# @api private
|
|
627
|
+
def self.take_classified?
|
|
628
|
+
classified = Thread.current[CLASSIFIED_FIBER_KEY]
|
|
629
|
+
Thread.current[CLASSIFIED_FIBER_KEY] = false
|
|
630
|
+
classified ? true : false
|
|
631
|
+
end
|
|
632
|
+
|
|
633
|
+
# @api private
|
|
634
|
+
def self.with_original_attrs(source)
|
|
635
|
+
previous = Thread.current[ORIGINAL_ATTRS_FIBER_KEY]
|
|
636
|
+
Thread.current[ORIGINAL_ATTRS_FIBER_KEY] = source
|
|
637
|
+
yield
|
|
638
|
+
ensure
|
|
639
|
+
Thread.current[ORIGINAL_ATTRS_FIBER_KEY] = previous
|
|
640
|
+
end
|
|
641
|
+
|
|
642
|
+
# @api private
|
|
643
|
+
def self.take_original_attrs
|
|
644
|
+
source = Thread.current[ORIGINAL_ATTRS_FIBER_KEY]
|
|
645
|
+
Thread.current[ORIGINAL_ATTRS_FIBER_KEY] = nil
|
|
646
|
+
source
|
|
647
|
+
end
|
|
648
|
+
|
|
649
|
+
def initialize(policy)
|
|
368
650
|
@policy = policy
|
|
369
651
|
end
|
|
370
652
|
|
|
371
|
-
def
|
|
372
|
-
|
|
653
|
+
def on_emit(log_record, context)
|
|
654
|
+
classified = self.class.take_classified?
|
|
655
|
+
seen = self.class.take_original_attrs
|
|
656
|
+
take_identity_from(log_record, context)
|
|
657
|
+
unless classified
|
|
658
|
+
scrubbed_severity = Bridges.scrub_utf8(log_record.severity_text)
|
|
659
|
+
log_record.severity_text = scrubbed_severity unless scrubbed_severity.equal?(log_record.severity_text)
|
|
660
|
+
end
|
|
661
|
+
fill_required_fields(log_record)
|
|
662
|
+
return if classified
|
|
663
|
+
|
|
664
|
+
attrs = log_record.attributes
|
|
665
|
+
classified_attrs = attrs.nil? || attrs.empty? ? attrs : @policy.classify_log_attributes(attrs, seen: seen)
|
|
666
|
+
scrubbed_body = Bridges.scrub_otel_value(log_record.body)
|
|
667
|
+
log_record.body = scrubbed_body unless scrubbed_body.equal?(log_record.body)
|
|
668
|
+
scrubbed_event = Bridges.scrub_utf8(log_record.event_name)
|
|
669
|
+
log_record.event_name = scrubbed_event unless scrubbed_event.equal?(log_record.event_name)
|
|
670
|
+
return if classified_attrs.nil?
|
|
671
|
+
|
|
672
|
+
scrubbed_attrs = Bridges.scrub_otel_value(classified_attrs, homogeneous_arrays: true)
|
|
673
|
+
log_record.attributes = scrubbed_attrs unless scrubbed_attrs.equal?(attrs)
|
|
373
674
|
end
|
|
374
675
|
|
|
375
|
-
def
|
|
376
|
-
|
|
676
|
+
def force_flush(timeout: nil) # rubocop:disable Lint/UnusedMethodArgument
|
|
677
|
+
OpenTelemetry::SDK::Logs::Export::SUCCESS
|
|
377
678
|
end
|
|
378
679
|
|
|
379
|
-
def
|
|
380
|
-
|
|
680
|
+
def shutdown(timeout: nil) # rubocop:disable Lint/UnusedMethodArgument
|
|
681
|
+
OpenTelemetry::SDK::Logs::Export::SUCCESS
|
|
381
682
|
end
|
|
382
683
|
|
|
383
|
-
|
|
384
|
-
|
|
684
|
+
private
|
|
685
|
+
|
|
686
|
+
SEVERITY_TEXT = %w[TRACE DEBUG INFO WARN ERROR FATAL].freeze
|
|
687
|
+
SEVERITY_NUMBERS = {
|
|
688
|
+
"TRACE" => 1, "DEBUG" => 5, "INFO" => 9, "WARN" => 13, "WARNING" => 13, "ERROR" => 17, "FATAL" => 21
|
|
689
|
+
}.freeze
|
|
690
|
+
SEVERITY_PATTERN = /\A(TRACE|DEBUG|INFO|WARN|ERROR|FATAL)([2-4])?\z/
|
|
691
|
+
INFO_NUMBER = 9
|
|
692
|
+
private_constant :SEVERITY_TEXT, :SEVERITY_NUMBERS, :SEVERITY_PATTERN, :INFO_NUMBER
|
|
693
|
+
|
|
694
|
+
# Every exported record carries a timestamp, a body, and a severity
|
|
695
|
+
# number (1..24) and text. The OpenTelemetry log API lets a caller
|
|
696
|
+
# leave them out. A record without them is an INFO record of the
|
|
697
|
+
# moment it was observed with an empty string body, matching Go's
|
|
698
|
+
# fillRequiredFields. Sub-level numbers format as OpenTelemetry short
|
|
699
|
+
# names (INFO2, ERROR2, and so on).
|
|
700
|
+
def fill_required_fields(log_record)
|
|
701
|
+
log_record.timestamp ||= log_record.observed_timestamp || Time.now
|
|
702
|
+
log_record.body = "" if log_record.body.nil?
|
|
703
|
+
text = log_record.severity_text
|
|
704
|
+
text = nil if text.nil? || text.to_s.strip.empty?
|
|
705
|
+
number = log_record.severity_number
|
|
706
|
+
unless number.is_a?(Integer) && number.between?(1, 24)
|
|
707
|
+
number = severity_number_for(text)
|
|
708
|
+
log_record.severity_number = number
|
|
709
|
+
end
|
|
710
|
+
log_record.severity_text = severity_text_for(number) if text.nil?
|
|
711
|
+
end
|
|
712
|
+
|
|
713
|
+
def severity_number_for(text)
|
|
714
|
+
return INFO_NUMBER if text.nil?
|
|
715
|
+
|
|
716
|
+
up = text.to_s.strip.upcase
|
|
717
|
+
return SEVERITY_NUMBERS[up] if SEVERITY_NUMBERS.key?(up)
|
|
718
|
+
|
|
719
|
+
match = SEVERITY_PATTERN.match(up)
|
|
720
|
+
return INFO_NUMBER unless match
|
|
721
|
+
|
|
722
|
+
SEVERITY_NUMBERS.fetch(match[1]) + (match[2] ? match[2].to_i - 1 : 0)
|
|
723
|
+
end
|
|
724
|
+
|
|
725
|
+
def severity_text_for(number)
|
|
726
|
+
clamped = number.clamp(1, 24)
|
|
727
|
+
base = SEVERITY_TEXT[(clamped - 1) / 4]
|
|
728
|
+
offset = (clamped - 1) % 4
|
|
729
|
+
offset.zero? ? base : "#{base}#{offset + 1}"
|
|
730
|
+
end
|
|
731
|
+
|
|
732
|
+
# A record's trace identity is the active span's and nothing else.
|
|
733
|
+
# The OpenTelemetry log API lets a caller pass trace and span ids of
|
|
734
|
+
# its own, which the specification reserves for the context.
|
|
735
|
+
def take_identity_from(log_record, context)
|
|
736
|
+
span_context = OpenTelemetry::Trace.current_span(context || OpenTelemetry::Context.current).context
|
|
737
|
+
valid = span_context.valid?
|
|
738
|
+
log_record.trace_id = valid ? copy_id(span_context.trace_id) : nil
|
|
739
|
+
log_record.span_id = valid ? copy_id(span_context.span_id) : nil
|
|
740
|
+
log_record.trace_flags = valid ? span_context.trace_flags : nil
|
|
741
|
+
end
|
|
742
|
+
|
|
743
|
+
def copy_id(raw_id)
|
|
744
|
+
raw_id.is_a?(String) && !raw_id.frozen? ? raw_id.dup : raw_id
|
|
385
745
|
end
|
|
386
746
|
end
|
|
387
747
|
|
|
388
|
-
|
|
389
|
-
|
|
748
|
+
# Wraps a reader's MetricStore during partial registration to track which
|
|
749
|
+
# streams succeeded so retries never register duplicates and rejected
|
|
750
|
+
# streams can be pruned from instruments.
|
|
751
|
+
class StreamGuard
|
|
752
|
+
CreatedStream = Struct.new(:stream, :store, :attached, :rejected, :known, :lock)
|
|
753
|
+
MAX_SCAN_DEPTH = 16
|
|
754
|
+
MAX_SCAN_NODES = 512
|
|
755
|
+
MAX_SCAN_ENQUEUE = 512
|
|
756
|
+
MAX_COLLECTION_SCAN = 4_096
|
|
757
|
+
NO_STREAM = Object.new.freeze
|
|
758
|
+
private_constant :MAX_SCAN_DEPTH, :MAX_SCAN_NODES, :MAX_SCAN_ENQUEUE, :MAX_COLLECTION_SCAN, :NO_STREAM
|
|
759
|
+
|
|
760
|
+
def initialize(inner, attached, rejected, lock, known: nil)
|
|
390
761
|
@inner = inner
|
|
391
|
-
@
|
|
762
|
+
@attached = attached
|
|
763
|
+
@rejected = rejected
|
|
764
|
+
@known = known
|
|
765
|
+
@lock = lock
|
|
392
766
|
end
|
|
393
767
|
|
|
394
|
-
def
|
|
395
|
-
|
|
396
|
-
|
|
768
|
+
def add_metric_stream(stream)
|
|
769
|
+
return nil if ReaderHelpers.aborted_stream?(stream)
|
|
770
|
+
return nil if @lock.synchronize { @attached.key?(stream) }
|
|
397
771
|
|
|
398
|
-
|
|
399
|
-
|
|
772
|
+
Thread.current[CREATING_STREAMS_KEY]&.push(CreatedStream.new(stream, @inner, @attached, @rejected, @known, @lock))
|
|
773
|
+
completed = false
|
|
774
|
+
begin
|
|
775
|
+
@inner.add_metric_stream(stream)
|
|
776
|
+
completed = true
|
|
777
|
+
ensure
|
|
778
|
+
finalize_stream(stream, completed)
|
|
779
|
+
end
|
|
780
|
+
nil
|
|
400
781
|
end
|
|
401
782
|
|
|
402
783
|
def method_missing(name, ...)
|
|
@@ -406,100 +787,2996 @@ module Libo11y
|
|
|
406
787
|
def respond_to_missing?(name, include_private = false)
|
|
407
788
|
@inner.respond_to?(name, include_private)
|
|
408
789
|
end
|
|
409
|
-
end
|
|
410
790
|
|
|
411
|
-
|
|
791
|
+
def self.reachable_metric_stores(store)
|
|
792
|
+
return [store] if store.is_a?(OpenTelemetry::SDK::Metrics::State::MetricStore)
|
|
412
793
|
|
|
413
|
-
|
|
414
|
-
|
|
794
|
+
new(store, nil, nil, nil).collect_metric_stores
|
|
795
|
+
end
|
|
415
796
|
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
)
|
|
435
|
-
else
|
|
436
|
-
raise ExporterError, "o11y: unsupported trace sampler #{raw.inspect}"
|
|
797
|
+
# Removes stream from reachable SDK MetricStores, or from a pure
|
|
798
|
+
# duck-typed custom store's mutable collections when no backing SDK
|
|
799
|
+
# MetricStore exists.
|
|
800
|
+
def self.prune_stream(store, stream)
|
|
801
|
+
sdk_stores = reachable_metric_stores(store)
|
|
802
|
+
if sdk_stores.empty?
|
|
803
|
+
StreamPruner.new(store, stream).prune
|
|
804
|
+
return
|
|
805
|
+
end
|
|
806
|
+
|
|
807
|
+
sdk_stores.each do |sdk_store|
|
|
808
|
+
store_mutex = sdk_store.instance_variable_get(:@mutex)
|
|
809
|
+
remove = lambda do
|
|
810
|
+
streams = sdk_store.instance_variable_get(:@metric_streams)
|
|
811
|
+
streams.reject! { |ms| ms.equal?(stream) } if streams.is_a?(Array)
|
|
812
|
+
end
|
|
813
|
+
store_mutex.is_a?(Mutex) ? store_mutex.synchronize(&remove) : remove.call
|
|
814
|
+
end
|
|
437
815
|
end
|
|
438
|
-
end
|
|
439
816
|
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
817
|
+
def self.non_store_boundary?(node)
|
|
818
|
+
node.is_a?(OpenTelemetry::SDK::Metrics::State::MetricStream) ||
|
|
819
|
+
node.is_a?(OpenTelemetry::SDK::Metrics::MeterProvider) ||
|
|
820
|
+
node.is_a?(OpenTelemetry::SDK::Metrics::Meter) ||
|
|
821
|
+
node.is_a?(OpenTelemetry::SDK::Metrics::Export::MetricReader) ||
|
|
822
|
+
node.is_a?(OpenTelemetry::SDK::Metrics::Instrument::SynchronousInstrument) ||
|
|
823
|
+
node.is_a?(OpenTelemetry::SDK::Metrics::Instrument::AsynchronousInstrument) ||
|
|
824
|
+
node.is_a?(PolicyMeterProvider) || node.is_a?(PolicyMeter) || node.is_a?(IsolatedReader)
|
|
825
|
+
end
|
|
826
|
+
|
|
827
|
+
def self.entry_holds_stream?(elem, stream)
|
|
828
|
+
return false if stream.equal?(NO_STREAM)
|
|
829
|
+
return true if elem.equal?(stream)
|
|
830
|
+
return false if scalar_leaf?(elem) || non_store_boundary?(elem)
|
|
831
|
+
return false if elem.is_a?(OpenTelemetry::SDK::Metrics::State::MetricStore) || elem.is_a?(Array) || elem.is_a?(Hash) || elem.is_a?(Set)
|
|
832
|
+
|
|
833
|
+
if elem.is_a?(Struct)
|
|
834
|
+
elem.any? { |val| val.equal?(stream) }
|
|
835
|
+
elsif elem.is_a?(Data)
|
|
836
|
+
elem.deconstruct.any? { |val| val.equal?(stream) }
|
|
837
|
+
else
|
|
838
|
+
elem.instance_variables.any? { |ivar| elem.instance_variable_get(ivar).equal?(stream) }
|
|
839
|
+
end
|
|
840
|
+
end
|
|
443
841
|
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
end
|
|
842
|
+
def self.scalar_leaf?(node)
|
|
843
|
+
node.nil? || node.equal?(true) || node.equal?(false) || node.is_a?(Numeric) || node.is_a?(Symbol) || node.is_a?(String)
|
|
844
|
+
end
|
|
448
845
|
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
)
|
|
455
|
-
when ExemplarFilter::ALWAYS_OFF
|
|
456
|
-
meter_provider.disable_exemplar_filter
|
|
457
|
-
else
|
|
458
|
-
meter_provider.enable_exemplar_filter(
|
|
459
|
-
exemplar_filter: OpenTelemetry::SDK::Metrics::Exemplar::TraceBasedExemplarFilter
|
|
460
|
-
)
|
|
846
|
+
# @api private
|
|
847
|
+
def collect_metric_stores
|
|
848
|
+
state = initial_scan_state(@inner)
|
|
849
|
+
scan_wrapper(state, NO_STREAM)
|
|
850
|
+
state[:seen_stores].keys
|
|
461
851
|
end
|
|
462
|
-
end
|
|
463
852
|
|
|
464
|
-
|
|
465
|
-
# resource it sends. The upstream exporters do not write a schema URL.
|
|
466
|
-
# Each one builds its request and hands the bytes to its private
|
|
467
|
-
# send_bytes, so that method is the one place to add it for all three.
|
|
468
|
-
# An exporter without that method is returned as it is, and the wire
|
|
469
|
-
# test then fails.
|
|
470
|
-
def stamp_schema_url(exporter, request_class, field)
|
|
471
|
-
return exporter unless exporter.respond_to?(:send_bytes, true)
|
|
853
|
+
private
|
|
472
854
|
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
855
|
+
def finalize_stream(stream, completed)
|
|
856
|
+
unless ReaderHelpers.aborted_stream?(stream)
|
|
857
|
+
record_stream_outcome(stream, completed)
|
|
858
|
+
return unless ReaderHelpers.aborted_stream?(stream)
|
|
859
|
+
|
|
860
|
+
@lock.synchronize { [@attached, @rejected, @known].each { |map| map&.delete(stream) } }
|
|
861
|
+
end
|
|
862
|
+
ReaderHelpers.purge_aborted_stream(@inner, stream)
|
|
863
|
+
end
|
|
864
|
+
|
|
865
|
+
def record_stream_outcome(stream, completed)
|
|
866
|
+
accepted = completed || stream_accepted?(@inner, stream)
|
|
867
|
+
@lock.synchronize do
|
|
868
|
+
if accepted
|
|
869
|
+
@attached[stream] = true
|
|
870
|
+
@known[stream] = true if @known
|
|
871
|
+
else
|
|
872
|
+
@rejected[stream] = true
|
|
479
873
|
end
|
|
480
|
-
super(bytes, timeout: timeout)
|
|
481
874
|
end
|
|
482
|
-
private :send_bytes
|
|
483
875
|
end
|
|
484
|
-
exporter.singleton_class.prepend(stamp)
|
|
485
|
-
exporter
|
|
486
|
-
end
|
|
487
876
|
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
877
|
+
def initial_scan_state(store)
|
|
878
|
+
best_depth = {}.compare_by_identity
|
|
879
|
+
best_depth[store] = 0
|
|
880
|
+
{
|
|
881
|
+
priority_queue: [[store, 0]],
|
|
882
|
+
collection_queue: [],
|
|
883
|
+
seen_stores: {}.compare_by_identity,
|
|
884
|
+
best_depth: best_depth,
|
|
885
|
+
expanded_depth: {}.compare_by_identity,
|
|
886
|
+
priority_visited: 0,
|
|
887
|
+
collection_visited: 0,
|
|
888
|
+
priority_budget: MAX_SCAN_ENQUEUE,
|
|
889
|
+
collection_budget: MAX_SCAN_ENQUEUE,
|
|
890
|
+
found_metric_store: false,
|
|
891
|
+
found_in_collection: false
|
|
892
|
+
}
|
|
893
|
+
end
|
|
894
|
+
|
|
895
|
+
# Detects whether store (an SDK MetricStore, a subclass, or a duck-typed
|
|
896
|
+
# delegator) already retained the freshly constructed stream before
|
|
897
|
+
# raising. Direct MetricStore instances check only @metric_streams.
|
|
898
|
+
# Duck-typed wrappers run a two-tier FIFO BFS (depth 16, separate 512-node
|
|
899
|
+
# and 512-enqueue budgets for wrapper objects vs collection containers,
|
|
900
|
+
# 4096 entries per collection): wrapper objects (custom objects, Struct,
|
|
901
|
+
# Data) drain before collection containers so large audit arrays never
|
|
902
|
+
# starve discovery of a wrapped SDK MetricStore. Any reachable SDK
|
|
903
|
+
# MetricStore is authoritative over wrapper audit arrays. Pure custom
|
|
904
|
+
# stores without a backing MetricStore fall back to checking collection
|
|
905
|
+
# entries (including 1-level Struct, Data, or object wrappers).
|
|
906
|
+
def stream_accepted?(store, stream)
|
|
907
|
+
return metric_store_has_stream?(store, stream) if store.is_a?(OpenTelemetry::SDK::Metrics::State::MetricStore)
|
|
908
|
+
|
|
909
|
+
scan_wrapper(initial_scan_state(store), stream)
|
|
910
|
+
end
|
|
911
|
+
|
|
912
|
+
def scan_wrapper(state, stream)
|
|
913
|
+
loop do
|
|
914
|
+
from_priority = !state[:priority_queue].empty?
|
|
915
|
+
entry = from_priority ? state[:priority_queue].shift : state[:collection_queue].shift
|
|
916
|
+
break unless entry
|
|
917
|
+
|
|
918
|
+
node, depth = entry
|
|
919
|
+
next if skip_bfs_node?(node, depth, state)
|
|
920
|
+
|
|
921
|
+
if node.is_a?(OpenTelemetry::SDK::Metrics::State::MetricStore)
|
|
922
|
+
state[:found_metric_store] = true
|
|
923
|
+
return true if metric_store_has_stream?(node, stream)
|
|
924
|
+
|
|
925
|
+
state[:seen_stores][node] = true
|
|
926
|
+
next
|
|
927
|
+
end
|
|
928
|
+
|
|
929
|
+
visit_key = from_priority ? :priority_visited : :collection_visited
|
|
930
|
+
next if state[visit_key] >= MAX_SCAN_NODES
|
|
931
|
+
|
|
932
|
+
state[:expanded_depth][node] = depth
|
|
933
|
+
state[visit_key] += 1
|
|
934
|
+
next if depth >= MAX_SCAN_DEPTH
|
|
935
|
+
|
|
936
|
+
return true if enqueue_children?(state, node, depth + 1, stream)
|
|
937
|
+
end
|
|
938
|
+
!state[:found_metric_store] && state[:found_in_collection]
|
|
939
|
+
end
|
|
940
|
+
|
|
941
|
+
def skip_bfs_node?(node, depth, state)
|
|
942
|
+
return true if StreamGuard.scalar_leaf?(node) || StreamGuard.non_store_boundary?(node)
|
|
943
|
+
return true if state[:seen_stores].key?(node)
|
|
944
|
+
|
|
945
|
+
prev = state[:expanded_depth][node]
|
|
946
|
+
!prev.nil? && prev <= depth
|
|
947
|
+
end
|
|
948
|
+
|
|
949
|
+
def metric_store_has_stream?(store, stream)
|
|
950
|
+
return false if stream.equal?(NO_STREAM)
|
|
951
|
+
|
|
952
|
+
streams = store.instance_variable_get(:@metric_streams)
|
|
953
|
+
streams.is_a?(Array) && streams.any? { |existing| existing.equal?(stream) }
|
|
954
|
+
end
|
|
955
|
+
|
|
956
|
+
def collection_node?(node)
|
|
957
|
+
node.is_a?(Array) || node.is_a?(Set) || node.is_a?(Hash)
|
|
958
|
+
end
|
|
959
|
+
|
|
960
|
+
def check_candidate_store?(state, node, stream)
|
|
961
|
+
return false unless node.is_a?(OpenTelemetry::SDK::Metrics::State::MetricStore)
|
|
962
|
+
return false if state[:seen_stores].key?(node)
|
|
963
|
+
|
|
964
|
+
state[:found_metric_store] = true
|
|
965
|
+
return true if metric_store_has_stream?(node, stream)
|
|
966
|
+
|
|
967
|
+
state[:seen_stores][node] = true
|
|
968
|
+
false
|
|
969
|
+
end
|
|
970
|
+
|
|
971
|
+
def push_candidate?(state, node, next_depth, priority: false)
|
|
972
|
+
return true if StreamGuard.scalar_leaf?(node) || StreamGuard.non_store_boundary?(node)
|
|
973
|
+
return true if state[:seen_stores].key?(node)
|
|
974
|
+
|
|
975
|
+
prev = state[:best_depth][node]
|
|
976
|
+
return true if !prev.nil? && prev <= next_depth
|
|
977
|
+
|
|
978
|
+
use_priority = priority && !collection_node?(node)
|
|
979
|
+
budget_key = use_priority ? :priority_budget : :collection_budget
|
|
980
|
+
return false if state[budget_key] <= 0
|
|
981
|
+
|
|
982
|
+
state[budget_key] -= 1
|
|
983
|
+
state[:best_depth][node] = next_depth
|
|
984
|
+
(use_priority ? state[:priority_queue] : state[:collection_queue]) << [node, next_depth]
|
|
985
|
+
true
|
|
986
|
+
end
|
|
987
|
+
|
|
988
|
+
def enqueue_children?(state, node, next_depth, stream)
|
|
989
|
+
case node
|
|
990
|
+
when Array then scan_array?(state, node, next_depth, stream)
|
|
991
|
+
when Set then scan_set?(state, node, next_depth, stream)
|
|
992
|
+
when Hash then scan_hash?(state, node, next_depth, stream)
|
|
993
|
+
when Struct, Data
|
|
994
|
+
vals = node.is_a?(Struct) ? node.to_a : node.deconstruct
|
|
995
|
+
return true if vals.any? { |val| check_candidate_store?(state, val, stream) }
|
|
996
|
+
|
|
997
|
+
vals.each { |val| push_candidate?(state, val, next_depth, priority: true) }
|
|
998
|
+
false
|
|
999
|
+
else
|
|
1000
|
+
# Check direct MetricStore ivars first; enqueue wrapper ivars on
|
|
1001
|
+
# priority_queue and collection ivars on collection_queue.
|
|
1002
|
+
vals = node.instance_variables.map { |ivar| node.instance_variable_get(ivar) }
|
|
1003
|
+
return true if vals.any? { |val| check_candidate_store?(state, val, stream) }
|
|
1004
|
+
|
|
1005
|
+
vals.each { |val| push_candidate?(state, val, next_depth, priority: true) }
|
|
1006
|
+
false
|
|
1007
|
+
end
|
|
1008
|
+
end
|
|
1009
|
+
|
|
1010
|
+
def scan_array?(state, list, next_depth, stream)
|
|
1011
|
+
scanned = 0
|
|
1012
|
+
list.reverse_each do |elem|
|
|
1013
|
+
return true if check_candidate_store?(state, elem, stream)
|
|
1014
|
+
|
|
1015
|
+
if !state[:found_metric_store] && !state[:found_in_collection] && StreamGuard.entry_holds_stream?(elem, stream)
|
|
1016
|
+
state[:found_in_collection] = true
|
|
1017
|
+
end
|
|
1018
|
+
push_candidate?(state, elem, next_depth)
|
|
1019
|
+
scanned += 1
|
|
1020
|
+
break if scanned >= MAX_COLLECTION_SCAN
|
|
1021
|
+
end
|
|
1022
|
+
false
|
|
1023
|
+
end
|
|
1024
|
+
|
|
1025
|
+
def scan_set?(state, set, next_depth, stream)
|
|
1026
|
+
scanned = 0
|
|
1027
|
+
set.each do |elem|
|
|
1028
|
+
return true if check_candidate_store?(state, elem, stream)
|
|
1029
|
+
|
|
1030
|
+
if !state[:found_metric_store] && !state[:found_in_collection] && StreamGuard.entry_holds_stream?(elem, stream)
|
|
1031
|
+
state[:found_in_collection] = true
|
|
1032
|
+
end
|
|
1033
|
+
push_candidate?(state, elem, next_depth)
|
|
1034
|
+
scanned += 1
|
|
1035
|
+
break if scanned >= MAX_COLLECTION_SCAN
|
|
1036
|
+
end
|
|
1037
|
+
false
|
|
1038
|
+
end
|
|
1039
|
+
|
|
1040
|
+
def scan_hash?(state, hash, next_depth, stream)
|
|
1041
|
+
scanned = 0
|
|
1042
|
+
hash.each do |k, v|
|
|
1043
|
+
return true if check_candidate_store?(state, k, stream) || check_candidate_store?(state, v, stream)
|
|
1044
|
+
|
|
1045
|
+
if !state[:found_metric_store] && !state[:found_in_collection] &&
|
|
1046
|
+
(StreamGuard.entry_holds_stream?(k, stream) || StreamGuard.entry_holds_stream?(v, stream))
|
|
1047
|
+
state[:found_in_collection] = true
|
|
1048
|
+
end
|
|
1049
|
+
push_candidate?(state, k, next_depth)
|
|
1050
|
+
push_candidate?(state, v, next_depth)
|
|
1051
|
+
scanned += 1
|
|
1052
|
+
break if scanned >= MAX_COLLECTION_SCAN
|
|
1053
|
+
end
|
|
1054
|
+
false
|
|
1055
|
+
end
|
|
1056
|
+
end
|
|
1057
|
+
|
|
1058
|
+
# Bounded BFS pruner for pure duck-typed custom stores (those without a
|
|
1059
|
+
# backing SDK MetricStore), removing an orphaned stream from mutable
|
|
1060
|
+
# Array, Set, and Hash collections during instrument-creation rollback.
|
|
1061
|
+
class StreamPruner
|
|
1062
|
+
MAX_DEPTH = 16
|
|
1063
|
+
MAX_NODES = 512
|
|
1064
|
+
MAX_ENQUEUE = 512
|
|
1065
|
+
MAX_COLLECTION_SCAN = 4_096
|
|
1066
|
+
private_constant :MAX_DEPTH, :MAX_NODES, :MAX_ENQUEUE, :MAX_COLLECTION_SCAN
|
|
1067
|
+
|
|
1068
|
+
def initialize(store, stream)
|
|
1069
|
+
@store = store
|
|
1070
|
+
@stream = stream
|
|
1071
|
+
end
|
|
1072
|
+
|
|
1073
|
+
def prune
|
|
1074
|
+
store_mutex = @store.instance_variable_defined?(:@mutex) ? @store.instance_variable_get(:@mutex) : nil
|
|
1075
|
+
work = -> { walk }
|
|
1076
|
+
store_mutex.is_a?(Mutex) && !store_mutex.owned? ? store_mutex.synchronize(&work) : work.call
|
|
1077
|
+
end
|
|
1078
|
+
|
|
1079
|
+
private
|
|
1080
|
+
|
|
1081
|
+
def walk
|
|
1082
|
+
@visited = {}.compare_by_identity
|
|
1083
|
+
@enqueued = {}.compare_by_identity
|
|
1084
|
+
@enqueued[@store] = true
|
|
1085
|
+
@queue = [[@store, 0]]
|
|
1086
|
+
@budget = MAX_ENQUEUE
|
|
1087
|
+
while (entry = @queue.shift)
|
|
1088
|
+
node, depth = entry
|
|
1089
|
+
next if @visited.key?(node) || StreamGuard.scalar_leaf?(node) || StreamGuard.non_store_boundary?(node)
|
|
1090
|
+
next if @visited.size >= MAX_NODES
|
|
1091
|
+
|
|
1092
|
+
@visited[node] = true
|
|
1093
|
+
prune_collection(node)
|
|
1094
|
+
next if depth >= MAX_DEPTH || @budget <= 0
|
|
1095
|
+
|
|
1096
|
+
enqueue_children(node, depth + 1)
|
|
1097
|
+
end
|
|
1098
|
+
end
|
|
1099
|
+
|
|
1100
|
+
def prune_collection(node)
|
|
1101
|
+
return if node.frozen?
|
|
1102
|
+
|
|
1103
|
+
case node
|
|
1104
|
+
when Array
|
|
1105
|
+
prune_array(node)
|
|
1106
|
+
when Set
|
|
1107
|
+
prune_set(node)
|
|
1108
|
+
when Hash
|
|
1109
|
+
prune_hash(node)
|
|
1110
|
+
end
|
|
1111
|
+
end
|
|
1112
|
+
|
|
1113
|
+
def prune_array(list)
|
|
1114
|
+
idx = list.length - 1
|
|
1115
|
+
scanned = 0
|
|
1116
|
+
while idx >= 0 && scanned < MAX_COLLECTION_SCAN
|
|
1117
|
+
list.delete_at(idx) if StreamGuard.entry_holds_stream?(list[idx], @stream)
|
|
1118
|
+
idx -= 1
|
|
1119
|
+
scanned += 1
|
|
1120
|
+
end
|
|
1121
|
+
end
|
|
1122
|
+
|
|
1123
|
+
def prune_set(set)
|
|
1124
|
+
to_delete = []
|
|
1125
|
+
scanned = 0
|
|
1126
|
+
set.each do |elem|
|
|
1127
|
+
to_delete << elem if StreamGuard.entry_holds_stream?(elem, @stream)
|
|
1128
|
+
scanned += 1
|
|
1129
|
+
break if scanned >= MAX_COLLECTION_SCAN
|
|
1130
|
+
end
|
|
1131
|
+
to_delete.each { |elem| set.delete(elem) }
|
|
1132
|
+
end
|
|
1133
|
+
|
|
1134
|
+
def prune_hash(hash)
|
|
1135
|
+
to_delete = []
|
|
1136
|
+
scanned = 0
|
|
1137
|
+
hash.each do |k, v|
|
|
1138
|
+
to_delete << k if StreamGuard.entry_holds_stream?(k, @stream) || StreamGuard.entry_holds_stream?(v, @stream)
|
|
1139
|
+
scanned += 1
|
|
1140
|
+
break if scanned >= MAX_COLLECTION_SCAN
|
|
1141
|
+
end
|
|
1142
|
+
to_delete.each { |k| hash.delete(k) }
|
|
1143
|
+
end
|
|
1144
|
+
|
|
1145
|
+
def enqueue_children(node, next_depth)
|
|
1146
|
+
each_child_bounded(node) do |child|
|
|
1147
|
+
break if @budget <= 0
|
|
1148
|
+
next if @visited.key?(child) || @enqueued.key?(child) || StreamGuard.scalar_leaf?(child) || StreamGuard.non_store_boundary?(child)
|
|
1149
|
+
|
|
1150
|
+
@enqueued[child] = true
|
|
1151
|
+
@queue << [child, next_depth]
|
|
1152
|
+
@budget -= 1
|
|
1153
|
+
end
|
|
1154
|
+
end
|
|
1155
|
+
|
|
1156
|
+
def each_child_bounded(node, &block)
|
|
1157
|
+
case node
|
|
1158
|
+
when Array
|
|
1159
|
+
scanned = 0
|
|
1160
|
+
node.reverse_each do |elem|
|
|
1161
|
+
block.call(elem)
|
|
1162
|
+
scanned += 1
|
|
1163
|
+
break if scanned >= MAX_COLLECTION_SCAN
|
|
1164
|
+
end
|
|
1165
|
+
when Set
|
|
1166
|
+
scanned = 0
|
|
1167
|
+
node.each do |elem|
|
|
1168
|
+
block.call(elem)
|
|
1169
|
+
scanned += 1
|
|
1170
|
+
break if scanned >= MAX_COLLECTION_SCAN
|
|
1171
|
+
end
|
|
1172
|
+
when Hash
|
|
1173
|
+
scanned = 0
|
|
1174
|
+
node.each do |k, v|
|
|
1175
|
+
block.call(k)
|
|
1176
|
+
block.call(v)
|
|
1177
|
+
scanned += 1
|
|
1178
|
+
break if scanned >= MAX_COLLECTION_SCAN
|
|
1179
|
+
end
|
|
1180
|
+
when Struct
|
|
1181
|
+
node.each(&block)
|
|
1182
|
+
when Data
|
|
1183
|
+
node.deconstruct.each(&block)
|
|
1184
|
+
else
|
|
1185
|
+
node.instance_variables.each { |ivar| block.call(node.instance_variable_get(ivar)) }
|
|
1186
|
+
end
|
|
1187
|
+
end
|
|
1188
|
+
end
|
|
1189
|
+
|
|
1190
|
+
# Lightweight store proxy returned by IsolatedReader#metric_store so
|
|
1191
|
+
# accepted streams are recorded in the reader's WeakMap for concurrent
|
|
1192
|
+
# instrument/reader reconciliation, and streams added while
|
|
1193
|
+
# PolicyMeter#with_stream_rollback is active can be rolled back if a
|
|
1194
|
+
# sibling reader raises.
|
|
1195
|
+
class RecordStreamProxy
|
|
1196
|
+
def initialize(inner, known, lock, created)
|
|
1197
|
+
@inner = inner
|
|
1198
|
+
@known = known
|
|
1199
|
+
@lock = lock
|
|
1200
|
+
@created = created
|
|
1201
|
+
end
|
|
1202
|
+
|
|
1203
|
+
def add_metric_stream(stream)
|
|
1204
|
+
return nil if ReaderHelpers.aborted_stream?(stream)
|
|
1205
|
+
|
|
1206
|
+
@created&.push(StreamGuard::CreatedStream.new(stream, @inner, nil, nil, @known, @lock))
|
|
1207
|
+
completed = false
|
|
1208
|
+
begin
|
|
1209
|
+
result = @inner.add_metric_stream(stream)
|
|
1210
|
+
completed = true
|
|
1211
|
+
result
|
|
1212
|
+
ensure
|
|
1213
|
+
if ReaderHelpers.aborted_stream?(stream)
|
|
1214
|
+
ReaderHelpers.purge_aborted_stream(@inner, stream)
|
|
1215
|
+
elsif completed
|
|
1216
|
+
@lock.synchronize { @known[stream] = true }
|
|
1217
|
+
if ReaderHelpers.aborted_stream?(stream)
|
|
1218
|
+
@lock.synchronize { @known.delete(stream) }
|
|
1219
|
+
ReaderHelpers.purge_aborted_stream(@inner, stream)
|
|
1220
|
+
end
|
|
1221
|
+
end
|
|
1222
|
+
end
|
|
1223
|
+
end
|
|
1224
|
+
|
|
1225
|
+
def method_missing(name, ...)
|
|
1226
|
+
@inner.public_send(name, ...)
|
|
1227
|
+
end
|
|
1228
|
+
|
|
1229
|
+
def respond_to_missing?(name, include_private = false)
|
|
1230
|
+
@inner.respond_to?(name, include_private)
|
|
1231
|
+
end
|
|
1232
|
+
end
|
|
1233
|
+
|
|
1234
|
+
# Prepended onto metric readers registered with libo11y so MetricData
|
|
1235
|
+
# collected by both built-in and user-injected readers sanitizes
|
|
1236
|
+
# overflowing integers, BigDecimal, and Rational values before export.
|
|
1237
|
+
module SanitizedCollect
|
|
1238
|
+
def collect(...)
|
|
1239
|
+
Sanitize.sanitize_metrics(super)
|
|
1240
|
+
end
|
|
1241
|
+
end
|
|
1242
|
+
|
|
1243
|
+
# Wraps a PeriodicMetricReader's @exporter during shutdown so an error
|
|
1244
|
+
# in exporter#force_flush never prevents exporter#shutdown from running
|
|
1245
|
+
# on either base PeriodicMetricReader or subclasses calling super.
|
|
1246
|
+
class SafeShutdownExporter
|
|
1247
|
+
attr_reader :inner
|
|
1248
|
+
|
|
1249
|
+
def initialize(inner)
|
|
1250
|
+
@inner = inner
|
|
1251
|
+
@mutex = Mutex.new
|
|
1252
|
+
@first_failure = nil
|
|
1253
|
+
@worst_status = OpenTelemetry::SDK::Metrics::Export::SUCCESS
|
|
1254
|
+
@timeout_error = nil
|
|
1255
|
+
end
|
|
1256
|
+
|
|
1257
|
+
def first_failure
|
|
1258
|
+
@mutex.synchronize do
|
|
1259
|
+
return nil if @first_failure.nil?
|
|
1260
|
+
|
|
1261
|
+
error = @worst_status == OpenTelemetry::SDK::Metrics::Export::TIMEOUT ? (@timeout_error || @first_failure.first) : @first_failure.first
|
|
1262
|
+
[error, @worst_status].freeze
|
|
1263
|
+
end
|
|
1264
|
+
end
|
|
1265
|
+
|
|
1266
|
+
def force_flush(...)
|
|
1267
|
+
run_step(:force_flush, ...)
|
|
1268
|
+
end
|
|
1269
|
+
|
|
1270
|
+
def shutdown(...)
|
|
1271
|
+
run_step(:shutdown, ...)
|
|
1272
|
+
end
|
|
1273
|
+
|
|
1274
|
+
def respond_to_missing?(name, include_private = false)
|
|
1275
|
+
@inner.respond_to?(name, include_private)
|
|
1276
|
+
end
|
|
1277
|
+
|
|
1278
|
+
def method_missing(name, ...)
|
|
1279
|
+
@inner.public_send(name, ...)
|
|
1280
|
+
end
|
|
1281
|
+
|
|
1282
|
+
private
|
|
1283
|
+
|
|
1284
|
+
def run_step(step, ...)
|
|
1285
|
+
return OpenTelemetry::SDK::Metrics::Export::SUCCESS unless @inner.respond_to?(step)
|
|
1286
|
+
|
|
1287
|
+
code = Bridges.normalize_lifecycle_status(@inner.public_send(step, ...))
|
|
1288
|
+
if code == OpenTelemetry::SDK::Metrics::Export::TIMEOUT
|
|
1289
|
+
record_failure(Timeout::Error.new("the metrics #{step} timed out"), OpenTelemetry::SDK::Metrics::Export::TIMEOUT)
|
|
1290
|
+
elsif code != OpenTelemetry::SDK::Metrics::Export::SUCCESS
|
|
1291
|
+
record_failure(ExporterError.new("the metrics #{step} failed"), OpenTelemetry::SDK::Metrics::Export::FAILURE)
|
|
1292
|
+
end
|
|
1293
|
+
OpenTelemetry::SDK::Metrics::Export::SUCCESS
|
|
1294
|
+
rescue StandardError => e
|
|
1295
|
+
record_failure(e, Bridges.exception_lifecycle_status(e))
|
|
1296
|
+
OpenTelemetry::SDK::Metrics::Export::SUCCESS
|
|
1297
|
+
end
|
|
1298
|
+
|
|
1299
|
+
def record_failure(error, status)
|
|
1300
|
+
@mutex.synchronize do
|
|
1301
|
+
@first_failure = [error, status].freeze if @first_failure.nil?
|
|
1302
|
+
@worst_status = status if status > @worst_status
|
|
1303
|
+
@timeout_error = error if status == OpenTelemetry::SDK::Metrics::Export::TIMEOUT && @timeout_error.nil?
|
|
1304
|
+
end
|
|
1305
|
+
end
|
|
1306
|
+
end
|
|
1307
|
+
|
|
1308
|
+
# Prepended onto PeriodicMetricReader instances registered with libo11y
|
|
1309
|
+
# so rejected, timed-out, or raising exports on user-injected readers
|
|
1310
|
+
# propagate to Telemetry#force_flush and Telemetry#shutdown without
|
|
1311
|
+
# terminating the reader's background worker thread or skipping exporter
|
|
1312
|
+
# shutdown when exporter#force_flush raises.
|
|
1313
|
+
module ObservedPeriodicReader
|
|
1314
|
+
FLUSH_RESULT_KEY = :libo11y_periodic_export_result
|
|
1315
|
+
EXPORT_TRACK_KEY = :libo11y_periodic_export_track
|
|
1316
|
+
EXPORT_NONEMPTY_KEY = :libo11y_periodic_export_nonempty
|
|
1317
|
+
|
|
1318
|
+
def collect(...)
|
|
1319
|
+
metrics = super
|
|
1320
|
+
if Thread.current[EXPORT_TRACK_KEY]
|
|
1321
|
+
nonempty = metrics.respond_to?(:empty?) ? !metrics.empty? : !metrics.nil?
|
|
1322
|
+
Thread.current[EXPORT_NONEMPTY_KEY] ||= nonempty
|
|
1323
|
+
end
|
|
1324
|
+
metrics
|
|
1325
|
+
end
|
|
1326
|
+
|
|
1327
|
+
def force_flush(*args, **kwargs, &)
|
|
1328
|
+
prev = Thread.current[FLUSH_RESULT_KEY]
|
|
1329
|
+
slot = []
|
|
1330
|
+
Thread.current[FLUSH_RESULT_KEY] = slot
|
|
1331
|
+
begin
|
|
1332
|
+
super_meth = ObservedPeriodicReader.instance_method(:force_flush).bind(self).super_method
|
|
1333
|
+
raw_status = if drop_timeout_kwarg?(args, kwargs, super_meth)
|
|
1334
|
+
super(&)
|
|
1335
|
+
else
|
|
1336
|
+
super
|
|
1337
|
+
end
|
|
1338
|
+
status = Bridges.normalize_lifecycle_status(raw_status)
|
|
1339
|
+
failed = slot.reject { |code| code.nil? || (code.is_a?(Integer) && code == OpenTelemetry::SDK::Metrics::Export::SUCCESS) }
|
|
1340
|
+
return status if failed.empty?
|
|
1341
|
+
|
|
1342
|
+
slot_status = if failed.any? { |code| code.is_a?(Integer) && code == OpenTelemetry::SDK::Metrics::Export::TIMEOUT }
|
|
1343
|
+
OpenTelemetry::SDK::Metrics::Export::TIMEOUT
|
|
1344
|
+
else
|
|
1345
|
+
OpenTelemetry::SDK::Metrics::Export::FAILURE
|
|
1346
|
+
end
|
|
1347
|
+
[status, slot_status].max
|
|
1348
|
+
ensure
|
|
1349
|
+
Thread.current[FLUSH_RESULT_KEY] = prev
|
|
1350
|
+
end
|
|
1351
|
+
end
|
|
1352
|
+
|
|
1353
|
+
def shutdown(*args, **kwargs, &)
|
|
1354
|
+
super_meth = ObservedPeriodicReader.instance_method(:shutdown).bind(self).super_method
|
|
1355
|
+
wrapper = acquire_shutdown_wrapper
|
|
1356
|
+
begin
|
|
1357
|
+
raw_status = drop_timeout_kwarg?(args, kwargs, super_meth) ? super(&) : super
|
|
1358
|
+
ensure
|
|
1359
|
+
release_shutdown_wrapper(wrapper) if wrapper
|
|
1360
|
+
end
|
|
1361
|
+
status = Bridges.normalize_lifecycle_status(raw_status)
|
|
1362
|
+
first_error, first_status = wrapper&.first_failure
|
|
1363
|
+
return status unless first_error
|
|
1364
|
+
|
|
1365
|
+
@libo11y_export_failures&.record(first_error)
|
|
1366
|
+
OpenTelemetry.handle_error(exception: first_error, message: "Fail to shutdown PeriodicMetricReader.")
|
|
1367
|
+
[status, first_status || OpenTelemetry::SDK::Metrics::Export::FAILURE].max
|
|
1368
|
+
end
|
|
1369
|
+
|
|
1370
|
+
private
|
|
1371
|
+
|
|
1372
|
+
def raw_exporter
|
|
1373
|
+
@exporter.is_a?(SafeShutdownExporter) ? @exporter.inner : @exporter
|
|
1374
|
+
end
|
|
1375
|
+
|
|
1376
|
+
def acquire_shutdown_wrapper
|
|
1377
|
+
@libo11y_shutdown_lock.synchronize do
|
|
1378
|
+
exporter = @exporter
|
|
1379
|
+
return nil unless exporter
|
|
1380
|
+
|
|
1381
|
+
wrapper = exporter.is_a?(SafeShutdownExporter) ? exporter : SafeShutdownExporter.new(exporter)
|
|
1382
|
+
@exporter = wrapper
|
|
1383
|
+
@libo11y_shutdown_depth += 1
|
|
1384
|
+
wrapper
|
|
1385
|
+
end
|
|
1386
|
+
end
|
|
1387
|
+
|
|
1388
|
+
def release_shutdown_wrapper(wrapper)
|
|
1389
|
+
@libo11y_shutdown_lock.synchronize do
|
|
1390
|
+
@libo11y_shutdown_depth -= 1
|
|
1391
|
+
@exporter = wrapper.inner if @libo11y_shutdown_depth.zero? && @exporter.equal?(wrapper)
|
|
1392
|
+
end
|
|
1393
|
+
end
|
|
1394
|
+
|
|
1395
|
+
def drop_timeout_kwarg?(args, kwargs, super_meth)
|
|
1396
|
+
args.empty? && kwargs.size == 1 && kwargs.key?(:timeout) && !Bridges.method_takes_timeout?(super_meth)
|
|
1397
|
+
end
|
|
1398
|
+
|
|
1399
|
+
def export(timeout: nil)
|
|
1400
|
+
prev_track = Thread.current[EXPORT_TRACK_KEY]
|
|
1401
|
+
prev_nonempty = Thread.current[EXPORT_NONEMPTY_KEY]
|
|
1402
|
+
Thread.current[EXPORT_TRACK_KEY] = true
|
|
1403
|
+
Thread.current[EXPORT_NONEMPTY_KEY] = false
|
|
1404
|
+
result = begin
|
|
1405
|
+
super
|
|
1406
|
+
ensure
|
|
1407
|
+
nonempty = Thread.current[EXPORT_NONEMPTY_KEY]
|
|
1408
|
+
Thread.current[EXPORT_TRACK_KEY] = prev_track
|
|
1409
|
+
Thread.current[EXPORT_NONEMPTY_KEY] = prev_nonempty
|
|
1410
|
+
end
|
|
1411
|
+
result = OpenTelemetry::SDK::Metrics::Export::FAILURE if result.nil? && nonempty
|
|
1412
|
+
Thread.current[FLUSH_RESULT_KEY]&.push(result)
|
|
1413
|
+
record_observed_export_result(result)
|
|
1414
|
+
result
|
|
1415
|
+
rescue StandardError => e
|
|
1416
|
+
exporter = raw_exporter
|
|
1417
|
+
@libo11y_export_failures&.record(e) unless exporter.is_a?(ObservedExporter)
|
|
1418
|
+
OpenTelemetry.handle_error(exception: e, message: "libo11y: #{exporter.class} raised in export")
|
|
1419
|
+
status = Bridges.exception_lifecycle_status(e)
|
|
1420
|
+
Thread.current[FLUSH_RESULT_KEY]&.push(status)
|
|
1421
|
+
status
|
|
1422
|
+
end
|
|
1423
|
+
|
|
1424
|
+
def record_observed_export_result(result)
|
|
1425
|
+
failures = @libo11y_export_failures
|
|
1426
|
+
return if failures.nil? || raw_exporter.is_a?(ObservedExporter)
|
|
1427
|
+
return if result.nil? || (result.is_a?(Integer) && result == OpenTelemetry::SDK::Metrics::Export::SUCCESS)
|
|
1428
|
+
|
|
1429
|
+
error = if result.is_a?(Integer) && result == OpenTelemetry::SDK::Metrics::Export::TIMEOUT
|
|
1430
|
+
Timeout::Error.new("the metrics export timed out")
|
|
1431
|
+
else
|
|
1432
|
+
ExporterError.new("the metrics export failed")
|
|
1433
|
+
end
|
|
1434
|
+
failures.record(error)
|
|
1435
|
+
end
|
|
1436
|
+
end
|
|
1437
|
+
|
|
1438
|
+
# A metric reader as the handle's meter provider registers it. Its
|
|
1439
|
+
# shutdown and force_flush take the timeout the provider passes, also
|
|
1440
|
+
# when the reader's own take none, as the SDK's in-memory pull
|
|
1441
|
+
# exporter's do not. An error either raises is kept for the report and
|
|
1442
|
+
# answered with the SDK's failure code: the SDK's provider stops at
|
|
1443
|
+
# the first reader that raises, which would leave the others running.
|
|
1444
|
+
class IsolatedReader < SimpleDelegator
|
|
1445
|
+
include QuietInspect
|
|
1446
|
+
|
|
1447
|
+
class SingleAttachProxy
|
|
1448
|
+
def initialize(inner, captured)
|
|
1449
|
+
@inner = inner
|
|
1450
|
+
@captured = captured
|
|
1451
|
+
end
|
|
1452
|
+
|
|
1453
|
+
def add_metric_stream(stream)
|
|
1454
|
+
@captured << stream
|
|
1455
|
+
@inner.add_metric_stream(stream)
|
|
1456
|
+
end
|
|
1457
|
+
|
|
1458
|
+
def method_missing(name, ...)
|
|
1459
|
+
@inner.public_send(name, ...)
|
|
1460
|
+
end
|
|
1461
|
+
|
|
1462
|
+
def respond_to_missing?(name, include_private = false)
|
|
1463
|
+
@inner.respond_to?(name, include_private)
|
|
1464
|
+
end
|
|
1465
|
+
end
|
|
1466
|
+
private_constant :SingleAttachProxy
|
|
1467
|
+
|
|
1468
|
+
def initialize(reader, failures)
|
|
1469
|
+
super(reader)
|
|
1470
|
+
@failures = failures
|
|
1471
|
+
@stream_lock = Mutex.new
|
|
1472
|
+
@attach_mutex = Mutex.new
|
|
1473
|
+
@tracking_streams = false
|
|
1474
|
+
@attached_streams = {}.compare_by_identity
|
|
1475
|
+
@rejected_streams = {}.compare_by_identity
|
|
1476
|
+
@known_streams = ObjectSpace::WeakMap.new
|
|
1477
|
+
end
|
|
1478
|
+
|
|
1479
|
+
# @api private
|
|
1480
|
+
def start_tracking_streams!
|
|
1481
|
+
@stream_lock.synchronize { @tracking_streams = true }
|
|
1482
|
+
end
|
|
1483
|
+
|
|
1484
|
+
# @api private
|
|
1485
|
+
def stop_tracking_streams!
|
|
1486
|
+
@stream_lock.synchronize do
|
|
1487
|
+
@tracking_streams = false
|
|
1488
|
+
@attached_streams.clear
|
|
1489
|
+
@rejected_streams.clear
|
|
1490
|
+
end
|
|
1491
|
+
end
|
|
1492
|
+
|
|
1493
|
+
# @api private
|
|
1494
|
+
def clear_known_streams!
|
|
1495
|
+
@stream_lock.synchronize { @known_streams = ObjectSpace::WeakMap.new }
|
|
1496
|
+
end
|
|
1497
|
+
|
|
1498
|
+
# @api private
|
|
1499
|
+
def drop_streams!(streams)
|
|
1500
|
+
@stream_lock.synchronize do
|
|
1501
|
+
streams.each do |ms|
|
|
1502
|
+
@attached_streams.delete(ms)
|
|
1503
|
+
@rejected_streams.delete(ms)
|
|
1504
|
+
@known_streams.delete(ms)
|
|
1505
|
+
end
|
|
1506
|
+
end
|
|
1507
|
+
end
|
|
1508
|
+
|
|
1509
|
+
# @api private
|
|
1510
|
+
def attached_stream?(key)
|
|
1511
|
+
@stream_lock.synchronize { @attached_streams.key?(key) }
|
|
1512
|
+
end
|
|
1513
|
+
|
|
1514
|
+
# @api private
|
|
1515
|
+
def owns_stream?(stream)
|
|
1516
|
+
@stream_lock.synchronize { !@known_streams[stream].nil? }
|
|
1517
|
+
end
|
|
1518
|
+
|
|
1519
|
+
# @api private
|
|
1520
|
+
def tracks_instrument?(instrument)
|
|
1521
|
+
streams = instrument.instance_variable_get(:@metric_streams)
|
|
1522
|
+
streams.is_a?(Array) && @stream_lock.synchronize { streams.any? { |ms| !@known_streams[ms].nil? } }
|
|
1523
|
+
end
|
|
1524
|
+
|
|
1525
|
+
# @api private
|
|
1526
|
+
def attach_instrument_if_missing(instrument, config)
|
|
1527
|
+
@attach_mutex.synchronize do
|
|
1528
|
+
return false if tracks_instrument?(instrument)
|
|
1529
|
+
|
|
1530
|
+
captured = []
|
|
1531
|
+
proxy = SingleAttachProxy.new(metric_store, captured)
|
|
1532
|
+
completed = false
|
|
1533
|
+
begin
|
|
1534
|
+
instrument.register_with_new_metric_store(proxy, default_aggregation: config)
|
|
1535
|
+
completed = true
|
|
1536
|
+
ensure
|
|
1537
|
+
if !completed && !captured.empty?
|
|
1538
|
+
streams = instrument.instance_variable_get(:@metric_streams)
|
|
1539
|
+
streams.reject! { |ms| captured.any? { |candidate| candidate.equal?(ms) } && !owns_stream?(ms) } if streams.is_a?(Array)
|
|
1540
|
+
end
|
|
1541
|
+
end
|
|
1542
|
+
true
|
|
1543
|
+
end
|
|
1544
|
+
end
|
|
1545
|
+
|
|
1546
|
+
# @api private
|
|
1547
|
+
def drain_rejected_streams
|
|
1548
|
+
@stream_lock.synchronize do
|
|
1549
|
+
drained = @rejected_streams
|
|
1550
|
+
@rejected_streams = {}.compare_by_identity
|
|
1551
|
+
drained
|
|
1552
|
+
end
|
|
1553
|
+
end
|
|
1554
|
+
|
|
1555
|
+
def metric_store
|
|
1556
|
+
store = __getobj__.metric_store
|
|
1557
|
+
if @stream_lock.synchronize { @tracking_streams }
|
|
1558
|
+
return StreamGuard.new(store, @attached_streams, @rejected_streams, @stream_lock, known: @known_streams)
|
|
1559
|
+
end
|
|
1560
|
+
|
|
1561
|
+
RecordStreamProxy.new(store, @known_streams, @stream_lock, Thread.current[CREATING_STREAMS_KEY])
|
|
1562
|
+
end
|
|
1563
|
+
|
|
1564
|
+
def shutdown(timeout: nil)
|
|
1565
|
+
forward(:shutdown, timeout)
|
|
1566
|
+
end
|
|
1567
|
+
|
|
1568
|
+
def force_flush(timeout: nil)
|
|
1569
|
+
forward(:force_flush, timeout)
|
|
1570
|
+
end
|
|
1571
|
+
|
|
1572
|
+
private
|
|
1573
|
+
|
|
1574
|
+
def forward(name, timeout)
|
|
1575
|
+
reader = __getobj__
|
|
1576
|
+
return OpenTelemetry::SDK::Metrics::Export::SUCCESS unless reader.respond_to?(name)
|
|
1577
|
+
|
|
1578
|
+
Bridges.takes_timeout?(reader, name) ? reader.public_send(name, timeout: timeout) : reader.public_send(name)
|
|
1579
|
+
rescue StandardError => e
|
|
1580
|
+
@failures&.record(e)
|
|
1581
|
+
OpenTelemetry.handle_error(exception: e, message: "libo11y: #{reader.class} raised in #{name}")
|
|
1582
|
+
Bridges.exception_lifecycle_status(e)
|
|
1583
|
+
end
|
|
1584
|
+
end
|
|
1585
|
+
|
|
1586
|
+
# The handle's tracer provider. A span processor added to it, at the
|
|
1587
|
+
# start from the span_processors option or later by the application,
|
|
1588
|
+
# joins one group behind the policy: each gets a finished span that
|
|
1589
|
+
# holds classified data only, and a span's violations are counted once
|
|
1590
|
+
# however many processors there are.
|
|
1591
|
+
class PolicyTracerProvider < OpenTelemetry::SDK::Trace::TracerProvider
|
|
1592
|
+
include QuietInspect
|
|
1593
|
+
|
|
1594
|
+
# @param failures [ExportFailures] where a processor's error is kept
|
|
1595
|
+
# for the shutdown report
|
|
1596
|
+
def initialize(policy:, failures:, owner: nil, **)
|
|
1597
|
+
super(**)
|
|
1598
|
+
@group_policy = policy
|
|
1599
|
+
@failures = failures
|
|
1600
|
+
@owner = owner || self
|
|
1601
|
+
@group = nil
|
|
1602
|
+
@closed = false
|
|
1603
|
+
@group_lock = Mutex.new
|
|
1604
|
+
@owned_processors = []
|
|
1605
|
+
@coordinator = ReaderCoordinator.new(failures)
|
|
1606
|
+
end
|
|
1607
|
+
|
|
1608
|
+
def tracer(deprecated_name = nil, deprecated_version = nil, name: nil, version: nil, attributes: nil)
|
|
1609
|
+
snap_attrs = attributes.nil? ? nil : LogCapture.otel_safe_attr_map(attributes, snapshot: true)
|
|
1610
|
+
super(
|
|
1611
|
+
Bridges.snapshot_utf8(deprecated_name),
|
|
1612
|
+
Bridges.snapshot_utf8(deprecated_version),
|
|
1613
|
+
name: Bridges.snapshot_utf8(name),
|
|
1614
|
+
version: Bridges.snapshot_utf8(version),
|
|
1615
|
+
attributes: snap_attrs
|
|
1616
|
+
)
|
|
1617
|
+
end
|
|
1618
|
+
|
|
1619
|
+
# Registers a processor of libo11y's own, which classifies for itself.
|
|
1620
|
+
#
|
|
1621
|
+
# @api private
|
|
1622
|
+
def register(processor)
|
|
1623
|
+
OpenTelemetry::SDK::Trace::TracerProvider.instance_method(:add_span_processor).bind_call(self, processor)
|
|
1624
|
+
end
|
|
1625
|
+
|
|
1626
|
+
# Says that the export path counts a span's violations, so the group
|
|
1627
|
+
# of injected processors does not count them again.
|
|
1628
|
+
#
|
|
1629
|
+
# @api private
|
|
1630
|
+
def export_path_counts!
|
|
1631
|
+
@group_lock.synchronize { @group_policy = @group_policy.silent }
|
|
1632
|
+
end
|
|
1633
|
+
|
|
1634
|
+
# A processor added after the shutdown is refused with a warning,
|
|
1635
|
+
# as the SDK's provider refuses it: nothing would shut it down.
|
|
1636
|
+
def add_span_processor(processor)
|
|
1637
|
+
@group_lock.synchronize do
|
|
1638
|
+
next OpenTelemetry.logger.warn("libo11y: add_span_processor after shutdown, the processor is not added") if @closed
|
|
1639
|
+
next if @group&.include?(processor)
|
|
1640
|
+
|
|
1641
|
+
claimed = Ownership.claim_part!(processor, @owner, role: :traces_processor)
|
|
1642
|
+
if @group.nil?
|
|
1643
|
+
@group = PolicySpanProcessor.new([], @group_policy, @failures)
|
|
1644
|
+
register(@group)
|
|
1645
|
+
end
|
|
1646
|
+
@group.add(processor)
|
|
1647
|
+
@owned_processors << processor if claimed
|
|
1648
|
+
end
|
|
1649
|
+
nil
|
|
1650
|
+
end
|
|
1651
|
+
|
|
1652
|
+
def shutdown(timeout: nil)
|
|
1653
|
+
run_shutdown(timeout)
|
|
1654
|
+
end
|
|
1655
|
+
|
|
1656
|
+
# @api private
|
|
1657
|
+
def shutdown_in_flight?
|
|
1658
|
+
@coordinator.shutdown_in_flight?
|
|
1659
|
+
end
|
|
1660
|
+
|
|
1661
|
+
def force_flush(timeout: nil)
|
|
1662
|
+
procs = @mutex.synchronize { @stopped ? [] : @span_processors.dup }
|
|
1663
|
+
targets = procs.flat_map { |proc| proc.is_a?(ProcessorFanOut) ? proc.lifecycle_targets : [proc] }
|
|
1664
|
+
@coordinator.force_flush(targets, timeout)
|
|
1665
|
+
end
|
|
1666
|
+
|
|
1667
|
+
private
|
|
1668
|
+
|
|
1669
|
+
def run_shutdown(timeout)
|
|
1670
|
+
procs, owned = @group_lock.synchronize do
|
|
1671
|
+
@mutex.synchronize do
|
|
1672
|
+
if @closed || @stopped
|
|
1673
|
+
@closed = true
|
|
1674
|
+
OpenTelemetry.logger.warn("calling Tracer#shutdown multiple times.")
|
|
1675
|
+
return OpenTelemetry::SDK::Trace::Export::FAILURE
|
|
1676
|
+
end
|
|
1677
|
+
|
|
1678
|
+
@closed = true
|
|
1679
|
+
@stopped = true
|
|
1680
|
+
@coordinator.begin_shutdown!
|
|
1681
|
+
@span_processors.each { |proc| proc.mark_stopped! if proc.respond_to?(:mark_stopped!) }
|
|
1682
|
+
[@span_processors.dup, @owned_processors.dup]
|
|
1683
|
+
end
|
|
1684
|
+
end
|
|
1685
|
+
targets = procs.flat_map { |proc| proc.is_a?(ProcessorFanOut) ? proc.lifecycle_targets : [proc] }
|
|
1686
|
+
release = lambda do
|
|
1687
|
+
Ownership.release_parts(owned, @owner)
|
|
1688
|
+
@owner.release_signal(:traces) if @owner.respond_to?(:release_signal) && (!@owner.respond_to?(:handed?) || @owner.handed?(:traces))
|
|
1689
|
+
end
|
|
1690
|
+
@coordinator.shutdown(targets, timeout, on_all_done: release)
|
|
1691
|
+
end
|
|
1692
|
+
end
|
|
1693
|
+
|
|
1694
|
+
# The handle's logger provider. A log record processor added to it, at
|
|
1695
|
+
# the start or later by the application, joins one group that calls
|
|
1696
|
+
# each whatever another does: the SDK's provider stops a shutdown at
|
|
1697
|
+
# the first processor that raises.
|
|
1698
|
+
class QuietLoggerProvider < OpenTelemetry::SDK::Logs::LoggerProvider
|
|
1699
|
+
include QuietInspect
|
|
1700
|
+
|
|
1701
|
+
# @param failures [ExportFailures] where a processor's error is kept
|
|
1702
|
+
# for the shutdown report
|
|
1703
|
+
def initialize(failures: nil, owner: nil, **)
|
|
1704
|
+
super(**)
|
|
1705
|
+
@failures = failures
|
|
1706
|
+
@owner = owner || self
|
|
1707
|
+
@group = nil
|
|
1708
|
+
@closed = false
|
|
1709
|
+
@group_lock = Mutex.new
|
|
1710
|
+
@owned_processors = []
|
|
1711
|
+
@coordinator = ReaderCoordinator.new(failures)
|
|
1712
|
+
end
|
|
1713
|
+
|
|
1714
|
+
def logger(name:, version: nil)
|
|
1715
|
+
super(name: Bridges.snapshot_utf8(name), version: Bridges.snapshot_utf8(version))
|
|
1716
|
+
end
|
|
1717
|
+
|
|
1718
|
+
# Registers a processor of libo11y's own, outside the group.
|
|
1719
|
+
#
|
|
1720
|
+
# @api private
|
|
1721
|
+
def register(processor)
|
|
1722
|
+
OpenTelemetry::SDK::Logs::LoggerProvider.instance_method(:add_log_record_processor).bind_call(self, processor)
|
|
1723
|
+
end
|
|
1724
|
+
|
|
1725
|
+
# A processor added after the shutdown is refused with a warning,
|
|
1726
|
+
# as the SDK's provider refuses it.
|
|
1727
|
+
def add_log_record_processor(processor)
|
|
1728
|
+
@group_lock.synchronize do
|
|
1729
|
+
next OpenTelemetry.logger.warn("libo11y: add_log_record_processor after shutdown, the processor is not added") if @closed
|
|
1730
|
+
next if @group&.include?(processor)
|
|
1731
|
+
|
|
1732
|
+
claimed = Ownership.claim_part!(processor, @owner, role: :logs_processor)
|
|
1733
|
+
if @group.nil?
|
|
1734
|
+
@group = IsolatedLogProcessors.new([], @failures)
|
|
1735
|
+
register(@group)
|
|
1736
|
+
end
|
|
1737
|
+
target = if processor.is_a?(OpenTelemetry::SDK::Logs::Export::BatchLogRecordProcessor)
|
|
1738
|
+
SnapshotLogRecordProcessor.new(processor)
|
|
1739
|
+
else
|
|
1740
|
+
processor
|
|
1741
|
+
end
|
|
1742
|
+
@group.add(target)
|
|
1743
|
+
@owned_processors << processor if claimed
|
|
1744
|
+
end
|
|
1745
|
+
nil
|
|
1746
|
+
end
|
|
1747
|
+
|
|
1748
|
+
def shutdown(timeout: nil)
|
|
1749
|
+
run_shutdown(timeout)
|
|
1750
|
+
end
|
|
1751
|
+
|
|
1752
|
+
# @api private
|
|
1753
|
+
def shutdown_in_flight?
|
|
1754
|
+
@coordinator.shutdown_in_flight?
|
|
1755
|
+
end
|
|
1756
|
+
|
|
1757
|
+
def force_flush(timeout: nil)
|
|
1758
|
+
procs = @mutex.synchronize { @stopped ? [] : @log_record_processors.dup }
|
|
1759
|
+
targets = procs.flat_map { |proc| proc.is_a?(ProcessorFanOut) ? proc.lifecycle_targets : [proc] }
|
|
1760
|
+
@coordinator.force_flush(targets, timeout)
|
|
1761
|
+
end
|
|
1762
|
+
|
|
1763
|
+
private
|
|
1764
|
+
|
|
1765
|
+
def run_shutdown(timeout)
|
|
1766
|
+
procs, owned = @group_lock.synchronize do
|
|
1767
|
+
@mutex.synchronize do
|
|
1768
|
+
if @closed || @stopped
|
|
1769
|
+
@closed = true
|
|
1770
|
+
OpenTelemetry.logger.warn("LoggerProvider#shutdown called multiple times.")
|
|
1771
|
+
return OpenTelemetry::SDK::Logs::Export::FAILURE
|
|
1772
|
+
end
|
|
1773
|
+
|
|
1774
|
+
@closed = true
|
|
1775
|
+
@stopped = true
|
|
1776
|
+
@coordinator.begin_shutdown!
|
|
1777
|
+
@log_record_processors.each { |proc| proc.mark_stopped! if proc.respond_to?(:mark_stopped!) }
|
|
1778
|
+
[@log_record_processors.dup, @owned_processors.dup]
|
|
1779
|
+
end
|
|
1780
|
+
end
|
|
1781
|
+
targets = procs.flat_map { |proc| proc.is_a?(ProcessorFanOut) ? proc.lifecycle_targets : [proc] }
|
|
1782
|
+
release = lambda do
|
|
1783
|
+
Ownership.release_parts(owned, @owner)
|
|
1784
|
+
@owner.release_signal(:logs) if @owner.respond_to?(:release_signal) && (!@owner.respond_to?(:handed?) || @owner.handed?(:logs))
|
|
1785
|
+
end
|
|
1786
|
+
@coordinator.shutdown(targets, timeout, on_all_done: release)
|
|
1787
|
+
end
|
|
1788
|
+
|
|
1789
|
+
public
|
|
1790
|
+
|
|
1791
|
+
# Copies the caller's attributes before the SDK builds a LogRecord:
|
|
1792
|
+
# the SDK retains a plain Hash via to_h and trims it in place, which
|
|
1793
|
+
# mutates reusable hashes and raises FrozenError on frozen ones.
|
|
1794
|
+
# Carries the original hash identity via a private fiber-local so
|
|
1795
|
+
# cycle detection cuts self-referential top-level hashes without
|
|
1796
|
+
# exposing raw attributes in OpenTelemetry::Context or breaking
|
|
1797
|
+
# callers that pass context: nil.
|
|
1798
|
+
def on_emit(attributes: nil, context: OpenTelemetry::Context.current, **)
|
|
1799
|
+
source = !attributes.nil? && attributes.respond_to?(:to_h) ? attributes.to_h : nil
|
|
1800
|
+
copied = source ? source.dup : attributes
|
|
1801
|
+
PolicyLogRecordProcessor.with_original_attrs(source) do
|
|
1802
|
+
super(attributes: copied, context: context, **)
|
|
1803
|
+
end
|
|
1804
|
+
end
|
|
1805
|
+
end
|
|
1806
|
+
|
|
1807
|
+
# The log provider of a handle that OTEL_SDK_DISABLED switched off. A
|
|
1808
|
+
# processor added to it later is not registered, so nothing can switch
|
|
1809
|
+
# the export back on.
|
|
1810
|
+
class DisabledLoggerProvider < QuietLoggerProvider
|
|
1811
|
+
def add_log_record_processor(_processor)
|
|
1812
|
+
nil
|
|
1813
|
+
end
|
|
1814
|
+
end
|
|
1815
|
+
|
|
1816
|
+
# Coordinates per-reader serialization (via ReaderGate) with cross-reader
|
|
1817
|
+
# concurrency under a shared monotonic deadline for providers and fanouts.
|
|
1818
|
+
class ReaderCoordinator
|
|
1819
|
+
ReaderGate = Struct.new(:mutex, :cv, :busy, :stopped)
|
|
1820
|
+
private_constant :ReaderGate
|
|
1821
|
+
|
|
1822
|
+
def initialize(failures)
|
|
1823
|
+
@failures = failures
|
|
1824
|
+
@mutex = Mutex.new
|
|
1825
|
+
@gates = {}.compare_by_identity
|
|
1826
|
+
@shutdown_in_flight = false
|
|
1827
|
+
end
|
|
1828
|
+
|
|
1829
|
+
def begin_shutdown!
|
|
1830
|
+
@mutex.synchronize { @shutdown_in_flight = true }
|
|
1831
|
+
end
|
|
1832
|
+
|
|
1833
|
+
def shutdown_in_flight?
|
|
1834
|
+
@mutex.synchronize { @shutdown_in_flight }
|
|
1835
|
+
end
|
|
1836
|
+
|
|
1837
|
+
def shutdown(readers, timeout, deadline: nil, on_all_done: nil)
|
|
1838
|
+
finish = track_shutdown(on_all_done)
|
|
1839
|
+
if readers.empty?
|
|
1840
|
+
finish.call
|
|
1841
|
+
return OpenTelemetry::SDK::Metrics::Export::SUCCESS
|
|
1842
|
+
end
|
|
1843
|
+
|
|
1844
|
+
deadline = resolve_deadline(timeout, deadline)
|
|
1845
|
+
run_concurrently(readers, deadline, on_all_done: finish) do |reader|
|
|
1846
|
+
with_shutdown_gate(reader) do
|
|
1847
|
+
invoke_step(reader, :shutdown, step_timeout(deadline, timeout), deadline: deadline)
|
|
1848
|
+
end
|
|
1849
|
+
end
|
|
1850
|
+
end
|
|
1851
|
+
|
|
1852
|
+
def flush_and_shutdown(readers, timeout, deadline: nil, on_all_done: nil)
|
|
1853
|
+
finish = track_shutdown(on_all_done)
|
|
1854
|
+
if readers.empty?
|
|
1855
|
+
finish.call
|
|
1856
|
+
return OpenTelemetry::SDK::Metrics::Export::SUCCESS
|
|
1857
|
+
end
|
|
1858
|
+
|
|
1859
|
+
deadline = resolve_deadline(timeout, deadline)
|
|
1860
|
+
run_concurrently(readers, deadline, on_all_done: finish) do |reader|
|
|
1861
|
+
with_shutdown_gate(reader) do
|
|
1862
|
+
flush_status = if deadline && monotonic >= deadline
|
|
1863
|
+
OpenTelemetry::SDK::Metrics::Export::TIMEOUT
|
|
1864
|
+
else
|
|
1865
|
+
invoke_step(reader, :force_flush, step_timeout(deadline, timeout), deadline: deadline)
|
|
1866
|
+
end
|
|
1867
|
+
shutdown_status = invoke_step(reader, :shutdown, step_timeout(deadline, timeout), deadline: deadline)
|
|
1868
|
+
[flush_status, shutdown_status].grep(Integer).max || OpenTelemetry::SDK::Metrics::Export::SUCCESS
|
|
1869
|
+
end
|
|
1870
|
+
end
|
|
1871
|
+
end
|
|
1872
|
+
|
|
1873
|
+
def force_flush(readers, timeout, deadline: nil)
|
|
1874
|
+
return OpenTelemetry::SDK::Metrics::Export::SUCCESS if readers.empty?
|
|
1875
|
+
|
|
1876
|
+
deadline = resolve_deadline(timeout, deadline)
|
|
1877
|
+
return OpenTelemetry::SDK::Metrics::Export::TIMEOUT if deadline && monotonic >= deadline
|
|
1878
|
+
|
|
1879
|
+
run_concurrently(readers, deadline) do |reader|
|
|
1880
|
+
run_gated_flush(reader, timeout, deadline)
|
|
1881
|
+
end
|
|
1882
|
+
end
|
|
1883
|
+
|
|
1884
|
+
private
|
|
1885
|
+
|
|
1886
|
+
def track_shutdown(on_all_done)
|
|
1887
|
+
@mutex.synchronize { @shutdown_in_flight = true }
|
|
1888
|
+
lambda do
|
|
1889
|
+
@mutex.synchronize { @shutdown_in_flight = false }
|
|
1890
|
+
on_all_done&.call
|
|
1891
|
+
end
|
|
1892
|
+
end
|
|
1893
|
+
|
|
1894
|
+
def with_shutdown_gate(reader)
|
|
1895
|
+
g = gate(reader)
|
|
1896
|
+
g.mutex.synchronize do
|
|
1897
|
+
g.stopped = true
|
|
1898
|
+
g.cv.broadcast
|
|
1899
|
+
g.cv.wait(g.mutex) while g.busy
|
|
1900
|
+
g.busy = true
|
|
1901
|
+
end
|
|
1902
|
+
yield
|
|
1903
|
+
ensure
|
|
1904
|
+
g.mutex.synchronize do
|
|
1905
|
+
g.busy = false
|
|
1906
|
+
g.cv.broadcast
|
|
1907
|
+
end
|
|
1908
|
+
end
|
|
1909
|
+
|
|
1910
|
+
def run_gated_flush(reader, timeout, deadline)
|
|
1911
|
+
g = gate(reader)
|
|
1912
|
+
acquired = acquire_flush_gate(g, deadline)
|
|
1913
|
+
return acquired unless acquired == :acquired
|
|
1914
|
+
|
|
1915
|
+
begin
|
|
1916
|
+
invoke_step(reader, :force_flush, step_timeout(deadline, timeout), deadline: deadline)
|
|
1917
|
+
ensure
|
|
1918
|
+
g.mutex.synchronize do
|
|
1919
|
+
g.busy = false
|
|
1920
|
+
g.cv.broadcast
|
|
1921
|
+
end
|
|
1922
|
+
end
|
|
1923
|
+
end
|
|
1924
|
+
|
|
1925
|
+
def acquire_flush_gate(gate, deadline)
|
|
1926
|
+
gate.mutex.synchronize do
|
|
1927
|
+
while gate.busy && !gate.stopped
|
|
1928
|
+
if deadline
|
|
1929
|
+
rem = deadline - monotonic
|
|
1930
|
+
return OpenTelemetry::SDK::Metrics::Export::TIMEOUT if rem <= 0
|
|
1931
|
+
|
|
1932
|
+
gate.cv.wait(gate.mutex, rem)
|
|
1933
|
+
else
|
|
1934
|
+
gate.cv.wait(gate.mutex)
|
|
1935
|
+
end
|
|
1936
|
+
end
|
|
1937
|
+
return OpenTelemetry::SDK::Metrics::Export::SUCCESS if gate.stopped
|
|
1938
|
+
return OpenTelemetry::SDK::Metrics::Export::TIMEOUT if deadline && monotonic >= deadline
|
|
1939
|
+
|
|
1940
|
+
gate.busy = true
|
|
1941
|
+
:acquired
|
|
1942
|
+
end
|
|
1943
|
+
end
|
|
1944
|
+
|
|
1945
|
+
def resolve_deadline(timeout, deadline)
|
|
1946
|
+
return deadline if deadline
|
|
1947
|
+
|
|
1948
|
+
inherited = Thread.current[DEADLINE_KEY]
|
|
1949
|
+
return inherited if inherited
|
|
1950
|
+
|
|
1951
|
+
timeout ? monotonic + timeout : nil
|
|
1952
|
+
end
|
|
1953
|
+
|
|
1954
|
+
def gate(reader)
|
|
1955
|
+
@mutex.synchronize { @gates[reader] ||= ReaderGate.new(Mutex.new, ConditionVariable.new, false, false) }
|
|
1956
|
+
end
|
|
1957
|
+
|
|
1958
|
+
def monotonic
|
|
1959
|
+
Process.clock_gettime(Process::CLOCK_MONOTONIC)
|
|
1960
|
+
end
|
|
1961
|
+
|
|
1962
|
+
def step_timeout(deadline, initial_timeout)
|
|
1963
|
+
return initial_timeout if deadline.nil?
|
|
1964
|
+
|
|
1965
|
+
[deadline - monotonic, 0.001].max
|
|
1966
|
+
end
|
|
1967
|
+
|
|
1968
|
+
def run_concurrently(readers, deadline, on_all_done: nil)
|
|
1969
|
+
results = Array.new(readers.length)
|
|
1970
|
+
remaining_lock = Mutex.new
|
|
1971
|
+
remaining_count = readers.length
|
|
1972
|
+
threads = readers.each_with_index.map do |reader, idx|
|
|
1973
|
+
Thread.new do
|
|
1974
|
+
Thread.current[DEADLINE_KEY] = deadline
|
|
1975
|
+
results[idx] = yield reader
|
|
1976
|
+
ensure
|
|
1977
|
+
Thread.current[DEADLINE_KEY] = nil
|
|
1978
|
+
done = remaining_lock.synchronize do
|
|
1979
|
+
remaining_count -= 1
|
|
1980
|
+
remaining_count.zero?
|
|
1981
|
+
end
|
|
1982
|
+
on_all_done&.call if done
|
|
1983
|
+
end
|
|
1984
|
+
end
|
|
1985
|
+
timed_out = false
|
|
1986
|
+
threads.each do |thread|
|
|
1987
|
+
remaining = deadline ? [deadline - monotonic, 0].max : nil
|
|
1988
|
+
timed_out = true unless remaining ? thread.join(remaining) : thread.join
|
|
1989
|
+
end
|
|
1990
|
+
return OpenTelemetry::SDK::Metrics::Export::TIMEOUT if timed_out
|
|
1991
|
+
|
|
1992
|
+
results.grep(Integer).max || OpenTelemetry::SDK::Metrics::Export::SUCCESS
|
|
1993
|
+
end
|
|
1994
|
+
|
|
1995
|
+
def invoke_step(reader, step, timeout, deadline: nil)
|
|
1996
|
+
return OpenTelemetry::SDK::Metrics::Export::SUCCESS unless reader.respond_to?(step)
|
|
1997
|
+
|
|
1998
|
+
raw = if reader.is_a?(ProcessorFanOut) && !reader.is_a?(IsolatedSpanProcessor)
|
|
1999
|
+
reader.public_send(step, timeout: timeout, deadline: deadline)
|
|
2000
|
+
elsif Bridges.takes_timeout?(reader, step)
|
|
2001
|
+
reader.public_send(step, timeout: timeout)
|
|
2002
|
+
else
|
|
2003
|
+
reader.public_send(step)
|
|
2004
|
+
end
|
|
2005
|
+
Bridges.normalize_lifecycle_status(raw)
|
|
2006
|
+
rescue StandardError => e
|
|
2007
|
+
@failures&.record(e)
|
|
2008
|
+
OpenTelemetry.handle_error(exception: e, message: "Fail to #{step} #{reader.class}.")
|
|
2009
|
+
Bridges.exception_lifecycle_status(e)
|
|
2010
|
+
end
|
|
2011
|
+
end
|
|
2012
|
+
|
|
2013
|
+
# Stateless helpers for decorating, stopping, and cleaning up metric
|
|
2014
|
+
# readers attached to a PolicyMeterProvider.
|
|
2015
|
+
module ReaderHelpers
|
|
2016
|
+
ABORTED_STREAMS = ObjectSpace::WeakMap.new
|
|
2017
|
+
ABORTED_STREAMS_MUTEX = Mutex.new
|
|
2018
|
+
|
|
2019
|
+
module AbortedInstrument
|
|
2020
|
+
def register_with_new_metric_store(*, **) = nil
|
|
2021
|
+
end
|
|
2022
|
+
|
|
2023
|
+
class AbortedStreamSink < Array
|
|
2024
|
+
def <<(stream)
|
|
2025
|
+
ReaderHelpers.mark_aborted_streams!([stream])
|
|
2026
|
+
self
|
|
2027
|
+
end
|
|
2028
|
+
alias push <<
|
|
2029
|
+
end
|
|
2030
|
+
private_constant :ABORTED_STREAMS, :ABORTED_STREAMS_MUTEX, :AbortedInstrument, :AbortedStreamSink
|
|
2031
|
+
|
|
2032
|
+
module_function
|
|
2033
|
+
|
|
2034
|
+
def mark_aborted_streams!(streams)
|
|
2035
|
+
ABORTED_STREAMS_MUTEX.synchronize do
|
|
2036
|
+
streams.each { |ms| ABORTED_STREAMS[ms] = true if Ownership.weakmap_key?(ms) }
|
|
2037
|
+
end
|
|
2038
|
+
end
|
|
2039
|
+
|
|
2040
|
+
def aborted_stream?(stream)
|
|
2041
|
+
return false unless Ownership.weakmap_key?(stream)
|
|
2042
|
+
|
|
2043
|
+
ABORTED_STREAMS_MUTEX.synchronize { !ABORTED_STREAMS[stream].nil? }
|
|
2044
|
+
end
|
|
2045
|
+
|
|
2046
|
+
def purge_aborted_stream(store, stream)
|
|
2047
|
+
StreamGuard.prune_stream(store, stream)
|
|
2048
|
+
clear_stream_callbacks(stream)
|
|
2049
|
+
end
|
|
2050
|
+
|
|
2051
|
+
def periodic_reader_alive?(raw)
|
|
2052
|
+
raw.alive?
|
|
2053
|
+
rescue NoMethodError
|
|
2054
|
+
false
|
|
2055
|
+
end
|
|
2056
|
+
|
|
2057
|
+
def clear_dangling_meter_provider(raw, sdk_provider)
|
|
2058
|
+
return if raw.frozen?
|
|
2059
|
+
return unless raw.instance_variable_get(:@meter_provider).equal?(sdk_provider)
|
|
2060
|
+
|
|
2061
|
+
raw.instance_variable_set(:@meter_provider, nil)
|
|
2062
|
+
end
|
|
2063
|
+
|
|
2064
|
+
def ensure_sanitized_collect(raw)
|
|
2065
|
+
return unless raw.respond_to?(:collect) && !raw.frozen? && !raw.is_a?(SanitizedCollect)
|
|
2066
|
+
|
|
2067
|
+
raw.singleton_class.prepend(SanitizedCollect)
|
|
2068
|
+
end
|
|
2069
|
+
|
|
2070
|
+
def ensure_observed_periodic_reader(raw, failures)
|
|
2071
|
+
return unless raw.is_a?(OpenTelemetry::SDK::Metrics::Export::PeriodicMetricReader) && !raw.frozen?
|
|
2072
|
+
|
|
2073
|
+
raw.instance_variable_set(:@libo11y_export_failures, failures)
|
|
2074
|
+
return if raw.is_a?(ObservedPeriodicReader)
|
|
2075
|
+
|
|
2076
|
+
raw.instance_variable_set(:@libo11y_shutdown_lock, Mutex.new)
|
|
2077
|
+
raw.instance_variable_set(:@libo11y_shutdown_depth, 0)
|
|
2078
|
+
raw.singleton_class.prepend(ObservedPeriodicReader)
|
|
2079
|
+
end
|
|
2080
|
+
|
|
2081
|
+
def clear_observed_periodic_reader(raw)
|
|
2082
|
+
return unless raw.is_a?(ObservedPeriodicReader) && !raw.frozen?
|
|
2083
|
+
|
|
2084
|
+
raw.instance_variable_set(:@libo11y_export_failures, nil)
|
|
2085
|
+
end
|
|
2086
|
+
|
|
2087
|
+
def mark_inner_stopped_if_uncontended(sdk_provider)
|
|
2088
|
+
return if sdk_provider.instance_variable_get(:@stopped)
|
|
2089
|
+
|
|
2090
|
+
inner_mutex = sdk_provider.instance_variable_get(:@mutex)
|
|
2091
|
+
if inner_mutex.is_a?(Mutex)
|
|
2092
|
+
return unless inner_mutex.try_lock
|
|
2093
|
+
|
|
2094
|
+
begin
|
|
2095
|
+
sdk_provider.instance_variable_set(:@stopped, true)
|
|
2096
|
+
ensure
|
|
2097
|
+
inner_mutex.unlock
|
|
2098
|
+
end
|
|
2099
|
+
else
|
|
2100
|
+
sdk_provider.instance_variable_set(:@stopped, true)
|
|
2101
|
+
end
|
|
2102
|
+
end
|
|
2103
|
+
|
|
2104
|
+
def mark_inner_stopped_and_drop(sdk_provider, isolated)
|
|
2105
|
+
inner_mutex = sdk_provider.instance_variable_get(:@mutex)
|
|
2106
|
+
update = lambda do
|
|
2107
|
+
sdk_provider.instance_variable_set(:@stopped, true)
|
|
2108
|
+
sdk_provider.metric_readers.reject! { |known| known.equal?(isolated) }
|
|
2109
|
+
end
|
|
2110
|
+
inner_mutex.is_a?(Mutex) ? inner_mutex.synchronize(&update) : update.call
|
|
2111
|
+
end
|
|
2112
|
+
|
|
2113
|
+
def prune_rejected_streams(isolated, instruments)
|
|
2114
|
+
rejected = isolated.drain_rejected_streams
|
|
2115
|
+
return if rejected.empty?
|
|
2116
|
+
|
|
2117
|
+
instruments.each do |instrument|
|
|
2118
|
+
streams = instrument.instance_variable_get(:@metric_streams)
|
|
2119
|
+
streams.reject! { |ms| rejected.key?(ms) } if streams.is_a?(Array)
|
|
2120
|
+
end
|
|
2121
|
+
end
|
|
2122
|
+
|
|
2123
|
+
def detach_reader_streams(raw, isolated, instruments)
|
|
2124
|
+
store = safe_metric_store(raw)
|
|
2125
|
+
instruments.each do |instrument|
|
|
2126
|
+
streams = instrument.instance_variable_get(:@metric_streams)
|
|
2127
|
+
next unless streams.is_a?(Array)
|
|
2128
|
+
|
|
2129
|
+
removed = []
|
|
2130
|
+
streams.reject! do |ms|
|
|
2131
|
+
next false unless isolated.attached_stream?(ms) || isolated.owns_stream?(ms)
|
|
2132
|
+
|
|
2133
|
+
removed << ms
|
|
2134
|
+
true
|
|
2135
|
+
end
|
|
2136
|
+
removed.each { |ms| StreamGuard.prune_stream(store, ms) } if store
|
|
2137
|
+
end
|
|
2138
|
+
rescue StandardError
|
|
2139
|
+
nil
|
|
2140
|
+
end
|
|
2141
|
+
|
|
2142
|
+
def safe_metric_store(raw)
|
|
2143
|
+
raw.respond_to?(:metric_store) ? raw.metric_store : nil
|
|
2144
|
+
rescue StandardError
|
|
2145
|
+
nil
|
|
2146
|
+
end
|
|
2147
|
+
|
|
2148
|
+
def shutdown_rejected_reader(raw)
|
|
2149
|
+
clear_observed_periodic_reader(raw)
|
|
2150
|
+
IsolatedReader.new(raw, nil).shutdown(timeout: nil)
|
|
2151
|
+
end
|
|
2152
|
+
|
|
2153
|
+
def clear_stream_callbacks(stream)
|
|
2154
|
+
stream_mutex = stream.instance_variable_defined?(:@mutex) ? stream.instance_variable_get(:@mutex) : nil
|
|
2155
|
+
clear = lambda do
|
|
2156
|
+
%i[@callback @callbacks].each do |ivar|
|
|
2157
|
+
next unless stream.instance_variable_defined?(ivar)
|
|
2158
|
+
|
|
2159
|
+
cbs = stream.instance_variable_get(ivar)
|
|
2160
|
+
cbs.clear if cbs.is_a?(Array)
|
|
2161
|
+
end
|
|
2162
|
+
end
|
|
2163
|
+
stream_mutex.is_a?(Mutex) && !stream_mutex.owned? ? stream_mutex.synchronize(&clear) : clear.call
|
|
2164
|
+
end
|
|
2165
|
+
|
|
2166
|
+
def detach_aborted_instrument(active_readers, sdk_provider, instrument)
|
|
2167
|
+
instrument.singleton_class.prepend(AbortedInstrument) unless instrument.frozen? || instrument.is_a?(AbortedInstrument)
|
|
2168
|
+
streams = instrument.instance_variable_get(:@metric_streams)
|
|
2169
|
+
instrument.instance_variable_set(:@metric_streams, AbortedStreamSink.new) unless instrument.frozen?
|
|
2170
|
+
return unless streams.is_a?(Array) && !streams.empty?
|
|
2171
|
+
|
|
2172
|
+
mark_aborted_streams!(streams)
|
|
2173
|
+
readers = active_readers.dup
|
|
2174
|
+
sdk_provider.metric_readers.each { |reader| readers << reader if readers.none? { |known| known.equal?(reader) } }
|
|
2175
|
+
readers.each do |reader|
|
|
2176
|
+
store = safe_metric_store(Ownership.unwrap_reader(reader))
|
|
2177
|
+
streams.each { |ms| StreamGuard.prune_stream(store, ms) } if store
|
|
2178
|
+
reader.drop_streams!(streams) if reader.respond_to?(:drop_streams!)
|
|
2179
|
+
end
|
|
2180
|
+
streams.each { |ms| clear_stream_callbacks(ms) }
|
|
2181
|
+
streams.clear
|
|
2182
|
+
end
|
|
2183
|
+
|
|
2184
|
+
def cleanup_late_reader(raw:, isolated:, provider:, sdk_provider:, owner:, claimed_part:,
|
|
2185
|
+
attached:, failed: false, instruments: [], state: nil)
|
|
2186
|
+
should_stop = attached || (failed && claimed_part && raw.is_a?(OpenTelemetry::SDK::Metrics::Export::PeriodicMetricReader))
|
|
2187
|
+
begin
|
|
2188
|
+
state[:handled] = true if state
|
|
2189
|
+
mark_inner_stopped_and_drop(sdk_provider, isolated)
|
|
2190
|
+
detach_reader_streams(raw, isolated, instruments) if attached
|
|
2191
|
+
ensure
|
|
2192
|
+
isolated.stop_tracking_streams!
|
|
2193
|
+
isolated.clear_known_streams!
|
|
2194
|
+
clear_observed_periodic_reader(raw)
|
|
2195
|
+
shutdown_rejected_reader(raw) if should_stop
|
|
2196
|
+
clear_dangling_meter_provider(raw, sdk_provider) unless attached
|
|
2197
|
+
if attached
|
|
2198
|
+
Ownership.release_parts([raw], owner) if claimed_part
|
|
2199
|
+
else
|
|
2200
|
+
Ownership.release_reader(raw, provider, sdk_provider: sdk_provider, part_owner: owner, release_part: claimed_part)
|
|
2201
|
+
end
|
|
2202
|
+
OpenTelemetry.logger.warn("libo11y: add_metric_reader after shutdown, the reader is not added")
|
|
2203
|
+
end
|
|
2204
|
+
end
|
|
2205
|
+
|
|
2206
|
+
def cleanup_unattached_reader(raw:, isolated:, provider:, sdk_provider:, owner:, claimed_part:, stop_periodic: true)
|
|
2207
|
+
clear_dangling_meter_provider(raw, sdk_provider)
|
|
2208
|
+
isolated.stop_tracking_streams!
|
|
2209
|
+
isolated.clear_known_streams!
|
|
2210
|
+
clear_observed_periodic_reader(raw)
|
|
2211
|
+
shutdown_rejected_reader(raw) if stop_periodic && claimed_part && raw.is_a?(OpenTelemetry::SDK::Metrics::Export::PeriodicMetricReader)
|
|
2212
|
+
Ownership.release_reader(raw, provider, sdk_provider: sdk_provider, part_owner: owner, release_part: claimed_part)
|
|
2213
|
+
end
|
|
2214
|
+
|
|
2215
|
+
def attach_instruments(reader, instruments, stop_check)
|
|
2216
|
+
config = OpenTelemetry::SDK::Metrics::MeterProvider.reader_config(reader)
|
|
2217
|
+
instruments.each do |instrument|
|
|
2218
|
+
break if stop_check.call
|
|
2219
|
+
|
|
2220
|
+
streams = instrument.instance_variable_get(:@metric_streams)
|
|
2221
|
+
next if streams.is_a?(Array) && streams.any? { |ms| reader.attached_stream?(ms) || reader.owns_stream?(ms) }
|
|
2222
|
+
|
|
2223
|
+
reader.attach_instrument_if_missing(instrument, config)
|
|
2224
|
+
end
|
|
2225
|
+
end
|
|
2226
|
+
end
|
|
2227
|
+
|
|
2228
|
+
# Policy-enforcing MeterProvider wrapper: classifies attributes before SDK recording so
|
|
2229
|
+
# every derived View stream and every Exemplar receives filtered attributes (PII always dropped).
|
|
2230
|
+
class PolicyMeterProvider
|
|
2231
|
+
include QuietInspect
|
|
2232
|
+
|
|
2233
|
+
# @param disabled [Boolean] OTEL_SDK_DISABLED switched the SDK off,
|
|
2234
|
+
# so a reader added later is not registered
|
|
2235
|
+
# @param bucketed [Array<String>] the histograms libo11y has
|
|
2236
|
+
# registered a view for
|
|
2237
|
+
# @param views [Array<Hash>] the views of the views option
|
|
2238
|
+
# @param failures [ExportFailures] where a reader's error is kept
|
|
2239
|
+
# for the shutdown report
|
|
2240
|
+
def initialize(inner, policy, disabled: false, bucketed: [], views: [], failures: nil, owner: nil)
|
|
2241
|
+
@inner = inner
|
|
2242
|
+
@policy = policy
|
|
2243
|
+
@disabled = disabled
|
|
2244
|
+
@bucketed = bucketed
|
|
2245
|
+
@views = views.dup
|
|
2246
|
+
@failures = failures
|
|
2247
|
+
@owner = owner || self
|
|
2248
|
+
@mutex = Mutex.new
|
|
2249
|
+
@meters = {}
|
|
2250
|
+
@internal_instruments = []
|
|
2251
|
+
@readers = {}.compare_by_identity
|
|
2252
|
+
@partial_readers = {}.compare_by_identity
|
|
2253
|
+
@owned_late_readers = []
|
|
2254
|
+
@active_readers_mutex = Mutex.new
|
|
2255
|
+
@active_readers = []
|
|
2256
|
+
@partial_reader_set = {}.compare_by_identity
|
|
2257
|
+
@stopped_snapshot = false
|
|
2258
|
+
@coordinator = ReaderCoordinator.new(failures)
|
|
2259
|
+
@closed = false
|
|
2260
|
+
end
|
|
2261
|
+
|
|
2262
|
+
# @api private
|
|
2263
|
+
def closed?
|
|
2264
|
+
stopped = @active_readers_mutex.synchronize { @stopped_snapshot }
|
|
2265
|
+
ReaderHelpers.mark_inner_stopped_if_uncontended(@inner) if stopped
|
|
2266
|
+
stopped
|
|
2267
|
+
end
|
|
2268
|
+
|
|
2269
|
+
EMPTY_SCOPE_ATTRIBUTES = {}.freeze
|
|
2270
|
+
private_constant :EMPTY_SCOPE_ATTRIBUTES
|
|
2271
|
+
|
|
2272
|
+
def meter(name, version: nil, attributes: nil)
|
|
2273
|
+
if closed?
|
|
2274
|
+
OpenTelemetry.logger.warn("calling MeterProvider#meter after shutdown, a noop meter will be returned.")
|
|
2275
|
+
return OpenTelemetry::Metrics::Meter.new
|
|
2276
|
+
end
|
|
2277
|
+
safe_name = Bridges.snapshot_utf8(name)
|
|
2278
|
+
safe_version = Bridges.snapshot_utf8(version) || ""
|
|
2279
|
+
norm_attributes = if attributes.nil?
|
|
2280
|
+
EMPTY_SCOPE_ATTRIBUTES
|
|
2281
|
+
else
|
|
2282
|
+
LogCapture.otel_safe_attr_map(attributes, snapshot: true)
|
|
2283
|
+
end
|
|
2284
|
+
key = [safe_name, safe_version, norm_attributes]
|
|
2285
|
+
@mutex.synchronize do
|
|
2286
|
+
if @closed || closed? || @inner.instance_variable_get(:@stopped)
|
|
2287
|
+
OpenTelemetry.logger.warn("calling MeterProvider#meter after shutdown, a noop meter will be returned.")
|
|
2288
|
+
return OpenTelemetry::Metrics::Meter.new
|
|
2289
|
+
end
|
|
2290
|
+
|
|
2291
|
+
@meters[key] ||= PolicyMeter.new(
|
|
2292
|
+
@inner.meter(safe_name, version: safe_version, attributes: norm_attributes),
|
|
2293
|
+
@policy,
|
|
2294
|
+
provider: self
|
|
2295
|
+
)
|
|
2296
|
+
end
|
|
2297
|
+
end
|
|
2298
|
+
|
|
2299
|
+
# Registers an instrument built directly on @inner (such as
|
|
2300
|
+
# o11y.schema.violations) so a retried late reader attaches to it too.
|
|
2301
|
+
#
|
|
2302
|
+
# @api private
|
|
2303
|
+
def track_internal_instrument(instrument)
|
|
2304
|
+
@mutex.synchronize { @internal_instruments << instrument }
|
|
2305
|
+
end
|
|
2306
|
+
|
|
2307
|
+
# Attaches a newly created instrument to any fully registered reader
|
|
2308
|
+
# that completed late registration in the window between SDK instrument
|
|
2309
|
+
# registration and descriptor publication. Partial readers are skipped
|
|
2310
|
+
# and reconciled on retry.
|
|
2311
|
+
#
|
|
2312
|
+
# @api private
|
|
2313
|
+
def reconcile_instrument(instrument)
|
|
2314
|
+
snapshot_full_readers.each do |reader|
|
|
2315
|
+
break if closed?
|
|
2316
|
+
|
|
2317
|
+
config = OpenTelemetry::SDK::Metrics::MeterProvider.reader_config(reader)
|
|
2318
|
+
reader.attach_instrument_if_missing(instrument, config)
|
|
2319
|
+
end
|
|
2320
|
+
end
|
|
2321
|
+
|
|
2322
|
+
# @api private
|
|
2323
|
+
def detach_aborted_instrument(instrument)
|
|
2324
|
+
active = @active_readers_mutex.synchronize { @active_readers.dup }
|
|
2325
|
+
ReaderHelpers.detach_aborted_instrument(active, @inner, instrument)
|
|
2326
|
+
end
|
|
2327
|
+
|
|
2328
|
+
def add_metric_reader(reader)
|
|
2329
|
+
return nil if @disabled
|
|
2330
|
+
|
|
2331
|
+
if closed?
|
|
2332
|
+
OpenTelemetry.logger.warn("libo11y: add_metric_reader after shutdown, the reader is not added")
|
|
2333
|
+
return nil
|
|
2334
|
+
end
|
|
2335
|
+
|
|
2336
|
+
raw = Ownership.unwrap_reader(reader)
|
|
2337
|
+
@mutex.synchronize do
|
|
2338
|
+
if @closed || closed?
|
|
2339
|
+
@closed = true
|
|
2340
|
+
OpenTelemetry.logger.warn("libo11y: add_metric_reader after shutdown, the reader is not added")
|
|
2341
|
+
return nil
|
|
2342
|
+
end
|
|
2343
|
+
return nil if @readers[raw]
|
|
2344
|
+
|
|
2345
|
+
if (partial = @partial_readers[raw])
|
|
2346
|
+
attach_and_promote_reader(raw, partial)
|
|
2347
|
+
else
|
|
2348
|
+
register_new_reader(raw)
|
|
2349
|
+
end
|
|
2350
|
+
end
|
|
2351
|
+
nil
|
|
2352
|
+
end
|
|
2353
|
+
|
|
2354
|
+
# @api private
|
|
2355
|
+
def attached_reader?(reader)
|
|
2356
|
+
raw = Ownership.unwrap_reader(reader)
|
|
2357
|
+
@mutex.synchronize { @readers.key?(raw) || @partial_readers.key?(raw) }
|
|
2358
|
+
end
|
|
2359
|
+
|
|
2360
|
+
private
|
|
2361
|
+
|
|
2362
|
+
def register_new_reader(raw)
|
|
2363
|
+
if raw.is_a?(OpenTelemetry::SDK::Metrics::Export::PeriodicMetricReader) && !ReaderHelpers.periodic_reader_alive?(raw)
|
|
2364
|
+
raise ArgumentError, "libo11y: PeriodicMetricReader is already shut down"
|
|
2365
|
+
end
|
|
2366
|
+
|
|
2367
|
+
isolated = Ownership.reader_for_provider(raw, @failures)
|
|
2368
|
+
reg = { claimed: false, claimed_part: false, completed: false, handled: false }
|
|
2369
|
+
begin
|
|
2370
|
+
Ownership.claim_reader(raw, self, part_owner: @owner, sdk_provider: @inner, state: reg)
|
|
2371
|
+
ReaderHelpers.ensure_sanitized_collect(raw)
|
|
2372
|
+
ReaderHelpers.ensure_observed_periodic_reader(raw, @failures)
|
|
2373
|
+
isolated.start_tracking_streams!
|
|
2374
|
+
@inner.add_metric_reader(isolated)
|
|
2375
|
+
reg[:completed] = true
|
|
2376
|
+
attached = @inner.metric_readers.any? { |known| known.equal?(isolated) }
|
|
2377
|
+
unless attached
|
|
2378
|
+
cleanup_late_reader_after_shutdown(raw, isolated, reg[:claimed_part], attached: false, failed: false, state: reg)
|
|
2379
|
+
return nil
|
|
2380
|
+
end
|
|
2381
|
+
unless publish_active_reader(raw, isolated, reg[:claimed_part], state: reg)
|
|
2382
|
+
cleanup_late_reader_after_shutdown(raw, isolated, reg[:claimed_part], attached: true, failed: false, state: reg)
|
|
2383
|
+
return nil
|
|
2384
|
+
end
|
|
2385
|
+
ensure
|
|
2386
|
+
finalize_failed_reader_registration(raw, isolated, reg[:claimed_part], failed: !reg[:completed]) if reg[:claimed] && !reg[:handled]
|
|
2387
|
+
end
|
|
2388
|
+
attach_and_promote_reader(raw, isolated)
|
|
2389
|
+
end
|
|
2390
|
+
|
|
2391
|
+
def publish_active_reader(raw, isolated, claimed_part, state: nil)
|
|
2392
|
+
@active_readers_mutex.synchronize do
|
|
2393
|
+
return false if @stopped_snapshot
|
|
2394
|
+
|
|
2395
|
+
@owned_late_readers << raw if claimed_part
|
|
2396
|
+
@active_readers << isolated unless @active_readers.any? { |known| known.equal?(isolated) }
|
|
2397
|
+
@partial_reader_set[isolated] = true
|
|
2398
|
+
@partial_readers[raw] = isolated
|
|
2399
|
+
state[:handled] = true if state
|
|
2400
|
+
true
|
|
2401
|
+
end
|
|
2402
|
+
end
|
|
2403
|
+
|
|
2404
|
+
def attach_and_promote_reader(raw, reader)
|
|
2405
|
+
completed = false
|
|
2406
|
+
begin
|
|
2407
|
+
ReaderHelpers.attach_instruments(reader, tracked_instruments, -> { closed? })
|
|
2408
|
+
return nil if closed?
|
|
2409
|
+
|
|
2410
|
+
@active_readers_mutex.synchronize { @partial_reader_set.delete(reader) }
|
|
2411
|
+
ReaderHelpers.attach_instruments(reader, tracked_instruments, -> { closed? })
|
|
2412
|
+
return nil if closed?
|
|
2413
|
+
|
|
2414
|
+
@readers[raw] = true
|
|
2415
|
+
@partial_readers.delete(raw)
|
|
2416
|
+
reader.stop_tracking_streams!
|
|
2417
|
+
completed = true
|
|
2418
|
+
ensure
|
|
2419
|
+
unless completed
|
|
2420
|
+
ReaderHelpers.prune_rejected_streams(reader, tracked_instruments)
|
|
2421
|
+
if @readers[raw]
|
|
2422
|
+
@partial_readers.delete(raw)
|
|
2423
|
+
reader.stop_tracking_streams!
|
|
2424
|
+
elsif !closed?
|
|
2425
|
+
@active_readers_mutex.synchronize { @partial_reader_set[reader] = true }
|
|
2426
|
+
@partial_readers[raw] = reader
|
|
2427
|
+
end
|
|
2428
|
+
end
|
|
2429
|
+
end
|
|
2430
|
+
end
|
|
2431
|
+
|
|
2432
|
+
def finalize_failed_reader_registration(raw, isolated, claimed_part, failed: true)
|
|
2433
|
+
ReaderHelpers.prune_rejected_streams(isolated, tracked_instruments)
|
|
2434
|
+
attached = @inner.metric_readers.any? { |known| known.equal?(isolated) }
|
|
2435
|
+
if closed?
|
|
2436
|
+
cleanup_late_reader_after_shutdown(raw, isolated, claimed_part, attached: attached, failed: failed)
|
|
2437
|
+
elsif attached
|
|
2438
|
+
unless publish_active_reader(raw, isolated, claimed_part)
|
|
2439
|
+
cleanup_late_reader_after_shutdown(raw, isolated, claimed_part, attached: true, failed: failed)
|
|
2440
|
+
end
|
|
2441
|
+
else
|
|
2442
|
+
ReaderHelpers.cleanup_unattached_reader(
|
|
2443
|
+
raw: raw, isolated: isolated, provider: self, sdk_provider: @inner, owner: @owner, claimed_part: claimed_part, stop_periodic: failed
|
|
2444
|
+
)
|
|
2445
|
+
end
|
|
2446
|
+
end
|
|
2447
|
+
|
|
2448
|
+
def cleanup_late_reader_after_shutdown(raw, isolated, claimed_part, attached: true, failed: false, state: nil)
|
|
2449
|
+
@closed = true
|
|
2450
|
+
ReaderHelpers.cleanup_late_reader(
|
|
2451
|
+
raw: raw, isolated: isolated, provider: self, sdk_provider: @inner,
|
|
2452
|
+
owner: @owner, claimed_part: claimed_part, attached: attached, failed: failed, instruments: tracked_instruments, state: state
|
|
2453
|
+
)
|
|
2454
|
+
end
|
|
2455
|
+
|
|
2456
|
+
def tracked_instruments = @internal_instruments + @meters.values.flat_map(&:tracked_instruments)
|
|
2457
|
+
def shutdown(timeout: nil) = run_provider_shutdown(:shutdown, timeout)
|
|
2458
|
+
def shutdown_in_flight? = @coordinator.shutdown_in_flight?
|
|
2459
|
+
def flush_and_shutdown(timeout: nil) = run_provider_shutdown(:flush_and_shutdown, timeout)
|
|
2460
|
+
def force_flush(timeout: nil) = @coordinator.force_flush(snapshot_active_readers, timeout)
|
|
2461
|
+
|
|
2462
|
+
public :shutdown, :shutdown_in_flight?, :flush_and_shutdown, :force_flush
|
|
2463
|
+
|
|
2464
|
+
def run_provider_shutdown(method_name, timeout)
|
|
2465
|
+
readers = claim_readers_for_shutdown
|
|
2466
|
+
return OpenTelemetry::SDK::Metrics::Export::FAILURE if readers.nil?
|
|
2467
|
+
|
|
2468
|
+
@coordinator.public_send(method_name, readers, timeout, on_all_done: metrics_release_callback(readers))
|
|
2469
|
+
end
|
|
2470
|
+
|
|
2471
|
+
public
|
|
2472
|
+
|
|
2473
|
+
# Adds a view, under the rules of the views option. The SDK adds a
|
|
2474
|
+
# view's attribute_keys to every measurement of the instruments it
|
|
2475
|
+
# matches, after the meter has classified them, so they are
|
|
2476
|
+
# classified here.
|
|
2477
|
+
#
|
|
2478
|
+
# @raise [ArgumentError] for a view without one of the SDK's
|
|
2479
|
+
# aggregations, and for one that selects a histogram libo11y has
|
|
2480
|
+
# registered a view for. The SDK cannot take that view back, and
|
|
2481
|
+
# would write the histogram as two streams. Also for one that
|
|
2482
|
+
# Bridges.refuse_mixed_views refuses.
|
|
2483
|
+
def add_view(name, **)
|
|
2484
|
+
options = Bridges.classified_view({ ** }, @policy)
|
|
2485
|
+
# The name as the SDK will get it: nil selects by the other fields alone.
|
|
2486
|
+
taken = @bucketed.select { |histogram| HistogramBuckets.selected_by?(options.merge(name: name), histogram) }
|
|
2487
|
+
unless taken.empty?
|
|
2488
|
+
raise ArgumentError,
|
|
2489
|
+
"libo11y: #{taken.join(", ")} has a view already. Give this one in the views option, or its boundaries in histogram_buckets"
|
|
2490
|
+
end
|
|
2491
|
+
|
|
2492
|
+
named = options.merge(name: name)
|
|
2493
|
+
@mutex.synchronize do
|
|
2494
|
+
Bridges.refuse_mixed_views(named, @views)
|
|
2495
|
+
@inner.add_view(name, **options)
|
|
2496
|
+
@views << named
|
|
2497
|
+
end
|
|
2498
|
+
nil
|
|
2499
|
+
end
|
|
2500
|
+
|
|
2501
|
+
def resource = @inner.resource
|
|
2502
|
+
def metric_readers = @inner.metric_readers
|
|
2503
|
+
def exemplar_filter = @inner.exemplar_filter
|
|
2504
|
+
|
|
2505
|
+
private
|
|
2506
|
+
|
|
2507
|
+
def metrics_release_callback(readers)
|
|
2508
|
+
late = @active_readers_mutex.synchronize { @owned_late_readers.dup }
|
|
2509
|
+
lambda do
|
|
2510
|
+
ReaderHelpers.mark_inner_stopped_if_uncontended(@inner)
|
|
2511
|
+
readers.each do |reader|
|
|
2512
|
+
reader.stop_tracking_streams! if reader.respond_to?(:stop_tracking_streams!)
|
|
2513
|
+
reader.clear_known_streams! if reader.respond_to?(:clear_known_streams!)
|
|
2514
|
+
end
|
|
2515
|
+
Ownership.release_parts(late, @owner) unless late.empty?
|
|
2516
|
+
@owner.release_signal(:metrics) if @owner.respond_to?(:release_signal) && (!@owner.respond_to?(:handed?) || @owner.handed?(:metrics))
|
|
2517
|
+
end
|
|
2518
|
+
end
|
|
2519
|
+
|
|
2520
|
+
def claim_readers_for_shutdown
|
|
2521
|
+
readers = @active_readers_mutex.synchronize do
|
|
2522
|
+
if @stopped_snapshot || @inner.instance_variable_get(:@stopped)
|
|
2523
|
+
@stopped_snapshot = true
|
|
2524
|
+
OpenTelemetry.logger.warn("calling MetricProvider#shutdown multiple times.")
|
|
2525
|
+
return nil
|
|
2526
|
+
end
|
|
2527
|
+
|
|
2528
|
+
@stopped_snapshot = true
|
|
2529
|
+
@coordinator.begin_shutdown!
|
|
2530
|
+
@active_readers.dup
|
|
2531
|
+
end
|
|
2532
|
+
ReaderHelpers.mark_inner_stopped_if_uncontended(@inner)
|
|
2533
|
+
readers
|
|
2534
|
+
end
|
|
2535
|
+
|
|
2536
|
+
def snapshot_active_readers
|
|
2537
|
+
stopped, readers = @active_readers_mutex.synchronize { [@stopped_snapshot, @stopped_snapshot ? [] : @active_readers.dup] }
|
|
2538
|
+
ReaderHelpers.mark_inner_stopped_if_uncontended(@inner) if stopped
|
|
2539
|
+
readers
|
|
2540
|
+
end
|
|
2541
|
+
|
|
2542
|
+
def snapshot_full_readers
|
|
2543
|
+
@active_readers_mutex.synchronize do
|
|
2544
|
+
return [] if @stopped_snapshot
|
|
2545
|
+
|
|
2546
|
+
@active_readers.reject { |reader| @partial_reader_set.key?(reader) }
|
|
2547
|
+
end
|
|
2548
|
+
end
|
|
2549
|
+
end
|
|
2550
|
+
|
|
2551
|
+
class PolicyMeter
|
|
2552
|
+
include QuietInspect
|
|
2553
|
+
|
|
2554
|
+
def initialize(inner, policy, provider: nil)
|
|
2555
|
+
@inner = inner
|
|
2556
|
+
@policy = policy
|
|
2557
|
+
@provider = provider
|
|
2558
|
+
@mutex = Mutex.new
|
|
2559
|
+
@create_mutex = Mutex.new
|
|
2560
|
+
@instruments = {}.compare_by_identity
|
|
2561
|
+
end
|
|
2562
|
+
|
|
2563
|
+
# @api private
|
|
2564
|
+
def tracked_instruments
|
|
2565
|
+
@mutex.synchronize { @instruments.keys }
|
|
2566
|
+
end
|
|
2567
|
+
|
|
2568
|
+
# The factories take what the SDK meter's take and pass it on, so
|
|
2569
|
+
# that OpenTelemetry can upgrade an instrument that was created on
|
|
2570
|
+
# its proxy before setup: it calls them with exemplar_filter,
|
|
2571
|
+
# exemplar_reservoir and advisory.
|
|
2572
|
+
%i[create_counter create_up_down_counter create_gauge].each do |factory|
|
|
2573
|
+
define_method(factory) do |name, **options|
|
|
2574
|
+
safe_name = Bridges.snapshot_utf8(name)
|
|
2575
|
+
safe_options = scrub_instrument_options(options)
|
|
2576
|
+
instrument = with_stream_rollback(safe_name) do |state|
|
|
2577
|
+
inst = @inner.public_send(factory, safe_name, **safe_options)
|
|
2578
|
+
track_and_reconcile(inst, safe_name, state)
|
|
2579
|
+
inst
|
|
2580
|
+
end
|
|
2581
|
+
PolicySyncInstrument.new(instrument, @policy)
|
|
2582
|
+
end
|
|
2583
|
+
end
|
|
2584
|
+
|
|
2585
|
+
# Public on the SDK's meter, though not part of the OpenTelemetry API.
|
|
2586
|
+
# What it returns is wrapped as a factory's result is.
|
|
2587
|
+
def create_instrument(kind, name, unit, description, *rest)
|
|
2588
|
+
safe_name = Bridges.snapshot_utf8(name)
|
|
2589
|
+
safe_unit = Bridges.snapshot_utf8(unit)
|
|
2590
|
+
safe_desc = Bridges.snapshot_utf8(description)
|
|
2591
|
+
if kind == :histogram && rest.length >= 4 && rest[3].is_a?(Hash) && rest[3].key?(:explicit_bucket_boundaries)
|
|
2592
|
+
rest = rest.dup
|
|
2593
|
+
rest[3] = normalize_histogram_advisory({ advisory: rest[3] }, nil)[:advisory]
|
|
2594
|
+
end
|
|
2595
|
+
observable = kind.to_s.start_with?("observable")
|
|
2596
|
+
defer_cb = observable && @inner.is_a?(OpenTelemetry::SDK::Metrics::Meter) && !rest.empty?
|
|
2597
|
+
orig_cb = nil
|
|
2598
|
+
if defer_cb
|
|
2599
|
+
rest = rest.dup
|
|
2600
|
+
orig_cb = rest[0]
|
|
2601
|
+
rest[0] = nil
|
|
2602
|
+
end
|
|
2603
|
+
instrument = with_stream_rollback(safe_name) do |state|
|
|
2604
|
+
inst = @inner.create_instrument(kind, safe_name, safe_unit, safe_desc, *rest)
|
|
2605
|
+
was_new = track_and_reconcile(inst, safe_name, state)
|
|
2606
|
+
commit_observable_callbacks(inst, orig_cb, was_new, safe_name) if defer_cb && !orig_cb.nil?
|
|
2607
|
+
inst
|
|
2608
|
+
end
|
|
2609
|
+
wrapper = observable ? PolicyAsyncInstrument : PolicySyncInstrument
|
|
2610
|
+
wrapper.new(instrument, @policy)
|
|
2611
|
+
end
|
|
2612
|
+
|
|
2613
|
+
# explicit_bucket_boundaries is shorthand for the advisory of that name.
|
|
2614
|
+
# Note: opentelemetry-metrics-sdk 0.22 accepts advisory parameters but
|
|
2615
|
+
# does not apply them to histogram streams; configure views or
|
|
2616
|
+
# histogram_buckets to set custom boundaries.
|
|
2617
|
+
def create_histogram(name, explicit_bucket_boundaries: nil, **options)
|
|
2618
|
+
safe_name = Bridges.snapshot_utf8(name)
|
|
2619
|
+
options = scrub_instrument_options(options)
|
|
2620
|
+
options = normalize_histogram_advisory(options, explicit_bucket_boundaries)
|
|
2621
|
+
instrument = with_stream_rollback(safe_name) do |state|
|
|
2622
|
+
inst = @inner.create_histogram(safe_name, **options)
|
|
2623
|
+
track_and_reconcile(inst, safe_name, state)
|
|
2624
|
+
inst
|
|
2625
|
+
end
|
|
2626
|
+
PolicySyncInstrument.new(instrument, @policy)
|
|
2627
|
+
end
|
|
2628
|
+
|
|
2629
|
+
# An observable instrument's callbacks take no argument and return a
|
|
2630
|
+
# number, so its attributes come only through add_attributes and
|
|
2631
|
+
# observe, which the wrapper classifies.
|
|
2632
|
+
%i[create_observable_counter create_observable_up_down_counter create_observable_gauge].each do |factory|
|
|
2633
|
+
define_method(factory) do |name, **options|
|
|
2634
|
+
safe_name = Bridges.snapshot_utf8(name)
|
|
2635
|
+
safe_options = scrub_instrument_options(options)
|
|
2636
|
+
defer_cb = @inner.is_a?(OpenTelemetry::SDK::Metrics::Meter) && safe_options.key?(:callback)
|
|
2637
|
+
orig_cb = nil
|
|
2638
|
+
if defer_cb
|
|
2639
|
+
safe_options = safe_options.dup
|
|
2640
|
+
orig_cb = safe_options.delete(:callback)
|
|
2641
|
+
end
|
|
2642
|
+
instrument = with_stream_rollback(safe_name) do |state|
|
|
2643
|
+
inst = @inner.public_send(factory, safe_name, **safe_options)
|
|
2644
|
+
was_new = track_and_reconcile(inst, safe_name, state)
|
|
2645
|
+
commit_observable_callbacks(inst, orig_cb, was_new, safe_name) if defer_cb && !orig_cb.nil?
|
|
2646
|
+
inst
|
|
2647
|
+
end
|
|
2648
|
+
PolicyAsyncInstrument.new(instrument, @policy)
|
|
2649
|
+
end
|
|
2650
|
+
end
|
|
2651
|
+
|
|
2652
|
+
def method_missing(name, ...)
|
|
2653
|
+
@inner.public_send(name, ...)
|
|
2654
|
+
end
|
|
2655
|
+
|
|
2656
|
+
def respond_to_missing?(name, include_private = false)
|
|
2657
|
+
@inner.respond_to?(name, include_private)
|
|
2658
|
+
end
|
|
2659
|
+
|
|
2660
|
+
private
|
|
2661
|
+
|
|
2662
|
+
# Serializes instrument creation per meter and rolls back streams and
|
|
2663
|
+
# descriptors if creation raises or is interrupted before returning.
|
|
2664
|
+
def with_stream_rollback(name)
|
|
2665
|
+
@create_mutex.synchronize do
|
|
2666
|
+
prev = Thread.current[CREATING_STREAMS_KEY]
|
|
2667
|
+
created = []
|
|
2668
|
+
before_descs = snapshot_descriptors(name)
|
|
2669
|
+
state = { before_descs: before_descs, untrack: nil, clear_callbacks: true }
|
|
2670
|
+
committed = false
|
|
2671
|
+
Thread.current[CREATING_STREAMS_KEY] = created
|
|
2672
|
+
begin
|
|
2673
|
+
result = yield(state)
|
|
2674
|
+
committed = true
|
|
2675
|
+
result
|
|
2676
|
+
ensure
|
|
2677
|
+
Thread.current[CREATING_STREAMS_KEY] = prev
|
|
2678
|
+
unless committed
|
|
2679
|
+
untrack_aborted_instruments(name, before_descs, state[:untrack])
|
|
2680
|
+
rollback_created_streams(created, clear_callbacks: state[:clear_callbacks])
|
|
2681
|
+
end
|
|
2682
|
+
@provider&.closed?
|
|
2683
|
+
end
|
|
2684
|
+
end
|
|
2685
|
+
end
|
|
2686
|
+
|
|
2687
|
+
def rollback_created_streams(created, clear_callbacks:)
|
|
2688
|
+
ReaderHelpers.mark_aborted_streams!(created.map(&:stream)) if clear_callbacks && !created.empty?
|
|
2689
|
+
created.each do |entry|
|
|
2690
|
+
StreamGuard.prune_stream(entry.store, entry.stream)
|
|
2691
|
+
ReaderHelpers.clear_stream_callbacks(entry.stream) if clear_callbacks
|
|
2692
|
+
next unless entry.lock
|
|
2693
|
+
|
|
2694
|
+
entry.lock.synchronize do
|
|
2695
|
+
entry.attached&.delete(entry.stream)
|
|
2696
|
+
entry.rejected&.delete(entry.stream)
|
|
2697
|
+
entry.known&.delete(entry.stream)
|
|
2698
|
+
end
|
|
2699
|
+
end
|
|
2700
|
+
end
|
|
2701
|
+
|
|
2702
|
+
def commit_observable_callbacks(instrument, callback, was_new, name)
|
|
2703
|
+
if was_new
|
|
2704
|
+
streams = instrument.instance_variable_get(:@metric_streams)
|
|
2705
|
+
with_stream_mutexes(streams.is_a?(Array) ? streams : []) { instrument.init_callback(callback) }
|
|
2706
|
+
elsif !Array(callback).empty?
|
|
2707
|
+
OpenTelemetry.logger.warn(
|
|
2708
|
+
"repeated observable instrument creation with callbacks for instrument name '#{name}'. " \
|
|
2709
|
+
"Ignoring new callbacks. Use Meter#register_callback to add callbacks."
|
|
2710
|
+
)
|
|
2711
|
+
end
|
|
2712
|
+
end
|
|
2713
|
+
|
|
2714
|
+
def with_stream_mutexes(streams, index = 0, &block)
|
|
2715
|
+
while index < streams.length
|
|
2716
|
+
stream = streams[index]
|
|
2717
|
+
index += 1
|
|
2718
|
+
mutex = stream.instance_variable_defined?(:@mutex) ? stream.instance_variable_get(:@mutex) : nil
|
|
2719
|
+
next unless mutex.is_a?(Mutex) && !mutex.owned?
|
|
2720
|
+
|
|
2721
|
+
return mutex.synchronize { with_stream_mutexes(streams, index, &block) }
|
|
2722
|
+
end
|
|
2723
|
+
block.call
|
|
2724
|
+
end
|
|
2725
|
+
|
|
2726
|
+
def track_and_reconcile(instrument, name, state)
|
|
2727
|
+
return false unless instrument.respond_to?(:register_with_new_metric_store) && instrument.respond_to?(:instrument_kind)
|
|
2728
|
+
|
|
2729
|
+
preexisting = state[:before_descs].key?(instrument)
|
|
2730
|
+
was_new = @mutex.synchronize do
|
|
2731
|
+
fresh = !preexisting && !@instruments.key?(instrument)
|
|
2732
|
+
@instruments[instrument] = true
|
|
2733
|
+
fresh
|
|
2734
|
+
end
|
|
2735
|
+
if was_new
|
|
2736
|
+
state[:untrack] = [instrument, name]
|
|
2737
|
+
else
|
|
2738
|
+
state[:clear_callbacks] = false
|
|
2739
|
+
end
|
|
2740
|
+
@provider&.reconcile_instrument(instrument) if was_new
|
|
2741
|
+
was_new
|
|
2742
|
+
end
|
|
2743
|
+
|
|
2744
|
+
def descriptor_key(name)
|
|
2745
|
+
name.respond_to?(:downcase) ? name.downcase : name.to_s.downcase
|
|
2746
|
+
end
|
|
2747
|
+
|
|
2748
|
+
def snapshot_descriptors(name)
|
|
2749
|
+
known = {}.compare_by_identity
|
|
2750
|
+
return known unless @inner.is_a?(OpenTelemetry::SDK::Metrics::Meter)
|
|
2751
|
+
|
|
2752
|
+
meter_mutex = @inner.instance_variable_get(:@mutex)
|
|
2753
|
+
collect = lambda do
|
|
2754
|
+
descriptors = @inner.instance_variable_get(:@instrument_descriptors)
|
|
2755
|
+
list = descriptors.is_a?(Hash) ? descriptors[descriptor_key(name)] : nil
|
|
2756
|
+
list.each { |desc| known[desc.instrument] = true } if list.is_a?(Array)
|
|
2757
|
+
end
|
|
2758
|
+
meter_mutex.is_a?(Mutex) ? meter_mutex.synchronize(&collect) : collect.call
|
|
2759
|
+
known
|
|
2760
|
+
end
|
|
2761
|
+
|
|
2762
|
+
def untrack_aborted_instruments(name, before_descs, tracked)
|
|
2763
|
+
aborted = []
|
|
2764
|
+
aborted << tracked.first if tracked && !before_descs.key?(tracked.first)
|
|
2765
|
+
if @inner.is_a?(OpenTelemetry::SDK::Metrics::Meter)
|
|
2766
|
+
meter_mutex = @inner.instance_variable_get(:@mutex)
|
|
2767
|
+
remove = lambda do
|
|
2768
|
+
descriptors = @inner.instance_variable_get(:@instrument_descriptors)
|
|
2769
|
+
next unless descriptors.is_a?(Hash)
|
|
2770
|
+
|
|
2771
|
+
key = descriptor_key(name)
|
|
2772
|
+
list = descriptors[key]
|
|
2773
|
+
next unless list.is_a?(Array)
|
|
2774
|
+
|
|
2775
|
+
kept = list.reject do |desc|
|
|
2776
|
+
fresh = !before_descs.key?(desc.instrument)
|
|
2777
|
+
aborted << desc.instrument if fresh && aborted.none? { |inst| inst.equal?(desc.instrument) }
|
|
2778
|
+
fresh
|
|
2779
|
+
end
|
|
2780
|
+
kept.empty? ? descriptors.delete(key) : descriptors[key] = kept
|
|
2781
|
+
end
|
|
2782
|
+
meter_mutex.is_a?(Mutex) ? meter_mutex.synchronize(&remove) : remove.call
|
|
2783
|
+
end
|
|
2784
|
+
@mutex.synchronize { aborted.each { |inst| @instruments.delete(inst) } }
|
|
2785
|
+
aborted.each { |inst| @provider&.detach_aborted_instrument(inst) }
|
|
2786
|
+
end
|
|
2787
|
+
|
|
2788
|
+
def scrub_instrument_options(options)
|
|
2789
|
+
return options unless options.key?(:unit) || options.key?(:description)
|
|
2790
|
+
|
|
2791
|
+
out = options.dup
|
|
2792
|
+
out[:unit] = Bridges.snapshot_utf8(out[:unit]) if out.key?(:unit)
|
|
2793
|
+
out[:description] = Bridges.snapshot_utf8(out[:description]) if out.key?(:description)
|
|
2794
|
+
out
|
|
2795
|
+
end
|
|
2796
|
+
|
|
2797
|
+
def normalize_histogram_advisory(options, explicit_bucket_boundaries)
|
|
2798
|
+
if !explicit_bucket_boundaries.nil?
|
|
2799
|
+
raw_bounds = explicit_bucket_boundaries
|
|
2800
|
+
source = "explicit_bucket_boundaries"
|
|
2801
|
+
elsif options[:advisory].is_a?(Hash) && options[:advisory].key?(:explicit_bucket_boundaries)
|
|
2802
|
+
raw_bounds = options[:advisory][:explicit_bucket_boundaries]
|
|
2803
|
+
source = "advisory.explicit_bucket_boundaries"
|
|
2804
|
+
else
|
|
2805
|
+
return options
|
|
2806
|
+
end
|
|
2807
|
+
|
|
2808
|
+
bounds = Bridges.normalize_histogram_boundaries(raw_bounds, source: source)
|
|
2809
|
+
base_advisory = options[:advisory].is_a?(Hash) ? options[:advisory] : {}
|
|
2810
|
+
options.merge(advisory: base_advisory.merge(explicit_bucket_boundaries: bounds))
|
|
2811
|
+
rescue ArgumentError => e
|
|
2812
|
+
OpenTelemetry.handle_error(message: "libo11y: ignoring invalid #{e.message.delete_prefix("libo11y: ")}")
|
|
2813
|
+
advisory = options[:advisory].is_a?(Hash) ? options[:advisory].except(:explicit_bucket_boundaries) : nil
|
|
2814
|
+
advisory ? options.merge(advisory: advisory) : options
|
|
2815
|
+
end
|
|
2816
|
+
end
|
|
2817
|
+
|
|
2818
|
+
# Wraps an observable instrument so the attributes it is given are
|
|
2819
|
+
# classified before the SDK records them.
|
|
2820
|
+
class PolicyAsyncInstrument
|
|
2821
|
+
include QuietInspect
|
|
2822
|
+
|
|
2823
|
+
def initialize(inner, policy)
|
|
2824
|
+
@inner = inner
|
|
2825
|
+
@policy = policy
|
|
2826
|
+
end
|
|
2827
|
+
|
|
2828
|
+
def add_attributes(attributes)
|
|
2829
|
+
@inner.add_attributes(@policy.classify_metric_attrs(attributes))
|
|
2830
|
+
end
|
|
2831
|
+
|
|
2832
|
+
def observe(timeout: nil, attributes: {})
|
|
2833
|
+
@inner.observe(timeout: timeout, attributes: @policy.classify_metric_attrs(attributes))
|
|
2834
|
+
end
|
|
2835
|
+
|
|
2836
|
+
def method_missing(name, ...)
|
|
2837
|
+
@inner.public_send(name, ...)
|
|
2838
|
+
end
|
|
2839
|
+
|
|
2840
|
+
def respond_to_missing?(name, include_private = false)
|
|
2841
|
+
@inner.respond_to?(name, include_private)
|
|
2842
|
+
end
|
|
2843
|
+
end
|
|
2844
|
+
|
|
2845
|
+
class PolicySyncInstrument
|
|
2846
|
+
include QuietInspect
|
|
2847
|
+
|
|
2848
|
+
def initialize(inner, policy)
|
|
2849
|
+
@inner = inner
|
|
2850
|
+
@policy = policy
|
|
2851
|
+
end
|
|
2852
|
+
|
|
2853
|
+
def add(increment, attributes: {})
|
|
2854
|
+
@inner.add(increment, attributes: @policy.classify_metric_attrs(attributes))
|
|
2855
|
+
end
|
|
2856
|
+
|
|
2857
|
+
def record(amount, attributes: {})
|
|
2858
|
+
@inner.record(amount, attributes: @policy.classify_metric_attrs(attributes))
|
|
2859
|
+
end
|
|
2860
|
+
|
|
2861
|
+
def method_missing(name, ...)
|
|
2862
|
+
@inner.public_send(name, ...)
|
|
2863
|
+
end
|
|
2864
|
+
|
|
2865
|
+
def respond_to_missing?(name, include_private = false)
|
|
2866
|
+
@inner.respond_to?(name, include_private)
|
|
2867
|
+
end
|
|
2868
|
+
end
|
|
2869
|
+
|
|
2870
|
+
# Cycle-safe, bounded UTF-8 and OTLP int64 value scrubbing helpers.
|
|
2871
|
+
module Sanitize
|
|
2872
|
+
# Stays well below google-protobuf's 100-frame nesting limit even for
|
|
2873
|
+
# nested Hashes (3 protobuf frames per Ruby Hash level).
|
|
2874
|
+
MAX_SCRUB_DEPTH = PII::MAX_COMPOSITE_DEPTH
|
|
2875
|
+
private_constant :MAX_SCRUB_DEPTH
|
|
2876
|
+
|
|
2877
|
+
module_function
|
|
2878
|
+
|
|
2879
|
+
def scrub_otel_value(value, active: {}.compare_by_identity, homogeneous_arrays: false, depth: 0, budget: [PII::MAX_COMPOSITE_NODES])
|
|
2880
|
+
case value
|
|
2881
|
+
when String
|
|
2882
|
+
SensitivityPolicy.utf8_safe(value)
|
|
2883
|
+
when Integer
|
|
2884
|
+
value.between?(SensitivityPolicy::INT64_MIN, SensitivityPolicy::INT64_MAX) ? value : value.to_s
|
|
2885
|
+
when Hash
|
|
2886
|
+
scrub_hash(value, active: active, homogeneous_arrays: homogeneous_arrays, depth: depth, budget: budget)
|
|
2887
|
+
when Array
|
|
2888
|
+
scrub_array(value, active: active, homogeneous_arrays: homogeneous_arrays, depth: depth, budget: budget)
|
|
2889
|
+
else
|
|
2890
|
+
value
|
|
2891
|
+
end
|
|
2892
|
+
end
|
|
2893
|
+
|
|
2894
|
+
def scrub_hash(hash, active:, homogeneous_arrays:, depth:, budget:)
|
|
2895
|
+
return {} if depth >= MAX_SCRUB_DEPTH
|
|
2896
|
+
|
|
2897
|
+
budget[0] -= 1
|
|
2898
|
+
return {} if budget[0].negative?
|
|
2899
|
+
|
|
2900
|
+
changed = false
|
|
2901
|
+
active[hash] = true
|
|
2902
|
+
begin
|
|
2903
|
+
out = {}
|
|
2904
|
+
hash.each do |k, v|
|
|
2905
|
+
budget[0] -= 1
|
|
2906
|
+
if budget[0].negative?
|
|
2907
|
+
changed = true
|
|
2908
|
+
break
|
|
2909
|
+
end
|
|
2910
|
+
if (v.is_a?(Hash) || v.is_a?(Array)) && active.key?(v)
|
|
2911
|
+
changed = true
|
|
2912
|
+
next
|
|
2913
|
+
end
|
|
2914
|
+
nk = k.is_a?(String) ? SensitivityPolicy.utf8_safe(k) : k
|
|
2915
|
+
nv = scrub_otel_value(v, active: active, homogeneous_arrays: homogeneous_arrays, depth: depth + 1, budget: budget)
|
|
2916
|
+
changed = true unless nk.equal?(k) && nv.equal?(v)
|
|
2917
|
+
out[nk] = nv
|
|
2918
|
+
end
|
|
2919
|
+
changed ? out : hash
|
|
2920
|
+
ensure
|
|
2921
|
+
active.delete(hash)
|
|
2922
|
+
end
|
|
2923
|
+
end
|
|
2924
|
+
|
|
2925
|
+
def scrub_array(list, active:, homogeneous_arrays:, depth:, budget:)
|
|
2926
|
+
return [] if depth >= MAX_SCRUB_DEPTH
|
|
2927
|
+
|
|
2928
|
+
budget[0] -= 1
|
|
2929
|
+
return [] if budget[0].negative?
|
|
2930
|
+
|
|
2931
|
+
changed = false
|
|
2932
|
+
active[list] = true
|
|
2933
|
+
begin
|
|
2934
|
+
out = []
|
|
2935
|
+
list.each do |el|
|
|
2936
|
+
budget[0] -= 1
|
|
2937
|
+
if budget[0].negative?
|
|
2938
|
+
changed = true
|
|
2939
|
+
break
|
|
2940
|
+
end
|
|
2941
|
+
if (el.is_a?(Hash) || el.is_a?(Array)) && active.key?(el)
|
|
2942
|
+
changed = true
|
|
2943
|
+
next
|
|
2944
|
+
end
|
|
2945
|
+
nel = scrub_otel_value(el, active: active, homogeneous_arrays: homogeneous_arrays, depth: depth + 1, budget: budget)
|
|
2946
|
+
changed = true unless nel.equal?(el)
|
|
2947
|
+
out << nel
|
|
2948
|
+
end
|
|
2949
|
+
if homogeneous_arrays && out.any?(String) && !out.all?(String)
|
|
2950
|
+
changed = true
|
|
2951
|
+
out = out.map { |el| SensitivityPolicy.utf8_safe(el.to_s) }
|
|
2952
|
+
end
|
|
2953
|
+
changed ? out : list
|
|
2954
|
+
ensure
|
|
2955
|
+
active.delete(list)
|
|
2956
|
+
end
|
|
2957
|
+
end
|
|
2958
|
+
|
|
2959
|
+
# Sanitizes MetricData before OTLP protobuf encoding so out-of-range
|
|
2960
|
+
# signed int64, BigDecimal, or Rational data-point, histogram, or
|
|
2961
|
+
# exemplar values encode as OTLP doubles instead of raising RangeError
|
|
2962
|
+
# or Google::Protobuf::TypeError and dropping the whole metrics batch.
|
|
2963
|
+
def sanitize_metrics(metrics)
|
|
2964
|
+
return metrics unless metrics.is_a?(Array)
|
|
2965
|
+
|
|
2966
|
+
changed = false
|
|
2967
|
+
sanitized = metrics.map do |metric_data|
|
|
2968
|
+
updated = sanitize_metric_data(metric_data)
|
|
2969
|
+
changed = true unless updated.equal?(metric_data)
|
|
2970
|
+
updated
|
|
2971
|
+
end
|
|
2972
|
+
changed ? sanitized : metrics
|
|
2973
|
+
end
|
|
2974
|
+
|
|
2975
|
+
def sanitize_metric_data(metric_data)
|
|
2976
|
+
return metric_data unless metric_data.respond_to?(:data_points)
|
|
2977
|
+
|
|
2978
|
+
points = metric_data.data_points
|
|
2979
|
+
return metric_data if points.nil? || points.empty?
|
|
2980
|
+
|
|
2981
|
+
changed = false
|
|
2982
|
+
sanitized = points.map do |point|
|
|
2983
|
+
updated = sanitize_data_point(point)
|
|
2984
|
+
changed = true unless updated.equal?(point)
|
|
2985
|
+
updated
|
|
2986
|
+
end
|
|
2987
|
+
return metric_data unless changed
|
|
2988
|
+
|
|
2989
|
+
copy = metric_data.dup
|
|
2990
|
+
copy.data_points = sanitized
|
|
2991
|
+
copy
|
|
2992
|
+
end
|
|
2993
|
+
|
|
2994
|
+
def sanitize_data_point(data_point)
|
|
2995
|
+
val_changed = data_point.respond_to?(:value) && coerce_number?(data_point.value)
|
|
2996
|
+
hist_changed = histogram_fields_need_coercion?(data_point)
|
|
2997
|
+
exemplars = data_point.respond_to?(:exemplars) ? data_point.exemplars : nil
|
|
2998
|
+
new_exemplars, ex_changed = sanitize_exemplars(exemplars)
|
|
2999
|
+
return data_point unless val_changed || hist_changed || ex_changed
|
|
3000
|
+
|
|
3001
|
+
copy = data_point.dup
|
|
3002
|
+
copy.value = data_point.value.to_f if val_changed
|
|
3003
|
+
coerce_histogram_fields!(copy) if hist_changed
|
|
3004
|
+
copy.exemplars = new_exemplars if ex_changed
|
|
3005
|
+
copy
|
|
3006
|
+
end
|
|
3007
|
+
|
|
3008
|
+
def sanitize_exemplars(exemplars)
|
|
3009
|
+
return [exemplars, false] if exemplars.nil? || exemplars.empty?
|
|
3010
|
+
|
|
3011
|
+
changed = false
|
|
3012
|
+
updated = exemplars.map do |ex|
|
|
3013
|
+
val_changed = coerce_number?(ex.value)
|
|
3014
|
+
attrs = ex.filtered_attributes
|
|
3015
|
+
scrubbed = attrs ? LogCapture.otel_safe_attr_map(attrs) : attrs
|
|
3016
|
+
attrs_changed = !scrubbed.equal?(attrs)
|
|
3017
|
+
if val_changed || attrs_changed
|
|
3018
|
+
changed = true
|
|
3019
|
+
copy = ex.dup
|
|
3020
|
+
copy.value = ex.value.to_f if val_changed
|
|
3021
|
+
copy.filtered_attributes = scrubbed if attrs_changed
|
|
3022
|
+
copy
|
|
3023
|
+
else
|
|
3024
|
+
ex
|
|
3025
|
+
end
|
|
3026
|
+
end
|
|
3027
|
+
[updated, changed]
|
|
3028
|
+
end
|
|
3029
|
+
|
|
3030
|
+
def coerce_number?(value)
|
|
3031
|
+
return false if value.is_a?(Float)
|
|
3032
|
+
return !value.between?(SensitivityPolicy::INT64_MIN, SensitivityPolicy::INT64_MAX) if value.is_a?(Integer)
|
|
3033
|
+
|
|
3034
|
+
value.is_a?(Numeric) && value.real?
|
|
3035
|
+
end
|
|
3036
|
+
|
|
3037
|
+
def histogram_fields_need_coercion?(data_point)
|
|
3038
|
+
return false unless data_point.respond_to?(:sum=)
|
|
3039
|
+
|
|
3040
|
+
return true if %i[sum min max].any? { |field| coerce_number?(data_point.public_send(field)) }
|
|
3041
|
+
return true if data_point.respond_to?(:zero_threshold=) && coerce_number?(data_point.zero_threshold)
|
|
3042
|
+
|
|
3043
|
+
explicit_bounds_need_coercion?(data_point)
|
|
3044
|
+
end
|
|
3045
|
+
|
|
3046
|
+
def explicit_bounds_need_coercion?(data_point)
|
|
3047
|
+
return false unless data_point.respond_to?(:explicit_bounds=) && data_point.explicit_bounds.is_a?(Array)
|
|
3048
|
+
|
|
3049
|
+
bounds = data_point.explicit_bounds
|
|
3050
|
+
bounds.any? { |bound| coerce_number?(bound) } || bounds.each_cons(2).any? { |prev, curr| prev.to_f >= curr.to_f }
|
|
3051
|
+
end
|
|
3052
|
+
|
|
3053
|
+
def coerce_histogram_fields!(copy)
|
|
3054
|
+
%i[sum min max].each do |field|
|
|
3055
|
+
val = copy.public_send(field)
|
|
3056
|
+
copy.public_send(:"#{field}=", val.to_f) if coerce_number?(val)
|
|
3057
|
+
end
|
|
3058
|
+
copy.zero_threshold = copy.zero_threshold.to_f if copy.respond_to?(:zero_threshold=) && coerce_number?(copy.zero_threshold)
|
|
3059
|
+
coerce_explicit_bounds!(copy)
|
|
3060
|
+
end
|
|
3061
|
+
|
|
3062
|
+
def coerce_explicit_bounds!(copy)
|
|
3063
|
+
return unless explicit_bounds_need_coercion?(copy)
|
|
3064
|
+
|
|
3065
|
+
coerced = copy.explicit_bounds.map(&:to_f)
|
|
3066
|
+
counts = copy.respond_to?(:bucket_counts=) && copy.bucket_counts.is_a?(Array) ? copy.bucket_counts : nil
|
|
3067
|
+
unless counts && counts.length == coerced.length + 1
|
|
3068
|
+
copy.explicit_bounds = coerced
|
|
3069
|
+
return
|
|
3070
|
+
end
|
|
3071
|
+
|
|
3072
|
+
merged_bounds = []
|
|
3073
|
+
merged_counts = [counts.first]
|
|
3074
|
+
coerced.each_with_index do |bound, idx|
|
|
3075
|
+
if !merged_bounds.empty? && bound <= merged_bounds.last
|
|
3076
|
+
# Fold the collapsed interval (prev, bound] into the inclusive
|
|
3077
|
+
# bucket <= prev, and advance the upper bucket to counts[idx + 1].
|
|
3078
|
+
merged_counts[-2] += merged_counts[-1]
|
|
3079
|
+
merged_counts[-1] = counts[idx + 1]
|
|
3080
|
+
else
|
|
3081
|
+
merged_bounds << bound
|
|
3082
|
+
merged_counts << counts[idx + 1]
|
|
3083
|
+
end
|
|
3084
|
+
end
|
|
3085
|
+
copy.explicit_bounds = merged_bounds
|
|
3086
|
+
copy.bucket_counts = merged_counts
|
|
3087
|
+
end
|
|
3088
|
+
end
|
|
3089
|
+
|
|
3090
|
+
module_function
|
|
3091
|
+
|
|
3092
|
+
def scrub_utf8(value)
|
|
3093
|
+
value.is_a?(String) ? SensitivityPolicy.utf8_safe(value) : Sanitize.scrub_otel_value(value)
|
|
3094
|
+
end
|
|
3095
|
+
|
|
3096
|
+
def snapshot_utf8(value)
|
|
3097
|
+
safe = scrub_utf8(value)
|
|
3098
|
+
safe.is_a?(String) && !safe.frozen? ? safe.dup.freeze : safe
|
|
3099
|
+
end
|
|
3100
|
+
|
|
3101
|
+
def scrub_otel_value(value, homogeneous_arrays: false)
|
|
3102
|
+
Sanitize.scrub_otel_value(value, homogeneous_arrays: homogeneous_arrays)
|
|
3103
|
+
end
|
|
3104
|
+
|
|
3105
|
+
# Validates and normalizes explicit histogram bucket boundaries to finite,
|
|
3106
|
+
# strictly increasing Float values (sorting first, matching upstream
|
|
3107
|
+
# ExplicitBucketHistogram) so recording-time bucket assignment matches
|
|
3108
|
+
# OTLP protobuf double explicit_bounds.
|
|
3109
|
+
#
|
|
3110
|
+
# @raise [ArgumentError]
|
|
3111
|
+
def normalize_histogram_boundaries(boundaries, source: "histogram_buckets")
|
|
3112
|
+
unless boundaries.is_a?(Array)
|
|
3113
|
+
raise ArgumentError, "libo11y: #{source} boundaries must be an Array of finite real numbers, got #{boundaries.inspect}"
|
|
3114
|
+
end
|
|
3115
|
+
|
|
3116
|
+
floats = boundaries.map do |bound|
|
|
3117
|
+
unless bound.is_a?(Numeric) && bound.real?
|
|
3118
|
+
raise ArgumentError, "libo11y: #{source} boundaries must be finite real numbers, got #{bound.inspect}"
|
|
3119
|
+
end
|
|
3120
|
+
|
|
3121
|
+
f = bound.to_f
|
|
3122
|
+
raise ArgumentError, "libo11y: #{source} boundaries must be finite real numbers, got #{bound.inspect}" unless f.finite?
|
|
3123
|
+
|
|
3124
|
+
f
|
|
3125
|
+
end.sort
|
|
3126
|
+
floats.each_cons(2) do |prev, curr|
|
|
3127
|
+
next if prev < curr
|
|
3128
|
+
|
|
3129
|
+
raise ArgumentError, "libo11y: #{source} boundaries must remain strictly increasing as floats"
|
|
3130
|
+
end
|
|
3131
|
+
floats
|
|
3132
|
+
end
|
|
3133
|
+
|
|
3134
|
+
def normalize_view_aggregation!(aggregation)
|
|
3135
|
+
if aggregation.is_a?(OpenTelemetry::SDK::Metrics::Aggregation::ExplicitBucketHistogram)
|
|
3136
|
+
raw_bounds = aggregation.instance_variable_get(:@boundaries)
|
|
3137
|
+
return unless raw_bounds
|
|
3138
|
+
|
|
3139
|
+
floats = normalize_histogram_boundaries(raw_bounds, source: "view aggregation")
|
|
3140
|
+
return unless raw_bounds.any? { |b| !b.is_a?(Float) } || floats != raw_bounds
|
|
3141
|
+
|
|
3142
|
+
aggregation.instance_variable_set(:@boundaries, floats)
|
|
3143
|
+
reservoir = aggregation.instance_variable_get(:@exemplar_reservoir)
|
|
3144
|
+
if reservoir.is_a?(OpenTelemetry::SDK::Metrics::Exemplar::AlignedHistogramBucketExemplarReservoir)
|
|
3145
|
+
reservoir.instance_variable_set(:@boundaries, floats)
|
|
3146
|
+
end
|
|
3147
|
+
elsif aggregation.is_a?(OpenTelemetry::SDK::Metrics::Aggregation::ExponentialBucketHistogram)
|
|
3148
|
+
zt = aggregation.instance_variable_get(:@zero_threshold)
|
|
3149
|
+
f = zt.is_a?(Numeric) && zt.real? ? zt.to_f : Float::NAN
|
|
3150
|
+
unless f.finite? && f >= 0
|
|
3151
|
+
raise ArgumentError, "libo11y: view aggregation zero_threshold must be a finite non-negative number, got #{zt.inspect}"
|
|
3152
|
+
end
|
|
3153
|
+
|
|
3154
|
+
aggregation.instance_variable_set(:@zero_threshold, f) unless zt.is_a?(Float)
|
|
3155
|
+
end
|
|
3156
|
+
end
|
|
3157
|
+
|
|
3158
|
+
# A view's options, checked, with its attribute_keys classified as
|
|
3159
|
+
# metric attributes are: a secret or PII key is dropped. The SDK adds
|
|
3160
|
+
# those attributes to every measurement the view matches, after the
|
|
3161
|
+
# meter has classified the measurement's own.
|
|
3162
|
+
#
|
|
3163
|
+
# @raise [ArgumentError] for an aggregation that is not one of the
|
|
3164
|
+
# SDK's, through which the SDK would record nothing, for explicit
|
|
3165
|
+
# histogram boundaries that are not finite and strictly increasing as
|
|
3166
|
+
# floats, and for attribute_keys that do not convert to a Hash
|
|
3167
|
+
def classified_view(options, policy)
|
|
3168
|
+
aggregation = options[:aggregation]
|
|
3169
|
+
unless aggregation.class.name.to_s.rpartition("::").first == "OpenTelemetry::SDK::Metrics::Aggregation"
|
|
3170
|
+
raise ArgumentError, "libo11y: a view needs an :aggregation from OpenTelemetry::SDK::Metrics::Aggregation, got #{aggregation.inspect}"
|
|
3171
|
+
end
|
|
3172
|
+
|
|
3173
|
+
normalize_view_aggregation!(aggregation)
|
|
3174
|
+
return options if options[:attribute_keys].nil?
|
|
3175
|
+
|
|
3176
|
+
# The SDK takes anything that converts to a Hash.
|
|
3177
|
+
keys = Hash.try_convert(options[:attribute_keys])
|
|
3178
|
+
raise ArgumentError, "libo11y: a view's attribute_keys must be a Hash, got #{options[:attribute_keys].class}" if keys.nil?
|
|
3179
|
+
|
|
3180
|
+
options.merge(attribute_keys: policy.classify_metric_attrs(keys))
|
|
3181
|
+
end
|
|
3182
|
+
|
|
3183
|
+
# Whether an object's method takes a timeout keyword. Most shutdown
|
|
3184
|
+
# and force_flush methods do. The SDK's in-memory pull exporter is one
|
|
3185
|
+
# whose do not.
|
|
3186
|
+
def takes_timeout?(object, name) = method_takes_timeout?(object.method(name))
|
|
3187
|
+
|
|
3188
|
+
def method_takes_timeout?(meth)
|
|
3189
|
+
return false if meth.nil?
|
|
3190
|
+
|
|
3191
|
+
# A keyword, not a positional parameter that happens to be named timeout.
|
|
3192
|
+
meth.parameters.any? { |kind, parameter| kind == :keyrest || (%i[key keyreq].include?(kind) && parameter == :timeout) }
|
|
3193
|
+
end
|
|
3194
|
+
|
|
3195
|
+
# Normalizes a lifecycle return value (force_flush / shutdown) to an OTel
|
|
3196
|
+
# Export status Integer. Accepts Integer 0 (SUCCESS), nil (void Ruby
|
|
3197
|
+
# method), or true (boolean duck-typed success); treats Integer TIMEOUT
|
|
3198
|
+
# as TIMEOUT; treats non-zero Integers, false, floats (0.0, 2.0), and any
|
|
3199
|
+
# other invalid value as FAILURE.
|
|
3200
|
+
def normalize_lifecycle_status(result)
|
|
3201
|
+
return OpenTelemetry::SDK::Metrics::Export::SUCCESS if result.nil? || result.equal?(true) || (result.is_a?(Integer) && result.zero?)
|
|
3202
|
+
return OpenTelemetry::SDK::Metrics::Export::TIMEOUT if result.is_a?(Integer) && result == OpenTelemetry::SDK::Metrics::Export::TIMEOUT
|
|
3203
|
+
|
|
3204
|
+
OpenTelemetry::SDK::Metrics::Export::FAILURE
|
|
3205
|
+
end
|
|
3206
|
+
|
|
3207
|
+
def exception_lifecycle_status(error)
|
|
3208
|
+
error.is_a?(Timeout::Error) ? OpenTelemetry::SDK::Metrics::Export::TIMEOUT : OpenTelemetry::SDK::Metrics::Export::FAILURE
|
|
3209
|
+
end
|
|
3210
|
+
|
|
3211
|
+
READER_OWNERSHIP_ERROR = "MetricReader cannot be registered with more than one MeterProvider"
|
|
3212
|
+
|
|
3213
|
+
# Tracks single-provider ownership for metric readers and injected parts
|
|
3214
|
+
# across libo11y handles and plain OpenTelemetry SDK MeterProvider instances.
|
|
3215
|
+
module Ownership
|
|
3216
|
+
READER_OWNERS = ObjectSpace::WeakMap.new
|
|
3217
|
+
READER_OWNERS_MUTEX = Mutex.new
|
|
3218
|
+
PART_OWNERS = ObjectSpace::WeakMap.new
|
|
3219
|
+
PART_ROLES = ObjectSpace::WeakMap.new
|
|
3220
|
+
PART_OWNERS_MUTEX = Mutex.new
|
|
3221
|
+
private_constant :READER_OWNERS, :READER_OWNERS_MUTEX, :PART_OWNERS, :PART_ROLES, :PART_OWNERS_MUTEX
|
|
3222
|
+
|
|
3223
|
+
module_function
|
|
3224
|
+
|
|
3225
|
+
def reader_for_provider(reader, failures)
|
|
3226
|
+
reader.is_a?(IsolatedReader) ? reader : IsolatedReader.new(reader, failures)
|
|
3227
|
+
end
|
|
3228
|
+
|
|
3229
|
+
def unwrap_reader(reader)
|
|
3230
|
+
reader.is_a?(IsolatedReader) ? reader.__getobj__ : reader
|
|
3231
|
+
end
|
|
3232
|
+
|
|
3233
|
+
def reader_owned?(reader, allowed_owner = nil)
|
|
3234
|
+
raw = unwrap_reader(reader)
|
|
3235
|
+
return true if READER_OWNERS_MUTEX.synchronize { !READER_OWNERS[raw].nil? }
|
|
3236
|
+
|
|
3237
|
+
upstream_reader_owned?(raw, allowed_owner)
|
|
3238
|
+
end
|
|
3239
|
+
|
|
3240
|
+
# Whether part is currently registered on an active (non-stopped)
|
|
3241
|
+
# MetricProvider (libo11y or plain OpenTelemetry SDK). Only checks
|
|
3242
|
+
# actual reader ownership registries, never arbitrary @meter_provider
|
|
3243
|
+
# instance variables on non-reader processors/exporters.
|
|
3244
|
+
def active_reader_owned?(part, allowed_owner = nil)
|
|
3245
|
+
raw = unwrap_reader(part)
|
|
3246
|
+
libo11y_mp = READER_OWNERS_MUTEX.synchronize { READER_OWNERS[raw] }
|
|
3247
|
+
return !provider_stopped?(libo11y_mp) if libo11y_mp
|
|
3248
|
+
|
|
3249
|
+
owners, mutex = upstream_reader_owners
|
|
3250
|
+
if owners
|
|
3251
|
+
existing = mutex ? mutex.synchronize { owners[raw] } : owners[raw]
|
|
3252
|
+
return true if existing && !existing.equal?(allowed_owner) && !provider_stopped?(existing)
|
|
3253
|
+
|
|
3254
|
+
return false
|
|
3255
|
+
end
|
|
3256
|
+
return false unless raw.is_a?(OpenTelemetry::SDK::Metrics::Export::MetricReader)
|
|
3257
|
+
|
|
3258
|
+
provider = raw.instance_variable_get(:@meter_provider)
|
|
3259
|
+
!provider.nil? && !provider.equal?(allowed_owner) && !provider_stopped?(provider)
|
|
3260
|
+
end
|
|
3261
|
+
|
|
3262
|
+
def provider_stopped?(provider)
|
|
3263
|
+
provider.respond_to?(:closed?) ? provider.closed? : provider.instance_variable_get(:@stopped) == true
|
|
3264
|
+
end
|
|
3265
|
+
|
|
3266
|
+
def weakmap_key?(obj)
|
|
3267
|
+
!(obj.nil? || obj.equal?(true) || obj.equal?(false) || Integer === obj || Float === obj || Symbol === obj) # rubocop:disable Style/CaseEquality
|
|
3268
|
+
end
|
|
3269
|
+
|
|
3270
|
+
def upstream_reader_owners = Upstream.reader_owners
|
|
3271
|
+
def upstream_reader_owned?(raw, allowed_owner = nil) = Upstream.reader_owned?(raw, allowed_owner)
|
|
3272
|
+
def claim_upstream_reader(raw, sdk_provider, allowed_owner: nil) = Upstream.claim_reader(raw, sdk_provider, allowed_owner: allowed_owner)
|
|
3273
|
+
def release_upstream_reader(raw, sdk_provider, restore_owner: nil) = Upstream.release_reader(raw, sdk_provider, restore_owner: restore_owner)
|
|
3274
|
+
|
|
3275
|
+
module Upstream
|
|
3276
|
+
module_function
|
|
3277
|
+
|
|
3278
|
+
def reader_owners
|
|
3279
|
+
mp = OpenTelemetry::SDK::Metrics::MeterProvider
|
|
3280
|
+
return [nil, nil] unless mp.const_defined?(:READER_OWNERS, false)
|
|
3281
|
+
|
|
3282
|
+
owners = mp.const_get(:READER_OWNERS)
|
|
3283
|
+
mutex = mp.const_defined?(:READER_OWNERS_MUTEX, false) ? mp.const_get(:READER_OWNERS_MUTEX) : nil
|
|
3284
|
+
[owners, mutex]
|
|
3285
|
+
end
|
|
3286
|
+
|
|
3287
|
+
def reader_owned?(raw, allowed_owner = nil)
|
|
3288
|
+
owners, mutex = reader_owners
|
|
3289
|
+
if owners
|
|
3290
|
+
existing = mutex ? mutex.synchronize { owners[raw] } : owners[raw]
|
|
3291
|
+
return true if existing && !existing.equal?(allowed_owner)
|
|
3292
|
+
end
|
|
3293
|
+
provider = raw.instance_variable_get(:@meter_provider)
|
|
3294
|
+
!provider.nil? && !provider.equal?(allowed_owner)
|
|
3295
|
+
end
|
|
3296
|
+
|
|
3297
|
+
def claim_reader(raw, sdk_provider, allowed_owner: nil)
|
|
3298
|
+
owners, mutex = reader_owners
|
|
3299
|
+
if owners
|
|
3300
|
+
claim = lambda do
|
|
3301
|
+
existing = owners[raw]
|
|
3302
|
+
if existing && !existing.equal?(sdk_provider) && !(allowed_owner && existing.equal?(allowed_owner))
|
|
3303
|
+
raise ArgumentError, READER_OWNERSHIP_ERROR
|
|
3304
|
+
end
|
|
3305
|
+
|
|
3306
|
+
provider = raw.instance_variable_get(:@meter_provider)
|
|
3307
|
+
if !provider.nil? && !provider.equal?(sdk_provider) && !(allowed_owner && provider.equal?(allowed_owner))
|
|
3308
|
+
raise ArgumentError, READER_OWNERSHIP_ERROR
|
|
3309
|
+
end
|
|
3310
|
+
|
|
3311
|
+
owners[raw] = sdk_provider if sdk_provider
|
|
3312
|
+
end
|
|
3313
|
+
mutex ? mutex.synchronize(&claim) : claim.call
|
|
3314
|
+
elsif reader_owned?(raw, sdk_provider)
|
|
3315
|
+
raise ArgumentError, READER_OWNERSHIP_ERROR
|
|
3316
|
+
end
|
|
3317
|
+
end
|
|
3318
|
+
|
|
3319
|
+
def release_reader(raw, sdk_provider, restore_owner: nil)
|
|
3320
|
+
return unless sdk_provider
|
|
3321
|
+
|
|
3322
|
+
owners, mutex = reader_owners
|
|
3323
|
+
return unless owners && Ownership.weakmap_key?(raw)
|
|
3324
|
+
|
|
3325
|
+
release = lambda do
|
|
3326
|
+
next unless owners[raw].equal?(sdk_provider)
|
|
3327
|
+
|
|
3328
|
+
restore_owner ? owners[raw] = restore_owner : owners.delete(raw)
|
|
3329
|
+
end
|
|
3330
|
+
mutex ? mutex.synchronize(&release) : release.call
|
|
3331
|
+
end
|
|
3332
|
+
|
|
3333
|
+
def record_restored_owner(raw, owner, existing)
|
|
3334
|
+
return if owner.frozen? || !Ownership.weakmap_key?(existing)
|
|
3335
|
+
|
|
3336
|
+
map = owner.instance_variable_defined?(:@libo11y_restored_upstream) ? owner.instance_variable_get(:@libo11y_restored_upstream) : nil
|
|
3337
|
+
unless map
|
|
3338
|
+
map = {}.compare_by_identity
|
|
3339
|
+
owner.instance_variable_set(:@libo11y_restored_upstream, map)
|
|
3340
|
+
end
|
|
3341
|
+
map[raw] = WeakRef.new(existing)
|
|
3342
|
+
end
|
|
3343
|
+
|
|
3344
|
+
def pop_restored_owner(raw, owner)
|
|
3345
|
+
return nil unless owner.instance_variable_defined?(:@libo11y_restored_upstream)
|
|
3346
|
+
|
|
3347
|
+
map = owner.instance_variable_get(:@libo11y_restored_upstream)
|
|
3348
|
+
return nil unless map
|
|
3349
|
+
|
|
3350
|
+
weak = map.delete(raw)
|
|
3351
|
+
return nil unless weak
|
|
3352
|
+
|
|
3353
|
+
weak.weakref_alive? ? weak.__getobj__ : nil
|
|
3354
|
+
rescue WeakRef::RefError
|
|
3355
|
+
nil
|
|
3356
|
+
end
|
|
3357
|
+
end
|
|
3358
|
+
private_constant :Upstream
|
|
3359
|
+
|
|
3360
|
+
# Claims raw for a MeterProvider, recording ownership in both
|
|
3361
|
+
# READER_OWNERS and PART_OWNERS/PART_ROLES. Returns true if PART_OWNERS
|
|
3362
|
+
# was newly claimed for part_owner (late registration).
|
|
3363
|
+
def claim_reader(reader, owner, part_owner: nil, sdk_provider: nil, state: nil)
|
|
3364
|
+
raw = unwrap_reader(reader)
|
|
3365
|
+
holder = part_owner || owner
|
|
3366
|
+
PART_OWNERS_MUTEX.synchronize do
|
|
3367
|
+
existing_part = PART_OWNERS[raw]
|
|
3368
|
+
raise ArgumentError, READER_OWNERSHIP_ERROR if !existing_part.nil? && !existing_part.equal?(holder)
|
|
3369
|
+
if existing_part.equal?(holder) && PART_ROLES[raw] && PART_ROLES[raw] != :metrics
|
|
3370
|
+
raise ArgumentError, "libo11y: injected #{raw.class} cannot be shared across signals"
|
|
3371
|
+
end
|
|
3372
|
+
|
|
3373
|
+
READER_OWNERS_MUTEX.synchronize do
|
|
3374
|
+
existing = READER_OWNERS[raw]
|
|
3375
|
+
raise ArgumentError, READER_OWNERSHIP_ERROR if existing && !existing.equal?(owner)
|
|
3376
|
+
|
|
3377
|
+
claim_upstream_reader(raw, sdk_provider, allowed_owner: holder)
|
|
3378
|
+
READER_OWNERS[raw] = owner
|
|
3379
|
+
state[:claimed] = true if state
|
|
3380
|
+
end
|
|
3381
|
+
|
|
3382
|
+
newly_claimed = existing_part.nil?
|
|
3383
|
+
if newly_claimed
|
|
3384
|
+
PART_OWNERS[raw] = holder
|
|
3385
|
+
PART_ROLES[raw] = :metrics
|
|
3386
|
+
state[:claimed_part] = true if state
|
|
3387
|
+
end
|
|
3388
|
+
newly_claimed
|
|
3389
|
+
end
|
|
3390
|
+
end
|
|
3391
|
+
|
|
3392
|
+
def release_reader(reader, owner, sdk_provider: nil, part_owner: nil, release_part: false)
|
|
3393
|
+
raw = unwrap_reader(reader)
|
|
3394
|
+
PART_OWNERS_MUTEX.synchronize do
|
|
3395
|
+
restore = !release_part && part_owner && PART_OWNERS[raw].equal?(part_owner) ? part_owner : nil
|
|
3396
|
+
READER_OWNERS_MUTEX.synchronize do
|
|
3397
|
+
READER_OWNERS.delete(raw) if READER_OWNERS[raw].equal?(owner)
|
|
3398
|
+
release_upstream_reader(raw, sdk_provider, restore_owner: restore)
|
|
3399
|
+
end
|
|
3400
|
+
if release_part && part_owner && PART_OWNERS[raw].equal?(part_owner)
|
|
3401
|
+
PART_OWNERS.delete(raw)
|
|
3402
|
+
PART_ROLES.delete(raw)
|
|
3403
|
+
end
|
|
3404
|
+
end
|
|
3405
|
+
end
|
|
3406
|
+
|
|
3407
|
+
# Atomically claims part for owner if not owned by another active handle
|
|
3408
|
+
# or metric provider. Returns true if owner already holds part or newly
|
|
3409
|
+
# claimed it, and false if another owner holds it.
|
|
3410
|
+
def try_claim_part!(part, owner, role: nil)
|
|
3411
|
+
PART_OWNERS_MUTEX.synchronize do
|
|
3412
|
+
existing = PART_OWNERS[part]
|
|
3413
|
+
return false if !existing.nil? && !existing.equal?(owner)
|
|
3414
|
+
return false if existing.equal?(owner) && role && PART_ROLES[part] && PART_ROLES[part] != role
|
|
3415
|
+
|
|
3416
|
+
if role == :metrics
|
|
3417
|
+
raw = unwrap_reader(part)
|
|
3418
|
+
return false if READER_OWNERS_MUTEX.synchronize { !READER_OWNERS[raw].nil? }
|
|
3419
|
+
|
|
3420
|
+
begin
|
|
3421
|
+
claim_upstream_reader(raw, owner, allowed_owner: owner)
|
|
3422
|
+
rescue ArgumentError
|
|
3423
|
+
return false
|
|
3424
|
+
end
|
|
3425
|
+
else
|
|
3426
|
+
return false if active_reader_owned?(part, owner)
|
|
3427
|
+
|
|
3428
|
+
begin
|
|
3429
|
+
claim_upstream_non_metric!(part, owner)
|
|
3430
|
+
rescue ArgumentError
|
|
3431
|
+
return false
|
|
3432
|
+
end
|
|
3433
|
+
end
|
|
3434
|
+
|
|
3435
|
+
PART_OWNERS[part] = owner
|
|
3436
|
+
PART_ROLES[part] = role if role
|
|
3437
|
+
true
|
|
3438
|
+
end
|
|
3439
|
+
end
|
|
3440
|
+
|
|
3441
|
+
# Atomically verifies that none of parts_by_role are shared across
|
|
3442
|
+
# roles/signals or owned by another active handle or provider, and
|
|
3443
|
+
# claims them for owner. Raises ArgumentError without mutating
|
|
3444
|
+
# ownership on conflict.
|
|
3445
|
+
def reserve_parts!(parts_by_role, owner)
|
|
3446
|
+
PART_OWNERS_MUTEX.synchronize do
|
|
3447
|
+
validate_parts_for_reserve!(parts_by_role, owner)
|
|
3448
|
+
claim_all_upstream!(parts_by_role, owner)
|
|
3449
|
+
parts_by_role.each do |role, list|
|
|
3450
|
+
list.each do |part|
|
|
3451
|
+
PART_OWNERS[part] = owner
|
|
3452
|
+
PART_ROLES[part] = role
|
|
3453
|
+
end
|
|
3454
|
+
end
|
|
3455
|
+
end
|
|
3456
|
+
end
|
|
3457
|
+
|
|
3458
|
+
def claim_upstream_non_metric!(part, owner)
|
|
3459
|
+
raw = unwrap_reader(part)
|
|
3460
|
+
owners, mutex = upstream_reader_owners
|
|
3461
|
+
return unless owners && weakmap_key?(raw)
|
|
3462
|
+
|
|
3463
|
+
libo11y_mp = READER_OWNERS_MUTEX.synchronize { READER_OWNERS[raw] }
|
|
3464
|
+
claim = lambda do
|
|
3465
|
+
existing = owners[raw]
|
|
3466
|
+
stopped = existing && (provider_stopped?(existing) || (libo11y_mp && provider_stopped?(libo11y_mp)))
|
|
3467
|
+
if existing && !existing.equal?(owner) && !stopped
|
|
3468
|
+
raise ArgumentError, "libo11y: injected #{part.class} is already owned by an active meter provider"
|
|
3469
|
+
end
|
|
3470
|
+
|
|
3471
|
+
unless existing.equal?(owner)
|
|
3472
|
+
Upstream.record_restored_owner(raw, owner, existing) if existing
|
|
3473
|
+
owners[raw] = owner
|
|
3474
|
+
end
|
|
3475
|
+
end
|
|
3476
|
+
mutex ? mutex.synchronize(&claim) : claim.call
|
|
3477
|
+
end
|
|
3478
|
+
|
|
3479
|
+
def restore_upstream_owner_for(raw, owner) = Upstream.pop_restored_owner(raw, owner)
|
|
3480
|
+
|
|
3481
|
+
def claim_all_upstream!(parts_by_role, owner)
|
|
3482
|
+
claimed_upstream = []
|
|
3483
|
+
completed = false
|
|
3484
|
+
begin
|
|
3485
|
+
parts_by_role.each do |role, list|
|
|
3486
|
+
list.each do |part|
|
|
3487
|
+
raw = unwrap_reader(part)
|
|
3488
|
+
claimed_upstream << raw
|
|
3489
|
+
role == :metrics ? claim_upstream_reader(raw, owner, allowed_owner: owner) : claim_upstream_non_metric!(part, owner)
|
|
3490
|
+
end
|
|
3491
|
+
end
|
|
3492
|
+
completed = true
|
|
3493
|
+
ensure
|
|
3494
|
+
unless completed
|
|
3495
|
+
claimed_upstream.each do |raw|
|
|
3496
|
+
restore = restore_upstream_owner_for(raw, owner)
|
|
3497
|
+
release_upstream_reader(raw, owner, restore_owner: restore)
|
|
3498
|
+
end
|
|
3499
|
+
end
|
|
3500
|
+
end
|
|
3501
|
+
end
|
|
3502
|
+
|
|
3503
|
+
def validate_parts_for_reserve!(parts_by_role, owner)
|
|
3504
|
+
seen_role = {}.compare_by_identity
|
|
3505
|
+
parts_by_role.each do |role, list|
|
|
3506
|
+
list.each do |part|
|
|
3507
|
+
prev = seen_role[part]
|
|
3508
|
+
raise ArgumentError, conflict_role_message(part, prev, role) if prev && prev != role
|
|
3509
|
+
|
|
3510
|
+
seen_role[part] = role
|
|
3511
|
+
existing = PART_OWNERS[part]
|
|
3512
|
+
if !existing.nil? && !existing.equal?(owner)
|
|
3513
|
+
raise ArgumentError, "libo11y: injected #{part.class} is already owned by another active handle"
|
|
3514
|
+
end
|
|
3515
|
+
raise ArgumentError, READER_OWNERSHIP_ERROR if role == :metrics && reader_owned?(part)
|
|
3516
|
+
if role != :metrics && active_reader_owned?(part)
|
|
3517
|
+
raise ArgumentError, "libo11y: injected #{part.class} is already owned by an active meter provider"
|
|
3518
|
+
end
|
|
3519
|
+
end
|
|
3520
|
+
end
|
|
3521
|
+
end
|
|
3522
|
+
|
|
3523
|
+
def conflict_role_message(part, first_role, second_role)
|
|
3524
|
+
same_signal = (first_role.to_s.split("_").first == second_role.to_s.split("_").first)
|
|
3525
|
+
if same_signal
|
|
3526
|
+
"libo11y: injected #{part.class} cannot be passed as both exporter and processor"
|
|
3527
|
+
else
|
|
3528
|
+
"libo11y: injected #{part.class} cannot be shared across signals"
|
|
3529
|
+
end
|
|
3530
|
+
end
|
|
3531
|
+
|
|
3532
|
+
# Claims part for owner during late provider registration. Returns false
|
|
3533
|
+
# if owner already holds part for the same role, raises ArgumentError
|
|
3534
|
+
# if another active handle or meter provider holds part or owner holds
|
|
3535
|
+
# it under another role, and returns true when newly claimed.
|
|
3536
|
+
def claim_part!(part, owner, role: nil)
|
|
3537
|
+
PART_OWNERS_MUTEX.synchronize do
|
|
3538
|
+
existing = PART_OWNERS[part]
|
|
3539
|
+
if existing.equal?(owner)
|
|
3540
|
+
raise ArgumentError, conflict_role_message(part, PART_ROLES[part], role) if role && PART_ROLES[part] && PART_ROLES[part] != role
|
|
3541
|
+
|
|
3542
|
+
return false
|
|
3543
|
+
end
|
|
3544
|
+
|
|
3545
|
+
raise ArgumentError, "libo11y: injected #{part.class} is already owned by another active handle" unless existing.nil?
|
|
3546
|
+
raise ArgumentError, "libo11y: injected #{part.class} is already owned by an active meter provider" if active_reader_owned?(part, owner)
|
|
3547
|
+
|
|
3548
|
+
claim_upstream_non_metric!(part, owner)
|
|
3549
|
+
PART_OWNERS[part] = owner
|
|
3550
|
+
PART_ROLES[part] = role if role
|
|
3551
|
+
true
|
|
3552
|
+
end
|
|
3553
|
+
end
|
|
3554
|
+
|
|
3555
|
+
def release_parts(parts, owner)
|
|
3556
|
+
PART_OWNERS_MUTEX.synchronize do
|
|
3557
|
+
parts.each do |part|
|
|
3558
|
+
next unless PART_OWNERS[part].equal?(owner)
|
|
3559
|
+
|
|
3560
|
+
PART_OWNERS.delete(part)
|
|
3561
|
+
PART_ROLES.delete(part)
|
|
3562
|
+
raw = unwrap_reader(part)
|
|
3563
|
+
restore = restore_upstream_owner_for(raw, owner)
|
|
3564
|
+
release_upstream_reader(raw, owner, restore_owner: restore)
|
|
3565
|
+
end
|
|
3566
|
+
end
|
|
3567
|
+
end
|
|
3568
|
+
end
|
|
3569
|
+
|
|
3570
|
+
# Whether two views, each the arguments of add_view with its :name,
|
|
3571
|
+
# may select one instrument together. Only what is certain says no:
|
|
3572
|
+
# two different names without a pattern, a name its pattern does not
|
|
3573
|
+
# match, or a kind, unit or meter both give and give differently.
|
|
3574
|
+
def may_select_together?(one, other)
|
|
3575
|
+
return false if %i[type unit meter_name meter_version].any? { |field| one[field] && other[field] && one[field] != other[field] }
|
|
3576
|
+
|
|
3577
|
+
names = [one[:name], other[:name]]
|
|
3578
|
+
return true if names.any?(&:nil?)
|
|
3579
|
+
|
|
3580
|
+
patterns, plain = names.map(&:to_s).partition { |name| name.match?(/[*?]/) }
|
|
3581
|
+
case plain.length
|
|
3582
|
+
when 2 then plain.first == plain.last
|
|
3583
|
+
when 1 then OpenTelemetry::SDK::Metrics::View::RegisteredView.new(patterns.first).name_match(plain.first)
|
|
3584
|
+
else true
|
|
3585
|
+
end
|
|
3586
|
+
end
|
|
3587
|
+
|
|
3588
|
+
# Refuses a view that adds attributes when another view may select
|
|
3589
|
+
# the same instrument. The SDK adds a view's attribute_keys to the
|
|
3590
|
+
# measurement itself, so the next view of that instrument gets them
|
|
3591
|
+
# too, and a point already recorded can change under them.
|
|
3592
|
+
#
|
|
3593
|
+
# @raise [ArgumentError]
|
|
3594
|
+
def refuse_mixed_views(view, others)
|
|
3595
|
+
clash = others.find do |other|
|
|
3596
|
+
may_select_together?(view, other) && [view, other].any? { |each| !each[:attribute_keys].to_h.empty? }
|
|
3597
|
+
end
|
|
3598
|
+
return if clash.nil?
|
|
3599
|
+
|
|
3600
|
+
raise ArgumentError,
|
|
3601
|
+
"libo11y: the views #{view[:name].inspect} and #{clash[:name].inspect} may select one instrument and one of them has attribute_keys, " \
|
|
3602
|
+
"which the OpenTelemetry Ruby SDK would add to both streams"
|
|
3603
|
+
end
|
|
3604
|
+
|
|
3605
|
+
# The sampler: the option, else the one OTEL_TRACES_SAMPLER names. A
|
|
3606
|
+
# name libo11y does not know gives the default with a warning, as the
|
|
3607
|
+
# OpenTelemetry Go SDK and the Go and Python implementations do, so a
|
|
3608
|
+
# typo in a standard variable does not stop the service.
|
|
3609
|
+
def build_sampler(opt_sampler, env_map)
|
|
3610
|
+
return opt_sampler unless opt_sampler.nil?
|
|
3611
|
+
|
|
3612
|
+
raw = Env.value(env_map, "OTEL_TRACES_SAMPLER")
|
|
3613
|
+
name = Env.sampler_name(env_map)
|
|
3614
|
+
OpenTelemetry.logger.warn("libo11y: OTEL_TRACES_SAMPLER=#{raw.inspect} names no sampler, using #{name}") if raw && raw.strip.downcase != name
|
|
3615
|
+
|
|
3616
|
+
samplers = OpenTelemetry::SDK::Trace::Samplers
|
|
3617
|
+
ratio = -> { samplers.trace_id_ratio_based(parse_ratio(env_map["OTEL_TRACES_SAMPLER_ARG"].to_s.strip)) }
|
|
3618
|
+
case name
|
|
3619
|
+
when "always_on" then samplers::ALWAYS_ON
|
|
3620
|
+
when "always_off" then samplers::ALWAYS_OFF
|
|
3621
|
+
when "traceidratio" then ratio.call
|
|
3622
|
+
when "parentbased_always_off" then samplers.parent_based(root: samplers::ALWAYS_OFF)
|
|
3623
|
+
when "parentbased_traceidratio" then samplers.parent_based(root: ratio.call)
|
|
3624
|
+
else samplers.parent_based(root: samplers::ALWAYS_ON)
|
|
3625
|
+
end
|
|
3626
|
+
end
|
|
3627
|
+
|
|
3628
|
+
# The ratio of a ratio sampler. With no argument, or one that is not a
|
|
3629
|
+
# number from 0 to 1, it is 1, as in the OpenTelemetry Go SDK.
|
|
3630
|
+
def parse_ratio(arg)
|
|
3631
|
+
return 1.0 if arg.empty?
|
|
3632
|
+
|
|
3633
|
+
ratio = Float(arg, exception: false)
|
|
3634
|
+
return ratio if ratio && !ratio.nan? && ratio.between?(0.0, 1.0)
|
|
3635
|
+
|
|
3636
|
+
OpenTelemetry.logger.warn("libo11y: OTEL_TRACES_SAMPLER_ARG=#{arg.inspect} is not a ratio from 0 to 1, using 1")
|
|
3637
|
+
1.0
|
|
3638
|
+
end
|
|
3639
|
+
|
|
3640
|
+
def configure_exemplar_filter(meter_provider, filter_sym)
|
|
3641
|
+
case filter_sym
|
|
3642
|
+
when ExemplarFilter::ALWAYS_ON
|
|
3643
|
+
meter_provider.enable_exemplar_filter(
|
|
3644
|
+
exemplar_filter: OpenTelemetry::SDK::Metrics::Exemplar::AlwaysOnExemplarFilter
|
|
3645
|
+
)
|
|
3646
|
+
when ExemplarFilter::ALWAYS_OFF
|
|
3647
|
+
meter_provider.disable_exemplar_filter
|
|
3648
|
+
else
|
|
3649
|
+
meter_provider.enable_exemplar_filter(
|
|
3650
|
+
exemplar_filter: OpenTelemetry::SDK::Metrics::Exemplar::TraceBasedExemplarFilter
|
|
3651
|
+
)
|
|
3652
|
+
end
|
|
3653
|
+
end
|
|
3654
|
+
|
|
3655
|
+
# Encodes instrumentation scope attributes and stamps the specification's
|
|
3656
|
+
# resource schema URL on OTLP trace, metric, and log requests.
|
|
3657
|
+
module OtlpEnvelope
|
|
3658
|
+
SCOPE_ATTRS_FIBER_KEY = :libo11y_otlp_scope_attrs
|
|
3659
|
+
private_constant :SCOPE_ATTRS_FIBER_KEY
|
|
3660
|
+
|
|
3661
|
+
module_function
|
|
3662
|
+
|
|
3663
|
+
def key_value(key, value)
|
|
3664
|
+
Opentelemetry::Proto::Common::V1::KeyValue.new(key: Bridges.scrub_utf8(key.to_s), value: any_value(value))
|
|
3665
|
+
end
|
|
3666
|
+
|
|
3667
|
+
def any_value(value)
|
|
3668
|
+
any = Opentelemetry::Proto::Common::V1::AnyValue.new
|
|
3669
|
+
case value
|
|
3670
|
+
when String then any.string_value = Bridges.scrub_utf8(value)
|
|
3671
|
+
when Integer
|
|
3672
|
+
if value.between?(SensitivityPolicy::INT64_MIN, SensitivityPolicy::INT64_MAX)
|
|
3673
|
+
any.int_value = value
|
|
3674
|
+
else
|
|
3675
|
+
any.string_value = value.to_s
|
|
3676
|
+
end
|
|
3677
|
+
when Float then any.double_value = value
|
|
3678
|
+
when true, false then any.bool_value = value
|
|
3679
|
+
when Array then any.array_value = Opentelemetry::Proto::Common::V1::ArrayValue.new(values: value.map { |el| any_value(el) })
|
|
3680
|
+
when Hash then any.kvlist_value = Opentelemetry::Proto::Common::V1::KeyValueList.new(values: value.map { |k, v| key_value(k, v) })
|
|
3681
|
+
end
|
|
3682
|
+
any
|
|
3683
|
+
end
|
|
3684
|
+
|
|
3685
|
+
def extract_scope_attrs(items)
|
|
3686
|
+
items.group_by(&:resource).values.map do |resource_items|
|
|
3687
|
+
resource_items.group_by(&:instrumentation_scope).keys.map do |scope|
|
|
3688
|
+
attrs = scope.respond_to?(:attributes) ? scope.attributes : nil
|
|
3689
|
+
attrs.is_a?(Hash) && !attrs.empty? ? attrs : nil
|
|
3690
|
+
end
|
|
3691
|
+
end
|
|
3692
|
+
end
|
|
3693
|
+
|
|
3694
|
+
def apply(request, field, scope_field, scopes_by_resource)
|
|
3695
|
+
request.public_send(field).each_with_index do |entry, r_idx|
|
|
3696
|
+
entry.schema_url = Spec::SCHEMA_URL if entry.schema_url.empty?
|
|
3697
|
+
next unless scope_field && scopes_by_resource
|
|
3698
|
+
|
|
3699
|
+
entry.public_send(scope_field).each_with_index do |scope_entry, s_idx|
|
|
3700
|
+
attrs = scopes_by_resource.dig(r_idx, s_idx)
|
|
3701
|
+
next unless attrs && scope_entry.scope && scope_entry.scope.attributes.empty?
|
|
3702
|
+
|
|
3703
|
+
attrs.each { |k, v| scope_entry.scope.attributes << key_value(k, v) }
|
|
3704
|
+
end
|
|
3705
|
+
end
|
|
3706
|
+
end
|
|
3707
|
+
|
|
3708
|
+
def with_scope_attrs(items, scope_field)
|
|
3709
|
+
prev = Thread.current[SCOPE_ATTRS_FIBER_KEY]
|
|
3710
|
+
Thread.current[SCOPE_ATTRS_FIBER_KEY] = scope_field ? extract_scope_attrs(items) : nil
|
|
3711
|
+
yield
|
|
3712
|
+
ensure
|
|
3713
|
+
Thread.current[SCOPE_ATTRS_FIBER_KEY] = prev
|
|
3714
|
+
end
|
|
3715
|
+
|
|
3716
|
+
def current_scope_attrs
|
|
3717
|
+
Thread.current[SCOPE_ATTRS_FIBER_KEY]
|
|
3718
|
+
end
|
|
3719
|
+
end
|
|
3720
|
+
|
|
3721
|
+
# Makes an OTLP exporter write the specification's schema URL on each
|
|
3722
|
+
# resource it sends and preserve instrumentation scope attributes that
|
|
3723
|
+
# opentelemetry-exporter-otlp-common omits. Each exporter builds its
|
|
3724
|
+
# request and hands the bytes to send_bytes, so wrapping export and
|
|
3725
|
+
# send_bytes handles all three signals uniformly.
|
|
3726
|
+
def stamp_schema_url(exporter, request_class, field, scope_field = nil)
|
|
3727
|
+
return exporter unless exporter.respond_to?(:send_bytes, true)
|
|
3728
|
+
|
|
3729
|
+
stamp = Module.new do
|
|
3730
|
+
define_method(:export) do |data, timeout: nil|
|
|
3731
|
+
items = data.is_a?(Array) ? data : data.to_a
|
|
3732
|
+
OtlpEnvelope.with_scope_attrs(items, scope_field) { super(items, timeout: timeout) }
|
|
3733
|
+
end
|
|
3734
|
+
|
|
3735
|
+
define_method(:send_bytes) do |bytes, timeout:|
|
|
3736
|
+
unless bytes.nil?
|
|
3737
|
+
request = request_class.decode(bytes)
|
|
3738
|
+
OtlpEnvelope.apply(request, field, scope_field, OtlpEnvelope.current_scope_attrs)
|
|
3739
|
+
bytes = request_class.encode(request)
|
|
3740
|
+
end
|
|
3741
|
+
super(bytes, timeout: timeout)
|
|
3742
|
+
end
|
|
3743
|
+
private :send_bytes
|
|
3744
|
+
end
|
|
3745
|
+
exporter.singleton_class.prepend(stamp)
|
|
3746
|
+
exporter
|
|
3747
|
+
end
|
|
3748
|
+
|
|
3749
|
+
# Builds an OTLP exporter. A certificate or key file that cannot be
|
|
3750
|
+
# read or parsed is reported as an exporter error that names the signal.
|
|
3751
|
+
def otlp_exporter(signal)
|
|
3752
|
+
yield
|
|
3753
|
+
rescue SystemCallError, IOError, OpenSSL::OpenSSLError => e
|
|
3754
|
+
raise ExporterError, "o11y: #{signal} exporter: #{e.message}"
|
|
3755
|
+
end
|
|
3756
|
+
|
|
3757
|
+
def build_otlp_trace_exporter(env_map)
|
|
3758
|
+
otlp_exporter(:traces) { new_otlp_trace_exporter(env_map) }
|
|
3759
|
+
end
|
|
3760
|
+
|
|
3761
|
+
def new_otlp_trace_exporter(env_map)
|
|
3762
|
+
Env.parse_protocol(env_map, "OTEL_EXPORTER_OTLP_TRACES_PROTOCOL")
|
|
3763
|
+
tls = Env.signal_tls(env_map, "OTEL_EXPORTER_OTLP_TRACES")
|
|
3764
|
+
exporter = OpenTelemetry::Exporter::OTLP::Exporter.new(
|
|
3765
|
+
endpoint: Env.signal_endpoint(env_map, "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT", "/v1/traces"),
|
|
3766
|
+
headers: Env.signal_headers(env_map, "OTEL_EXPORTER_OTLP_TRACES_HEADERS"),
|
|
3767
|
+
compression: Env.signal_compression(env_map, "OTEL_EXPORTER_OTLP_TRACES_COMPRESSION"),
|
|
495
3768
|
timeout: Env.signal_timeout(env_map, "OTEL_EXPORTER_OTLP_TRACES_TIMEOUT"),
|
|
496
3769
|
ssl_verify_mode: Env.ssl_verify_mode(env_map),
|
|
497
3770
|
**tls
|
|
498
3771
|
)
|
|
499
|
-
stamp_schema_url(exporter, Opentelemetry::Proto::Collector::Trace::V1::ExportTraceServiceRequest, :resource_spans)
|
|
3772
|
+
stamp_schema_url(exporter, Opentelemetry::Proto::Collector::Trace::V1::ExportTraceServiceRequest, :resource_spans, :scope_spans)
|
|
500
3773
|
end
|
|
501
3774
|
|
|
502
3775
|
def build_otlp_metric_exporter(env_map)
|
|
3776
|
+
otlp_exporter(:metrics) { new_otlp_metric_exporter(env_map) }
|
|
3777
|
+
end
|
|
3778
|
+
|
|
3779
|
+
def new_otlp_metric_exporter(env_map)
|
|
503
3780
|
Env.parse_protocol(env_map, "OTEL_EXPORTER_OTLP_METRICS_PROTOCOL")
|
|
504
3781
|
tls = Env.signal_tls(env_map, "OTEL_EXPORTER_OTLP_METRICS")
|
|
505
3782
|
exporter = OpenTelemetry::Exporter::OTLP::Metrics::MetricsExporter.new(
|
|
@@ -508,12 +3785,33 @@ module Libo11y
|
|
|
508
3785
|
compression: Env.signal_compression(env_map, "OTEL_EXPORTER_OTLP_METRICS_COMPRESSION"),
|
|
509
3786
|
timeout: Env.signal_timeout(env_map, "OTEL_EXPORTER_OTLP_METRICS_TIMEOUT"),
|
|
510
3787
|
ssl_verify_mode: Env.ssl_verify_mode(env_map),
|
|
3788
|
+
default_aggregation: { histogram: histogram_aggregation(env_map) },
|
|
511
3789
|
**tls
|
|
512
3790
|
)
|
|
513
|
-
stamp_schema_url(exporter, Opentelemetry::Proto::Collector::Metrics::V1::ExportMetricsServiceRequest, :resource_metrics)
|
|
3791
|
+
stamp_schema_url(exporter, Opentelemetry::Proto::Collector::Metrics::V1::ExportMetricsServiceRequest, :resource_metrics, :scope_metrics)
|
|
3792
|
+
sanitize_export = Module.new do
|
|
3793
|
+
def export(metrics, timeout: nil)
|
|
3794
|
+
super(Sanitize.sanitize_metrics(metrics), timeout: timeout)
|
|
3795
|
+
end
|
|
3796
|
+
end
|
|
3797
|
+
exporter.singleton_class.prepend(sanitize_export)
|
|
3798
|
+
exporter
|
|
3799
|
+
end
|
|
3800
|
+
|
|
3801
|
+
# The histogram aggregation OTEL_EXPORTER_OTLP_METRICS_DEFAULT_HISTOGRAM_AGGREGATION
|
|
3802
|
+
# selects in env_map. It is always passed, because the exporter's own
|
|
3803
|
+
# default reads the process environment.
|
|
3804
|
+
def histogram_aggregation(env_map)
|
|
3805
|
+
aggregation = OpenTelemetry::SDK::Metrics::Aggregation
|
|
3806
|
+
name = Env.value(env_map, "OTEL_EXPORTER_OTLP_METRICS_DEFAULT_HISTOGRAM_AGGREGATION").to_s.strip.downcase
|
|
3807
|
+
name == "base2_exponential_bucket_histogram" ? aggregation::ExponentialBucketHistogram : aggregation::ExplicitBucketHistogram
|
|
514
3808
|
end
|
|
515
3809
|
|
|
516
3810
|
def build_otlp_log_exporter(env_map)
|
|
3811
|
+
otlp_exporter(:logs) { new_otlp_log_exporter(env_map) }
|
|
3812
|
+
end
|
|
3813
|
+
|
|
3814
|
+
def new_otlp_log_exporter(env_map)
|
|
517
3815
|
Env.parse_protocol(env_map, "OTEL_EXPORTER_OTLP_LOGS_PROTOCOL")
|
|
518
3816
|
tls = Env.signal_tls(env_map, "OTEL_EXPORTER_OTLP_LOGS")
|
|
519
3817
|
exporter = OpenTelemetry::Exporter::OTLP::Logs::LogsExporter.new(
|
|
@@ -524,7 +3822,7 @@ module Libo11y
|
|
|
524
3822
|
ssl_verify_mode: Env.ssl_verify_mode(env_map),
|
|
525
3823
|
**tls
|
|
526
3824
|
)
|
|
527
|
-
stamp_schema_url(exporter, Opentelemetry::Proto::Collector::Logs::V1::ExportLogsServiceRequest, :resource_logs)
|
|
3825
|
+
stamp_schema_url(exporter, Opentelemetry::Proto::Collector::Logs::V1::ExportLogsServiceRequest, :resource_logs, :scope_logs)
|
|
528
3826
|
end
|
|
529
3827
|
end
|
|
530
3828
|
end
|