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.
Files changed (38) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +170 -21
  3. data/README.md +77 -8
  4. data/lib/libo11y/{proc.rb → child_process.rb} +12 -2
  5. data/lib/libo11y/db.rb +22 -10
  6. data/lib/libo11y/detached.rb +241 -29
  7. data/lib/libo11y/http_client.rb +48 -15
  8. data/lib/libo11y/internal/bridges.rb +3553 -255
  9. data/lib/libo11y/internal/endpoint.rb +7 -1
  10. data/lib/libo11y/internal/env.rb +177 -59
  11. data/lib/libo11y/internal/error_type.rb +17 -0
  12. data/lib/libo11y/internal/histogram_buckets.rb +42 -0
  13. data/lib/libo11y/internal/http_common.rb +2 -0
  14. data/lib/libo11y/internal/identity.rb +10 -1
  15. data/lib/libo11y/internal/injected.rb +178 -0
  16. data/lib/libo11y/internal/logging_device.rb +141 -32
  17. data/lib/libo11y/internal/path_match.rb +148 -0
  18. data/lib/libo11y/internal/pii.rb +185 -65
  19. data/lib/libo11y/internal/pipeline.rb +141 -34
  20. data/lib/libo11y/internal/policy.rb +556 -52
  21. data/lib/libo11y/internal/propagators.rb +29 -6
  22. data/lib/libo11y/internal/quiet_inspect.rb +20 -0
  23. data/lib/libo11y/internal/resource.rb +187 -52
  24. data/lib/libo11y/internal/sdk_load.rb +64 -0
  25. data/lib/libo11y/internal/sql_text.rb +365 -67
  26. data/lib/libo11y/internal/summary.rb +2 -1
  27. data/lib/libo11y/options.rb +159 -1
  28. data/lib/libo11y/rack.rb +257 -44
  29. data/lib/libo11y/record.rb +70 -7
  30. data/lib/libo11y/redact.rb +87 -21
  31. data/lib/libo11y/signals.rb +70 -29
  32. data/lib/libo11y/spec/app_registry.rb +97 -61
  33. data/lib/libo11y/spec/yaml_v3.rb +179 -111
  34. data/lib/libo11y/telemetry.rb +315 -53
  35. data/lib/libo11y/testing.rb +31 -19
  36. data/lib/libo11y/version.rb +1 -1
  37. data/lib/libo11y.rb +1 -1
  38. metadata +94 -39
@@ -63,20 +63,43 @@ module Libo11y
63
63
  end
64
64
 
65
65
  class CompositePropagator
66
+ # The header names the propagators own, read once here. A propagator
67
+ # whose fields raises is reported and counted as owning none, so it
68
+ # can fail neither the start nor a later call.
69
+ attr_reader :fields
70
+
66
71
  def initialize(propagators)
67
72
  @propagators = propagators
73
+ @fields = propagators.flat_map do |propagator|
74
+ propagator.respond_to?(:fields) ? Array(propagator.fields).map(&:to_s) : []
75
+ rescue StandardError => e
76
+ OpenTelemetry.handle_error(exception: e, message: "libo11y: #{propagator.class} raised in fields")
77
+ []
78
+ end.uniq.freeze
68
79
  end
69
80
 
81
+ # A propagator that raises is reported to OpenTelemetry's error
82
+ # handler and skipped, as OpenTelemetry's own composite propagator
83
+ # does: a fault in telemetry must not fail the request or the call
84
+ # it rides on.
70
85
  def inject(carrier, context: OpenTelemetry::Context.current, setter: OpenTelemetry::Context::Propagation.text_map_setter)
71
- @propagators.each { |p| p.inject(carrier, context: context, setter: setter) }
86
+ @propagators.each do |propagator|
87
+ staged = {}
88
+ propagator.inject(staged, context: context, setter: OpenTelemetry::Context::Propagation.text_map_setter)
89
+ staged.each { |key, value| setter.set(carrier, key, value) }
90
+ rescue StandardError => e
91
+ OpenTelemetry.handle_error(exception: e, message: "libo11y: #{propagator.class} raised in inject")
92
+ end
93
+ nil
72
94
  end
