Class: Inspec::Telemetry::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/inspec/utils/telemetry/base.rb

Direct Known Subclasses

HTTP, Null

Constant Summary collapse

VERSION =
2.0
TYPE =
"job"
JOB_TYPE =
"InSpec"

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#scratch ⇒ Object

Returns the value of attribute scratch.



13
14
15
# File 'lib/inspec/utils/telemetry/base.rb', line 13

def scratch
  @scratch
end

Instance Method Details

#create_wrapper ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
# File 'lib/inspec/utils/telemetry/base.rb', line 20

def create_wrapper
  Inspec::Log.debug "Initialising wrapper for telemetry"
  {
    version: VERSION,
    createdTimeUTC: Time.now.getutc.iso8601,
    environment: Inspec::Telemetry::RunContextProbe.guess_run_context,
    licenseIds: fetch_license_ids,
    source: "#{Inspec::Dist::EXEC_NAME}:#{Inspec::VERSION}",
    type: TYPE,
  }
end

#fetch_license_ids ⇒ Object



15
16
17
18
# File 'lib/inspec/utils/telemetry/base.rb', line 15

def fetch_license_ids
  Inspec::Log.debug "Fetching license IDs for telemetry"
  @license_keys ||= ChefLicensing.license_keys
end

#format_control_tags(tags) ⇒ Object



112
113
114
115
116
117
118
# File 'lib/inspec/utils/telemetry/base.rb', line 112

def format_control_tags(tags)
  tags_list = []
  tags.each do |key, value|
    tags_list << { name: key.to_s, value: (value || "").to_s }
  end
  tags_list
end

#hash_to_uuid(value) ⇒ Object

Train's platform.uuid can return a raw 64-char hex identifier (e.g. a Docker container ID from /proc/self/mountinfo) instead of a proper UUID when running inside a container. Normalize such values into a valid RFC 4122 (v5-like) UUID so downstream consumers can always rely on the UUID format. Values that are already a valid UUID, or that don't match a 64-char hex string, are returned as-is.



141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
# File 'lib/inspec/utils/telemetry/base.rb', line 141

def hash_to_uuid(value)
  return nil if value.nil?

  value_str = value.to_s
  return nil if value_str.empty?

  uuid_format = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/i
  return value_str if value_str =~ uuid_format

  hex_64_format = /^[0-9a-fA-F]{64}$/i
  return value_str unless value_str =~ hex_64_format

  bytes = value_str[0, 32].scan(/.{2}/).map { |byte| byte.to_i(16) }

  time_low        = bytes[0..3].inject(0)   { |a, b| (a << 8) | b }
  time_mid        = bytes[4..5].inject(0)   { |a, b| (a << 8) | b }
  time_hi_version = bytes[6..7].inject(0)   { |a, b| (a << 8) | b }
  clock_seq       = bytes[8..9].inject(0)   { |a, b| (a << 8) | b }
  node            = bytes[10..15].inject(0) { |a, b| (a << 8) | b }

  # Set version (5) and variant (RFC 4122) bits per the UUID spec
  time_hi_version = (time_hi_version & 0x0FFF) | (5 << 12)
  clock_seq       = (clock_seq & 0x3FFF) | 0x8000

  format("%08x-%04x-%04x-%04x-%012x", time_low, time_mid, time_hi_version, clock_seq, node)
end

#note_all_invoked_features ⇒ Object



173
174
175
176
177
# File 'lib/inspec/utils/telemetry/base.rb', line 173

def note_all_invoked_features
  Inspec::Feature.list_all_invoked_features.each do |feature|
    Inspec::Telemetry.note_feature_usage(feature.to_s)
  end
end

#note_feature_usage(feature_name) ⇒ Object



32
33
34
35
36
# File 'lib/inspec/utils/telemetry/base.rb', line 32

def note_feature_usage(feature_name)
  @scratch ||= {}
  @scratch[:features] ||= []
  @scratch[:features] << feature_name
end

#note_gem_dependency_usage(opts) ⇒ Object



