Class: Inspec::Telemetry::RunContextProbe

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

Overview

Guesses the run context of InSpec - how were we invoked? All stack values here are determined experimentally

Class Method Summary collapse

Class Method Details

.audit_cookbook?(stack) ⇒ Boolean

Returns:

  • (Boolean)


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

def self.audit_cookbook?(stack)
  stack_match(stack: stack, path: "chef/handler", label: "run_report_handlers") &&
    stack_match(stack: stack, path: "handler/audit_report", label: "report")
end

.guess_run_context(stack = nil) ⇒ Object

Guess, using stack introspection, if we were called under test-kitchen, cli, audit-cookbook, or otherwise. TODO add compliance-phase of chef-infra



19
20
21
22
23
24
25
26
# File 'lib/inspec/utils/telemetry/run_context_probe.rb', line 19

def self.guess_run_context(stack = nil)
  stack ||= caller_locations
  return "test-kitchen" if kitchen?(stack)
  return "cli" if run_by_thor?(stack)
  return "audit-cookbook" if audit_cookbook?(stack)

  "unknown"
end

.kitchen?(stack) ⇒ Boolean

Returns:

  • (Boolean)


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

def self.kitchen?(stack)
  stack_match(stack: stack, path: "kitchen/instance", label: "verify_action") &&
    stack_match(stack: stack, path: "kitchen/instance", label: "verify")
end

.run_by_thor?(stack) ⇒ Boolean

Returns:

  • (Boolean)


28
29
30
31
# File 'lib/inspec/utils/telemetry/run_context_probe.rb', line 28

def self.run_by_thor?(stack)
  stack_match(stack: stack, path: "thor/command", label: "run") &&
    stack_match(stack: stack, path: "thor/invocation", label: "invoke_command")
end

.stack_match(stack: [], label: nil, path: nil) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/inspec/utils/telemetry/run_context_probe.rb', line 43

def self.stack_match(stack: [], label: nil, path: nil)
  return false if stack.nil?

  stack.any? do |frame|
    if label && path
      frame.label == label && frame.absolute_path.include?(path)
    elsif label
      frame.label == label
    elsif path
      frame.absolute_path.include?(path)
    else
      false
    end
  end
end

.under_automate?Boolean

Guess if we are running under Automate

Returns:

  • (Boolean)


8
9
10
11
12
13
14
# File 'lib/inspec/utils/telemetry/run_context_probe.rb', line 8

def self.under_automate?
  # Currently assume we are under automate if we have an automate-based reporter
  Inspec::Config.cached[:reporter]
    .keys
    .map(&:to_s)
    .any? { |n| n =~ /automate/ }
end