73
95
 
74
96
  def extract(carrier, context: OpenTelemetry::Context.current, getter: OpenTelemetry::Context::Propagation.text_map_getter)
75
- @propagators.reduce(context) { |ctx, p| p.extract(carrier, context: ctx, getter: getter) }
76
- end
77
-
78
- def fields
79
- @propagators.flat_map { |p| p.respond_to?(:fields) ? p.fields : [] }.uniq
97
+ @propagators.reduce(context) do |extracted, propagator|
98
+ propagator.extract(carrier, context: extracted, getter: getter)
99
+ rescue StandardError => e
100
+ OpenTelemetry.handle_error(exception: e, message: "libo11y: #{propagator.class} raised in extract")
101
+ extracted
102
+ end
80
103
  end
81
104
  end
82
105
  end
@@ -0,0 +1,20 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Libo11y
4
+ module Internal
5
+ # An inspect that shows the class and nothing else. Ruby's own prints
6
+ # every instance variable, and those of libo11y's objects lead to the
7
+ # OTLP exporters, whose headers and endpoints may hold credentials, and
8
+ # to the PII hash key. An error message, a debugger or a stray log line
9
+ # inspects whatever it is given.
10
+ module QuietInspect
11
+ def inspect
12
+ "#<#{self.class.name}>"
13
+ end
14
+
15
+ def pretty_print(printer)
16
+ printer.text(inspect)
17
+ end
18
+ end
19
+ end
20
+ end
@@ -1,48 +1,131 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require "json"
4
+ require "pathname"
4
5
  require "socket"
5
- require "opentelemetry/sdk"
6
+ require_relative "sdk_load"
6
7
  require_relative "../errors"
7
8
  require_relative "../spec"
8
9
  require_relative "env"
9
10
  require_relative "identity"
11
+ require_relative "policy"
10
12
 
11
13
  module Libo11y
12
14
  module Internal
13
15
  module ResourceBuilder
14
16
  UNKNOWN_VERSION = "0.0.0-unknown"
15
- CGROUP_ID_RE = /\b([0-9a-f]{64})\b/i
17
+ # A container ID: 64 lower-case hex digits, and nothing beside them.
18
+ CONTAINER_ID = /\A[0-9a-f]{64}\z/
16
19
 
17
20
  Result = Data.define(:resource, :attributes, :service_name, :environment, :service_version, :instance_id, :version_fallback)
18
21
 
19
22
  module_function
20
23
 
21
- def detect_container_id
22
- return nil unless File.readable?("/proc/self/cgroup")
24
+ # The container ID of this process, or nil outside a container. The
25
+ # cgroup file names it under cgroup v1 and under cgroup v2 with
26
+ # systemd. Under cgroup v2 with a cgroup namespace that file shows
27
+ # only the namespace's root, and the mount table still names it. The
28
+ # rules are those of the Python implementation.
29
+ #
30
+ # @param read [#call, nil] reads a file under /proc and returns its
31
+ # text, or nil. Without one the files of this process are read, on
32
+ # Linux only.
33
+ def detect_container_id(read = nil)
34
+ if read.nil?
35
+ return nil unless RUBY_PLATFORM.include?("linux")
23
36
 
24
- File.foreach("/proc/self/cgroup") do |line|
25
- m = CGROUP_ID_RE.match(line)
26
- return m[1].downcase if m
37
+ read = method(:read_proc)
27
38
  end
39
+ cgroup = read.call("/proc/self/cgroup")
40
+ found = container_id_from_cgroup(cgroup) if cgroup
41
+ return found if found
42
+
43
+ mountinfo = read.call("/proc/self/mountinfo")
44
+ container_id_from_mountinfo(mountinfo) if mountinfo
45
+ end
46
+
47
+ def read_proc(path)
48
+ File.read(path, encoding: Encoding::UTF_8).scrub
49
+ rescue SystemCallError, IOError
28
50
  nil
