libo11y 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,286 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../errors"
4
+ require_relative "../options"
5
+ require_relative "../redact"
6
+ require_relative "../spec"
7
+ require_relative "pii"
8
+
9
+ module Libo11y
10
+ module Internal
11
+ class ViolationRecorder
12
+ def initialize
13
+ @mutex = Mutex.new
14
+ @pending = []
15
+ @sink = nil
16
+ end
17
+
18
+ def attach(sink)
19
+ pending = nil
20
+ @mutex.synchronize do
21
+ @sink = sink
22
+ pending = @pending
23
+ @pending = []
24
+ end
25
+ pending.each { |sig, rule| sink.call(sig, rule) }
26
+ end
27
+
28
+ def record(signal, rule)
29
+ sink = nil
30
+ @mutex.synchronize do
31
+ if @sink.nil?
32
+ @pending << [signal, rule]
33
+ return
34
+ end
35
+ sink = @sink
36
+ end
37
+ sink.call(signal, rule)
38
+ end
39
+ end
40
+
41
+ class SensitivityPolicy
42
+ RULE_SECRET = "secret_attribute"
43
+ RULE_PII = "pii_attribute"
44
+
45
+ attr_reader :pii_mode
46
+
47
+ def self.load_app_registries(spec_sources)
48
+ return {} if spec_sources.nil?
49
+
50
+ sources = spec_sources.is_a?(Array) ? spec_sources : [spec_sources]
51
+ by_ns = {}
52
+ classes = {}
53
+ sources.each do |src|
54
+ compiled = case src
55
+ when Spec::AppRegistry::Compiled
56
+ src
57
+ when String
58
+ if File.file?(src)
59
+ Spec::AppRegistry.load_file(src)
60
+ else
61
+ Spec::AppRegistry.compile(Spec::AppRegistry.parse(src), source: "<inline>")
62
+ end
63
+ else
64
+ raise InvalidAppRegistry, "o11y: invalid application registry source #{src.class}"
65
+ end
66
+ prev = by_ns[compiled.namespace]
67
+ if prev
68
+ raise InvalidAppRegistry,
69
+ "o11y: invalid application registry: duplicate namespace #{compiled.namespace.inspect} declared in #{prev} and #{compiled.source}"
70
+ end
71
+ by_ns[compiled.namespace] = compiled.source
72
+ classes.merge!(compiled.classes)
73
+ rescue SystemCallError, Spec::AppRegistry::ParseError, Spec::AppRegistry::ValidationError => e
74
+ raise InvalidAppRegistry, "o11y: invalid application registry: #{e.message}"
75
+ end
76
+ classes
77
+ end
78
+
79
+ def initialize(pii_mode: PIIMode::DROP, pii_hash_key: nil, app_classes: nil, recorder: nil)
80
+ mode = pii_mode.is_a?(Symbol) ? pii_mode : pii_mode.to_s.to_sym
81
+ raise Error, "o11y: invalid pii_mode #{pii_mode.inspect}" unless PIIMode::ALL.include?(mode)
82
+
83
+ key_bytes = pii_hash_key.nil? ? "".b : pii_hash_key.b
84
+ raise PIIHashKey if mode == PIIMode::HASH && key_bytes.bytesize < PII::MIN_PII_HASH_KEY_LEN
85
+
86
+ @pii_mode = mode
87
+ @key = key_bytes
88
+ @app = app_classes ? app_classes.dup.freeze : {}.freeze
89
+ @recorder = recorder
90
+ end
91
+
92
+ def silent
93
+ SensitivityPolicy.new(pii_mode: @pii_mode, pii_hash_key: @key, app_classes: @app, recorder: nil)
94
+ end
95
+
96
+ def lookup(key)
97
+ Spec::SENSITIVITY_OF[key] || @app[key]
98
+ end
99
+
100
+ def action_for(cls)
101
+ return :drop if cls == Spec::Sensitivity::SECRET
102
+
103
+ if cls == Spec::Sensitivity::PII
104
+ return :keep if @pii_mode == PIIMode::ALLOW
105
+ return :rewrite if @pii_mode == PIIMode::HASH
106
+
107
+ return :drop
108
+ end
109
+ :keep
110
+ end
111
+
112
+ def decide(signal, key)
113
+ cls = lookup(key)
114
+ act = action_for(cls)
115
+ if act != :keep && @recorder
116
+ rule = cls == Spec::Sensitivity::SECRET ? RULE_SECRET : RULE_PII
117
+ @recorder.record(signal, rule)
118
+ end
119
+ act
120
+ end
121
+
122
+ def metric_keep?(key)
123
+ cls = lookup(key)
124
+ return false if cls == Spec::Sensitivity::SECRET
125
+ return @pii_mode == PIIMode::ALLOW if cls == Spec::Sensitivity::PII
126
+
127
+ true
128
+ end
129
+
130
+ def tokenize(value)
131
+ PII.token(@key, value)
132
+ end
133
+
134
+ def classify_flat(signal, attrs)
135
+ return [{}, false] if attrs.nil? || attrs.empty?
136
+
137
+ changed = false
138
+ out = {}
139
+ attrs.each do |raw_k, raw_v|
140
+ k = raw_k.to_s
141
+ v = render(raw_v)
142
+ changed = true unless v.equal?(raw_v)
143
+ act = decide(signal, k)
144
+ if act == :drop
145
+ changed = true
146
+ next
147
+ elsif act == :rewrite
148
+ changed = true
149
+ out[k] = tokenize(v)
150
+ else
151
+ out[k] = v
152
+ end
153
+ end
154
+ [out, changed]
155
+ end
156
+
157
+ def classify_metric_attrs(attrs)
158
+ return {} if attrs.nil? || attrs.empty?
159
+
160
+ out = {}
161
+ attrs.each do |raw_k, raw_v|
162
+ k = raw_k.to_s
163
+ next unless metric_keep?(k)
164
+
165
+ out[k] = render(raw_v)
166
+ end
167
+ out
168
+ end
169
+
170
+ # Applies capture-time redaction, the attribute replacer and the policy
171
+ # to a log record's attributes. Nested Hashes and Arrays are walked, so
172
+ # every member is judged on its dotted effective key, as go/logredact.go
173
+ # does. The walk fails closed. One budget of 2048 nodes is shared by the
174
+ # whole call and spent before a node is examined. A Hash whose effective
175
+ # key has more than 16 parts, or an Array nested 16 deep, is not
176
+ # entered. A reference back into the value being walked, the attributes
177
+ # themselves included, is cut. What the walk did not examine is dropped,
178
+ # and so is a Hash or Array that classification emptied.
179
+ def classify_log_attributes(attrs, replacer: nil)
180
+ return {} if attrs.nil? || attrs.empty?
181
+
182
+ walk = LogWalk.new(PII::MAX_COMPOSITE_NODES, { attrs => true }.compare_by_identity, replacer)
183
+ walk_hash(attrs, [], walk).first
184
+ end
185
+
186
+ private
187
+
188
+ LogWalk = Struct.new(:budget, :active, :replacer) do
189
+ # Takes one node from the budget and reports whether any remained.
190
+ def spend?
191
+ return false if budget <= 0
192
+
193
+ self.budget -= 1
194
+ true
195
+ end
196
+ end
197
+ private_constant :LogWalk
198
+
199
+ # Renders a Secret, Masked or Fields value, also inside a Hash or Array.
200
+ def render(value)
201
+ case value
202
+ when Hash then Redact.render(value)
203
+ when Array then value.any? { |v| Redact.redactable?(v) || v.is_a?(Hash) || v.is_a?(Array) } ? Redact.render(value) : value
204
+ else Redact.redactable?(value) ? Redact.render(value) : value
205
+ end
206
+ end
207
+
208
+ # Classifies one Hash's members. Returns what survives, and whether any
209
+ # member was dropped.
210
+ def walk_hash(mapping, groups, walk)
211
+ out = {}
212
+ changed = false
213
+ mapping.each do |raw_k, raw_v|
214
+ return [out, true] unless walk.spend? # the budget is spent: drop the remaining members
215
+
216
+ k = raw_k.to_s
217
+ # Capture-time redaction first, so the replacer never sees a raw Secret or Masked.
218
+ val = Redact.redactable?(raw_v) ? Redact.render(raw_v) : raw_v
219
+
220
+ if walk.replacer
221
+ replaced = walk.replacer.call(groups, k, val)
222
+ k, val = replaced
223
+ k = k.to_s
224
+ if replaced.nil? || k.empty?
225
+ changed = true
226
+ next
227
+ end
228
+ end
229
+
230
+ case decide(Spec::Signal::LOGS, (groups + [k]).join("."))
231
+ when :drop
232
+ changed = true
233
+ when :rewrite
234
+ out[k] = tokenize(val)
235
+ else
236
+ member, keep, member_changed = walk_value(val, groups + [k], 0, walk)
237
+ changed ||= member_changed
238
+ out[k] = member if keep
239
+ end
240
+ end
241
+ [out, changed]
242
+ end
243
+
244
+ # Classifies one value held under the effective key path. Returns the
245
+ # classified value, whether to keep it, and whether classification
246
+ # dropped anything. depth counts Array nesting, and a Hash member starts
247
+ # again at zero, so a Hash is bounded by the length of its effective key
248
+ # and an Array by its nesting.
249
+ def walk_value(value, path, depth, walk)
250
+ value = Redact.render(value) if Redact.redactable?(value)
251
+ case value
252
+ when nil, true, false, Integer, Float, String then return [value, true, false]
253
+ when Hash, Array then nil
254
+ else return [value.to_s, true, false]
255
+ end
256
+
257
+ if depth >= PII::MAX_COMPOSITE_DEPTH || path.length > PII::MAX_COMPOSITE_DEPTH || !walk.spend? || walk.active.key?(value)
258
+ return [nil, false, true]
259
+ end
260
+
261
+ walk.active[value] = true
262
+ begin
263
+ out, changed = value.is_a?(Hash) ? walk_hash(value, path, walk) : walk_array(value, path, depth, walk)
264
+ [out, !out.empty? || !changed, changed]
265
+ ensure
266
+ walk.active.delete(value)
267
+ end
268
+ end
269
+
270
+ def walk_array(list, path, depth, walk)
271
+ kept = []
272
+ changed = false
273
+ list.each do |el|
274
+ unless walk.spend?
275
+ changed = true # the budget is spent: drop the remaining elements
276
+ break
277
+ end
278
+ member, keep, member_changed = walk_value(el, path, depth + 1, walk)
279
+ changed ||= member_changed
280
+ kept << member if keep
281
+ end
282
+ [kept, changed]
283
+ end
284
+ end
285
+ end
286
+ end
@@ -0,0 +1,87 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "opentelemetry"
4
+
5
+ module Libo11y
6
+ module Internal
7
+ # Inject-only baggage egress filter wrapping any OpenTelemetry propagator.
8
+ class BaggageEgressPropagator
9
+ def initialize(inner, allow_predicate = nil)
10
+ @inner = inner
11
+ @allow = allow_predicate
12
+ end
13
+
14
+ def inject(carrier, context: OpenTelemetry::Context.current, setter: OpenTelemetry::Context::Propagation.text_map_setter)
15
+ ctx = filter_baggage(context)
16
+ @inner.inject(carrier, context: ctx, setter: setter)
17
+ end
18
+
19
+ def extract(carrier, context: OpenTelemetry::Context.current, getter: OpenTelemetry::Context::Propagation.text_map_getter)
20
+ @inner.extract(carrier, context: context, getter: getter)
21
+ end
22
+
23
+ def fields
24
+ @inner.respond_to?(:fields) ? @inner.fields : []
25
+ end
26
+
27
+ private
28
+
29
+ def filter_baggage(context)
30
+ return context if @allow.nil?
31
+
32
+ values = OpenTelemetry::Baggage.values(context: context)
33
+ return context if values.nil? || values.empty?
34
+
35
+ kept = {}
36
+ values.each do |k, v|
37
+ kept[k] = v if @allow.call(k)
38
+ end
39
+ return context if kept.size == values.size
40
+
41
+ filtered_ctx = OpenTelemetry::Baggage.clear(context: context)
42
+ kept.each do |k, v|
43
+ filtered_ctx = OpenTelemetry::Baggage.set_value(k, v, context: filtered_ctx)
44
+ end
45
+ filtered_ctx
46
+ end
47
+ end
48
+
49
+ module Propagators
50
+ module_function
51
+
52
+ def build(propagators_opt, baggage_egress_allow)
53
+ list = if propagators_opt.nil?
54
+ [
55
+ OpenTelemetry::Trace::Propagation::TraceContext.text_map_propagator,
56
+ OpenTelemetry::Baggage::Propagation.text_map_propagator
57
+ ]
58
+ elsif propagators_opt.is_a?(Array)
59
+ propagators_opt
60
+ else
61
+ [propagators_opt]
62
+ end
63
+
64
+ inner = CompositePropagator.new(list)
65
+ BaggageEgressPropagator.new(inner, baggage_egress_allow)
66
+ end
67
+
68
+ class CompositePropagator
69
+ def initialize(propagators)
70
+ @propagators = propagators
71
+ end
72
+
73
+ def inject(carrier, context: OpenTelemetry::Context.current, setter: OpenTelemetry::Context::Propagation.text_map_setter)
74
+ @propagators.each { |p| p.inject(carrier, context: context, setter: setter) }
75
+ end
76
+
77
+ def extract(carrier, context: OpenTelemetry::Context.current, getter: OpenTelemetry::Context::Propagation.text_map_getter)
78
+ @propagators.reduce(context) { |ctx, p| p.extract(carrier, context: ctx, getter: getter) }
79
+ end
80
+
81
+ def fields
82
+ @propagators.flat_map { |p| p.respond_to?(:fields) ? p.fields : [] }.uniq
83
+ end
84
+ end
85
+ end
86
+ end
87
+ end
@@ -0,0 +1,178 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "socket"
5
+ require "opentelemetry/sdk"
6
+ require_relative "../errors"
7
+ require_relative "../spec"
8
+ require_relative "env"
9
+ require_relative "identity"
10
+
11
+ module Libo11y
12
+ module Internal
13
+ module ResourceBuilder
14
+ UNKNOWN_VERSION = "0.0.0-unknown"
15
+ CGROUP_ID_RE = /\b([0-9a-f]{64})\b/i
16
+
17
+ Result = Data.define(:resource, :attributes, :service_name, :environment, :service_version, :instance_id)
18
+
19
+ module_function
20
+
21
+ def detect_container_id
22
+ return nil unless File.readable?("/proc/self/cgroup")
23
+
24
+ File.foreach("/proc/self/cgroup") do |line|
25
+ m = CGROUP_ID_RE.match(line)
26
+ return m[1].downcase if m
27
+ end
28
+ nil
29
+ rescue StandardError
30
+ nil
31
+ end
32
+
33
+ def load_build_info(opt)
34
+ return {} if opt.nil?
35
+ return opt.transform_keys(&:to_s) if opt.is_a?(Hash)
36
+
37
+ if opt.is_a?(String) && File.file?(opt)
38
+ JSON.parse(File.read(opt))
39
+ else
40
+ {}
41
+ end
42
+ rescue StandardError
43
+ {}
44
+ end
45
+
46
+ def build(options, env_map, policy, recorder)
47
+ env_res = Env.parse_resource_attributes(env_map["OTEL_RESOURCE_ATTRIBUTES"])
48
+ opt_res = (options.resource_attributes || {}).transform_keys(&:to_s)
49
+ build_info = options.build_info_enabled ? load_build_info(options.build_info) : {}
50
+
51
+ # Service name precedence: option > OTEL_SERVICE_NAME > OTEL_RESOURCE_ATTRIBUTES > resource_attributes
52
+ service_name = options.service_name ||
53
+ env_map["OTEL_SERVICE_NAME"] ||
54
+ env_res["service.name"] ||
55
+ opt_res["service.name"]
56
+ service_name = service_name.to_s.strip
57
+
58
+ if service_name.empty? || service_name == "unknown_service" || service_name.start_with?("unknown_service:")
59
+ raise NoServiceName if options.strict_identity
60
+
61
+ recorder&.record(Spec::Signal::RESOURCE, "identity_service_name")
62
+ service_name = "unknown_service" if service_name.empty?
63
+
64
+ end
65
+
66
+ # Environment precedence: option > OTEL_RESOURCE_ATTRIBUTES > resource_attributes
67
+ environment = options.environment ||
68
+ env_res["deployment.environment.name"] ||
69
+ opt_res["deployment.environment.name"]
70
+ environment = environment.to_s.strip
71
+
72
+ allowed_envs = Spec::ENVIRONMENT_VALUES.dup
73
+ Array(options.extra_environments).each { |e| allowed_envs.add(e.to_s) }
74
+
75
+ if environment.empty?
76
+ raise NoEnvironment if options.strict_identity
77
+
78
+ recorder&.record(Spec::Signal::RESOURCE, "identity_environment")
79
+
80
+ elsif !allowed_envs.include?(environment)
81
+ raise InvalidEnvironment, "o11y: deployment environment #{environment.inspect} not in the allowed set" if options.strict_identity
82
+
83
+ recorder&.record(Spec::Signal::RESOURCE, "identity_environment_invalid")
84
+
85
+ end
86
+
87
+ # Service version
88
+ version = options.version ||
89
+ opt_res["service.version"] ||
90
+ env_res["service.version"] ||
91
+ build_info["version"] ||
92
+ build_info["service.version"]
93
+ version = version.to_s.strip
94
+ version_fallback = version.empty?
95
+ version = UNKNOWN_VERSION if version_fallback
96
+
97
+ # Instance ID
98
+ pod_uid = opt_res["k8s.pod.uid"] || env_res["k8s.pod.uid"] || ""
99
+ pod_name = opt_res["k8s.pod.name"] || env_res["k8s.pod.name"] || ""
100
+ k8s_ns = opt_res["k8s.namespace.name"] || env_res["k8s.namespace.name"] || ""
101
+ instance_id = options.service_instance_id ||
102
+ opt_res["service.instance.id"] ||
103
+ env_res["service.instance.id"] ||
104
+ Identity.derive_instance_id(pod_uid: pod_uid, pod_name: pod_name, namespace: k8s_ns) ||
105
+ Identity.random_instance_id
106
+
107
+ attrs = {
108
+ "telemetry.sdk.name" => "opentelemetry",
109
+ "telemetry.sdk.language" => "ruby",
110
+ "telemetry.sdk.version" => OpenTelemetry::SDK::VERSION,
111
+ "telemetry.distro.name" => "libo11y",
112
+ "telemetry.distro.version" => Libo11y::VERSION,
113
+ "process.runtime.name" => RUBY_ENGINE,
114
+ "process.runtime.version" => RUBY_VERSION,
115
+ "process.runtime.description" => RUBY_DESCRIPTION
116
+ }
117
+
118
+ begin
119
+ hostname = Socket.gethostname
120
+ attrs["host.name"] = hostname unless hostname.nil? || hostname.empty?
121
+ rescue StandardError
122
+ nil
123
+ end
124
+
125
+ cid = detect_container_id
126
+ attrs["container.id"] = cid if cid
127
+
128
+ if options.build_info_enabled && !build_info.empty?
129
+ attrs["vcs.ref.head.revision"] = build_info["vcs_revision"].to_s if build_info["vcs_revision"]
130
+ attrs[Spec::ATTR_BUILD_TIME] = build_info["build_time"].to_s if build_info["build_time"]
131
+ attrs[Spec::ATTR_BUILD_MODIFIED] = build_info["build_modified"] unless build_info["build_modified"].nil?
132
+ end
133
+
134
+ # Merge env resource attributes, then explicit resource attributes
135
+ attrs.merge!(env_res)
136
+ attrs.merge!(opt_res)
137
+
138
+ attrs["service.name"] = service_name
139
+ attrs["service.version"] = version
140
+ attrs["service.instance.id"] = instance_id
141
+ attrs["deployment.environment.name"] = environment unless environment.empty?
142
+ attrs["service.namespace"] = options.service_namespace.to_s if options.service_namespace && !options.service_namespace.to_s.empty?
143
+
144
+ # Classify the entire resource through the sensitivity policy once at construction
145
+ classified, = policy.classify_flat(Spec::Signal::RESOURCE, attrs)
146
+
147
+ # Keep only valid OTel attribute values
148
+ sanitized = {}
149
+ classified.each do |k, v|
150
+ sanitized[k.to_s] = normalize_otel_value(v) unless v.nil?
151
+ end
152
+
153
+ sanitized_frozen = sanitized.freeze
154
+ otel_res = OpenTelemetry::SDK::Resources::Resource.create(sanitized_frozen)
155
+ schema_url = Spec::SCHEMA_URL
156
+ otel_res.define_singleton_method(:schema_url) { schema_url }
157
+ otel_res.define_singleton_method(:attributes) { sanitized_frozen }
158
+
159
+ Result.new(
160
+ resource: otel_res,
161
+ attributes: sanitized_frozen,
162
+ service_name: service_name,
163
+ environment: environment,
164
+ service_version: version,
165
+ instance_id: instance_id
166
+ )
167
+ end
168
+
169
+ def normalize_otel_value(v)
170
+ case v
171
+ when String, Integer, Float, TrueClass, FalseClass then v
172
+ when Array then v.map(&:to_s)
173
+ else v.to_s
174
+ end
175
+ end
176
+ end
177
+ end
178
+ end
@@ -0,0 +1,86 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Libo11y
4
+ module Internal
5
+ # Zero-dependency Ruby runtime and semantic-convention process metrics.
6
+ module RuntimeMetrics
7
+ module_function
8
+
9
+ def register(meter_provider)
10
+ meter = meter_provider.meter("libo11y.runtime", version: Libo11y::VERSION)
11
+
12
+ meter.create_observable_counter(
13
+ "ruby.gc.count",
14
+ unit: "{collection}",
15
+ description: "Total Ruby garbage collections.",
16
+ callback: lambda do
17
+ GC.count
18
+ end
19
+ )
20
+
21
+ meter.create_observable_gauge(
22
+ "ruby.gc.heap_live_slots",
23
+ unit: "{slot}",
24
+ description: "Live object slots on the Ruby heap.",
25
+ callback: lambda do
26
+ GC.stat(:heap_live_slots)
27
+ end
28
+ )
29
+
30
+ meter.create_observable_gauge(
31
+ "process.thread.count",
32
+ unit: "{thread}",
33
+ description: "Number of active Ruby threads.",
34
+ callback: lambda do
35
+ Thread.list.size
36
+ end
37
+ )
38
+
39
+ meter.create_observable_counter(
40
+ "process.cpu.time",
41
+ unit: "s",
42
+ description: "Process CPU time in seconds.",
43
+ callback: lambda do
44
+ t = Process.times
45
+ t.utime + t.stime
46
+ end
47
+ )
48
+
49
+ if File.readable?("/proc/self/statm")
50
+ meter.create_observable_gauge(
51
+ "process.memory.usage",
52
+ unit: "By",
53
+ description: "Resident set size in bytes.",
54
+ callback: lambda do
55
+ read_rss_bytes
56
+ end
57
+ )
58
+ end
59
+
60
+ return unless File.directory?("/proc/self/fd")
61
+
62
+ meter.create_observable_gauge(
63
+ "process.unix.file_descriptor.count",
64
+ unit: "{file_descriptor}",
65
+ description: "Open file descriptors.",
66
+ callback: lambda do
67
+ Dir.children("/proc/self/fd").size
68
+ rescue StandardError
69
+ 0
70
+ end
71
+ )
72
+ rescue StandardError
73
+ nil
74
+ end
75
+
76
+ def read_rss_bytes
77
+ parts = File.read("/proc/self/statm").split
78
+ return 0 if parts.length < 2
79
+
80
+ parts[1].to_i * 4096
81
+ rescue StandardError
82
+ 0
83
+ end
84
+ end
85
+ end
86
+ end