179
180
181
182
183
184
185
186
# File 'lib/inspec/utils/telemetry/base.rb', line 179

def note_gem_dependency_usage(opts)
  unless opts[:runner].target_profiles.map do |tp|
    tp..gem_dependencies + \
        tp.locked_dependencies.list.map { |_k, v| v.profile..gem_dependencies }.flatten
  end.flatten.empty?
    Inspec::Telemetry.note_feature_usage("inspec-gem-deps-in-profiles")
  end
end

#note_per_run_features(opts) ⇒ Object



168
169
170
171
# File 'lib/inspec/utils/telemetry/base.rb', line 168

def note_per_run_features(opts)
  note_all_invoked_features
  note_gem_dependency_usage(opts)
end

#obscure(cleartext) ⇒ Object

Hash text if non-nil



121
122
123
124
125
126
# File 'lib/inspec/utils/telemetry/base.rb', line 121

def obscure(cleartext)
  return nil if cleartext.nil?
  return nil if cleartext.empty?

  Digest::SHA2.new(256).hexdigest(cleartext)
end

#run_ending(opts) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
# File 'lib/inspec/utils/telemetry/base.rb', line 45

def run_ending(opts)
  note_per_run_features(opts)

  payload = create_wrapper

  train_platform = opts[:runner].backend.backend.platform
  payload[:platform] = safe_platform_field(train_platform, :name)

  payload[:jobs] = [{
                      type: JOB_TYPE,

                      # Target platform info
                      environment: {
                        host: obscure(URI(opts[:runner].backend.backend.uri).host) || "unknown",
                        os: safe_platform_field(train_platform, :name) || "unknown",
                        version: safe_platform_field(train_platform, :release) || "unknown",
                        architecture: safe_platform_field(train_platform, :arch) || "unknown",
                        id: hash_to_uuid(safe_platform_field(train_platform, :uuid)),
                      },

                      runtime: Inspec::VERSION,
                      content: [],  # one content == one profile
                      steps: [],    # one step == one control
                    }]

  opts[:run_data][:profiles].each do |profile|
    payload[:jobs][0][:content] << {
      name: obscure(profile[:name]),
      version: profile[:version],
      sha256: profile[:sha256],
      maintainer: profile[:maintainer] || "",
      type: "profile",
    }

    profile[:controls].each do |control|
      payload[:jobs][0][:steps] << {
        id: obscure(control[:id]),
        name: "inspec-control",
        description: control[:desc] || "",
        target: {
          mode: opts[:runner].backend.backend.backend_type,
          id: opts[:runner].backend.backend.platform.uuid,
        },
        resources: [],
        features: [],
        tags: format_control_tags(control[:tags]),
      }

      control[:results]&.each do |resource_block|
        payload[:jobs][0][:steps].last[:resources] << {
          type: "inspec-resource",
          name: resource_block[:resource_class],
          id: obscure(resource_block[:resource_title].respond_to?(:resource_id) ? resource_block[:resource_title].resource_id : nil) || "unknown",
        }
      end

      # Per-control features.
      payload[:jobs][0][:steps].last[:features] = scratch[:features].dup
    end
  end

  Inspec::Log.debug "Final data for telemetry upload -> #{payload}"
  Inspec::Log.debug "Finishing telemetry for InSpec"
  # Return payload object for testing
  payload
end

#run_starting(_opts = {}) ⇒ Object



38
39
40
41
42
43
# File 'lib/inspec/utils/telemetry/base.rb', line 38

def run_starting(_opts = {})
  Inspec::Log.debug "Initiating telemetry for InSpec"
  @scratch ||= {}
  @scratch[:features] ||= []
  @scratch[:run_start_time] = Time.now.getutc.iso8601
end

#safe_platform_field(platform, field) ⇒ Object

Safely access platform fields that may not exist



129
130
131
132
133
134
# File 'lib/inspec/utils/telemetry/base.rb', line 129

def safe_platform_field(platform, field)
  return nil if platform.nil?
  return nil unless platform.respond_to?(field)

  platform.send(field)
end