29
- rescue StandardError
51
+ end
52
+
53
+ # The container ID in the text of /proc/self/cgroup. Each line is
54
+ # hierarchy:controllers:path, for cgroup v1 and v2 alike. The ID is the
55
+ # innermost path segment that names one, on the first line that has
56
+ # one. A run of 64 hex digits inside a longer segment is not an ID.
57
+ def container_id_from_cgroup(text)
58
+ text.each_line do |line|
59
+ parts = line.split(":", 3)
60
+ next unless parts.length == 3
61
+
62
+ parts[2].strip.split("/").reverse_each do |segment|
63
+ found = container_id_in_segment(segment)
64
+ return found if found
65
+ end
66
+ end
30
67
  nil
31
68
  end
32
69
 
33
- def load_build_info(opt)
34
- return {} if opt.nil?
35
- return opt.transform_keys(&:to_s) if opt.is_a?(Hash)
70
+ # The container ID a cgroup path segment names, if it names one: the
71
+ # bare ID, or a runtime prefix joined to it by a dash or a colon
72
+ # (docker-, crio-, libpod-, cri-containerd-, cri-containerd:), each
73
+ # with or without systemd's .scope suffix.
74
+ def container_id_in_segment(segment)
75
+ candidate = segment.delete_suffix(".scope")
76
+ cut = [candidate.rindex("-") || -1, candidate.rindex(":") || -1].max
77
+ candidate = candidate[(cut + 1)..]
78
+ CONTAINER_ID.match?(candidate) ? candidate : nil
79
+ end
80
+
81
+ # The container ID in the text of /proc/self/mountinfo. A container
82
+ # runtime bind-mounts /etc/hostname from a directory named after the
83
+ # container. Only that mount is read: overlay layers and volumes have
84
+ # 64-digit IDs of their own.
85
+ def container_id_from_mountinfo(text)
86
+ text.each_line do |line|
87
+ fields = line.split
88
+ next if fields.length < 5 || fields[4] != "/etc/hostname"
36
89
 
37
- if opt.is_a?(String) && File.file?(opt)
38
- JSON.parse(File.read(opt))
39
- else
40
- {}
90
+ found = fields[3].split("/").find { |segment| CONTAINER_ID.match?(segment) }
91
+ return found if found
41
92
  end
93
+ nil
94
+ end
95
+
96
+ # The build info: a Hash, or the JSON object in the file a String or a
97
+ # Pathname names. Anything else, and a file that cannot be read or
98
+ # holds no JSON object, gives no build info.
99
+ def load_build_info(opt)
100
+ return opt.transform_keys { |k| SensitivityPolicy.utf8_safe(k.to_s) } if opt.is_a?(Hash)
101
+ return {} unless opt.is_a?(String) || opt.is_a?(Pathname)
102
+ return {} unless File.file?(opt)
103
+
104
+ parsed = JSON.parse(File.read(opt))
105
+ parsed.is_a?(Hash) ? parsed : {}
42
106
  rescue StandardError
43
107
  {}
44
108
  end
45
109
 
110
+ # A build info boolean: true, false, or the text of either. Anything
111
+ # else is nil, because the registry declares the attribute a boolean.
112
+ def build_flag(value)
113
+ return value if [true, false].include?(value)
114
+ return nil unless value.is_a?(String)
115
+
116
+ { "true" => true, "false" => false }[SensitivityPolicy.utf8_safe(value).strip.downcase]
117
+ end
118
+
119
+ # A build info value as text, or nil when it is missing or blank.
120
+ def build_value(build_info, key)
121
+ text = SensitivityPolicy.utf8_safe(build_info[key].to_s).strip
122
+ text.empty? ? nil : text
123
+ end
124
+
125
+ def build_version(build_info)
126
+ build_value(build_info, "version") || build_value(build_info, "service.version")
127
+ end
128
+
46
129
  # Composes, validates and classifies the resource. Precedence, lowest to
47
130
  # highest: what libo11y detects and the build info, then the
48
131
  # environment (OTEL_RESOURCE_ATTRIBUTES, then OTEL_SERVICE_NAME), then
@@ -56,34 +139,18 @@ module Libo11y
56
139
  env_name = Env.value(env_map, "OTEL_SERVICE_NAME")
57
140
  attrs["service.name"] = env_name if env_name
58
141
 
59
- attrs.merge!((options.resource_attributes || {}).transform_keys(&:to_s))
60
- {
61
- "service.name" => options.service_name,
62
- "service.namespace" => options.service_namespace,
63
- "deployment.environment.name" => options.environment,
64
- "service.version" => options.version,
65
- "service.instance.id" => options.service_instance_id
66
- }.each do |key, option|
67
- text = option.to_s.strip
68
- attrs[key] = text unless text.empty?
69
- end
70
- attrs["service.version"] ||= build_info["version"] || build_info["service.version"]
71
-
142
+ attrs.merge!((options.resource_attributes || {}).transform_keys { |k| SensitivityPolicy.normalize_key(k) })
143
+ apply_named_options(attrs, options, build_info)
72
144
  enforce_identity(attrs, options, recorder)
73
145
 
74
- version_fallback = attrs["service.version"].to_s.strip.empty?
146
+ version_fallback = string_attr(attrs, "service.version").empty?
75
147
  attrs["service.version"] = UNKNOWN_VERSION if version_fallback
76
- if attrs["service.instance.id"].to_s.strip.empty?
77
- attrs["service.instance.id"] = Identity.derive_instance_id(
78
- pod_uid: attrs["k8s.pod.uid"].to_s, pod_name: attrs["k8s.pod.name"].to_s, namespace: attrs["k8s.namespace.name"].to_s
79
- ) || Identity.random_instance_id
80
- end
81
- attrs.delete("deployment.environment.name") if attrs["deployment.environment.name"].to_s.strip.empty?
148
+ ensure_instance_id(attrs)
82
149
 
83
- service_name = attrs["service.name"]
84
- environment = attrs["deployment.environment.name"].to_s
85
- version = attrs["service.version"]
86
- instance_id = attrs["service.instance.id"]
150
+ service_name = raw_string_attr(attrs, "service.name")
151
+ environment = raw_string_attr(attrs, "deployment.environment.name")
152
+ version = raw_string_attr(attrs, "service.version")
153
+ instance_id = raw_string_attr(attrs, "service.instance.id")
87
154
 
88
155
  # Classify the entire resource through the sensitivity policy once at construction
89
156
  classified, = policy.classify_flat(Spec::Signal::RESOURCE, attrs)
@@ -126,9 +193,12 @@ module Libo11y
126
193
  attrs["host.name"] = hostname if hostname
127
194
  cid = detect_container_id
128
195
  attrs["container.id"] = cid if cid
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?
196
+ revision = build_value(build_info, "vcs_revision")
197
+ attrs["vcs.ref.head.revision"] = revision if revision
198
+ build_time = build_value(build_info, "build_time")
199
+ attrs[Spec::ATTR_BUILD_TIME] = build_time if build_time
200
+ modified = build_flag(build_info["build_modified"])
201
+ attrs[Spec::ATTR_BUILD_MODIFIED] = modified unless modified.nil?
132
202
  attrs
133
203
  end
134
204
 
@@ -139,22 +209,68 @@ module Libo11y
139
209
  nil
140
210
  end
141
211
 
212
+ # Trims Go Unicode White_Space after normalizing to valid UTF-8 so
213
+ # non-UTF-8 or BINARY values never raise EncodingError.
214
+ def trim_unicode_space(str)
215
+ Spec::AppRegistry.go_trim_space(SensitivityPolicy.utf8_safe(str))
216
+ end
217
+
218
+ # Returns the Go-trimmed (Unicode White_Space) String value of attrs[key],
219
+ # or "" when missing or not a String, matching Go's strings.TrimSpace(resourceString(...)).
220
+ def string_attr(attrs, key)
221
+ val = attrs[key]
222
+ val.is_a?(String) ? trim_unicode_space(val) : ""
223
+ end
224
+
225
+ # Returns the UTF-8-normalized raw String value of attrs[key] without
226
+ # trimming, or "" when missing or not a String, matching Go's resourceString.
227
+ def raw_string_attr(attrs, key)
228
+ val = attrs[key]
229
+ val.is_a?(String) ? SensitivityPolicy.utf8_safe(val) : ""
230
+ end
231
+
232
+ def apply_named_options(attrs, options, build_info)
233
+ {
234
+ "service.name" => options.service_name,
235
+ "service.namespace" => options.service_namespace,
236
+ "deployment.environment.name" => options.environment,
237
+ "service.version" => options.version,
238
+ "service.instance.id" => options.service_instance_id
239
+ }.each do |key, option|
240
+ text = trim_unicode_space(option.to_s)
241
+ attrs[key] = text unless text.empty?
242
+ end
243
+ return unless string_attr(attrs, "service.version").empty?
244
+
245
+ bv = build_version(build_info)
246
+ attrs["service.version"] = bv if bv
247
+ end
248
+
249
+ def ensure_instance_id(attrs)
250
+ return unless string_attr(attrs, "service.instance.id").empty?
251
+
252
+ attrs["service.instance.id"] = Identity.derive_instance_id(
253
+ pod_uid: raw_string_attr(attrs, "k8s.pod.uid"),
254
+ pod_name: raw_string_attr(attrs, "k8s.pod.name"),
255
+ namespace: raw_string_attr(attrs, "k8s.namespace.name")
256
+ ) || Identity.random_instance_id
257
+ end
258
+
142
259
  # Applies the tier-0 identity contract. Under strict identity a
143
260
  # violation raises. Otherwise each one is counted on
144
261
  # o11y.schema.violations.
145
262
  def enforce_identity(attrs, options, recorder)
146
- name = attrs["service.name"].to_s.strip
263
+ name = string_attr(attrs, "service.name")
147
264
  if name.empty? || name == "unknown_service" || name.start_with?("unknown_service:")
148
265
  raise NoServiceName if options.strict_identity
149
266
 
150
267
  recorder&.record(Spec::Signal::RESOURCE, "identity_service_name")
151
- attrs["service.name"] = "unknown_service" if name.empty?
152
- else
153
- attrs["service.name"] = name
268
+ attrs["service.name"] = "unknown_service" if attrs["service.name"].nil?
154
269
  end
155
270
 
156
- environment = attrs["deployment.environment.name"].to_s.strip
157
- allowed = Spec::ENVIRONMENT_VALUES.to_a.map(&:to_s) | Array(options.extra_environments).map(&:to_s)
271
+ environment = raw_string_attr(attrs, "deployment.environment.name")
272
+ allowed = Spec::ENVIRONMENT_VALUES.to_a.map(&:to_s) |
273
+ Array(options.extra_environments).map { |e| SensitivityPolicy.utf8_safe(e.to_s) }
158
274
  if environment.empty?
159
275
  raise NoEnvironment if options.strict_identity
160
276
 
@@ -167,14 +283,33 @@ module Libo11y
167
283
 
168
284
  recorder&.record(Spec::Signal::RESOURCE, "identity_environment_invalid")
169
285
  end
170
- attrs["deployment.environment.name"] = environment
171
286
  end
172
287
 
288
+ # An attribute value OpenTelemetry accepts. A list of strings, of
289
+ # booleans or of numbers keeps its type, and any other list becomes
290
+ # strings. Mutable strings and arrays are snapshotted and frozen so
291
+ # later caller edits cannot corrupt exported resources.
173
292
  def normalize_otel_value(v)
174
293
  case v
175
- when String, Integer, Float, TrueClass, FalseClass then v
176
- when Array then v.map(&:to_s)
177
- else v.to_s
294
+ when String then snapshot_string(v)
295
+ when Integer then v.between?(SensitivityPolicy::INT64_MIN, SensitivityPolicy::INT64_MAX) ? v : v.to_s.freeze
296
+ when Float, TrueClass, FalseClass then v
297
+ when Array
298
+ items = v.map { |el| el.is_a?(Integer) && !el.between?(SensitivityPolicy::INT64_MIN, SensitivityPolicy::INT64_MAX) ? el.to_s : el }
299
+ items = items.map(&:to_s) unless typed_list?(items)
300
+ items.map { |el| el.is_a?(String) ? snapshot_string(el) : el }.freeze
301
+ else snapshot_string(v.to_s)
302
+ end
303
+ end
304
+
305
+ def snapshot_string(str)
306
+ safe = SensitivityPolicy.utf8_safe(str)
307
+ safe.frozen? ? safe : safe.dup.freeze
308
+ end
309
+
310
+ def typed_list?(list)
311
+ [[String], [Integer, Float], [TrueClass, FalseClass]].any? do |types|
312
+ list.all? { |element| types.any? { |type| element.is_a?(type) } }
178
313
  end
179
314
  end
180
315
  end
@@ -0,0 +1,64 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "opentelemetry"
4
+
5
+ module Libo11y
6
+ module Internal
7
+ # Loads the OpenTelemetry SDKs. Every libo11y file that needs them
8
+ # requires this one.
9
+ #
10
+ # The trace and log SDKs read the attribute limit variables of the
11
+ # process environment while they load, to build their default limits,
12
+ # and raise for a value they refuse: a count that is not positive, a
13
+ # value length under 32, or text that is no integer. A process with
14
+ # such a variable could then not load libo11y at all, whatever env a
15
+ # handle is given. So those variables are taken out of the environment
16
+ # while the SDKs load and put back after, and the SDKs build their
17
+ # defaults without them. A variable the SDKs accept is left alone.
18
+ # libo11y reads the limits again, from the env of each handle, when the
19
+ # handle is built.
20
+ module SdkLoad
21
+ COUNT_LIMIT = /\AOTEL_(?:[A-Z]+_)*COUNT_LIMIT\z/
22
+ LENGTH_LIMIT = /\AOTEL_(?:[A-Z]+_)*LENGTH_LIMIT\z/
23
+ # The least value length the SDKs accept.
24
+ MIN_LENGTH = 32
25
+ private_constant :COUNT_LIMIT, :LENGTH_LIMIT, :MIN_LENGTH
26
+
27
+ module_function
28
+
29
+ def load_sdks
30
+ hidden = ENV.select { |name, value| refused?(name, value) }
31
+ hidden.each_key { |name| ENV.delete(name) }
32
+ begin
33
+ require "opentelemetry/sdk"
34
+ require "opentelemetry-metrics-sdk"
35
+ require "opentelemetry-logs-sdk"
36
+ ensure
37
+ hidden.each { |name, value| ENV[name] = value }
38
+ end
39
+ hidden.each_key do |name|
40
+ default = COUNT_LIMIT.match?(name) ? "the SDK's default of 128 applies" : "the SDK's default applies, which is no limit"
41
+ OpenTelemetry.logger.warn("libo11y: #{name} holds a value the OpenTelemetry Ruby SDK does not accept, so #{default}")
42
+ end
43
+ end
44
+
45
+ # Whether the SDKs would raise for this variable when they load. The
46
+ # value is read as the SDKs read it, with Integer and no base, so a
47
+ # value they take, such as "0x40", stays in the environment for them.
48
+ # A handle reads its own limits in base 10, as Go does.
49
+ def refused?(name, value)
50
+ least = if COUNT_LIMIT.match?(name)
51
+ 1
52
+ elsif LENGTH_LIMIT.match?(name)
53
+ MIN_LENGTH
54
+ end
55
+ return false if least.nil?
56
+
57
+ number = Integer(value, exception: false)
58
+ number.nil? || number < least
59
+ end
60
+ end
61
+
62
+ SdkLoad.load_sdks
63
+ end
64
+ end