Module: Contrast::Agent::AtExitHook

Extended by:
Components::Logger::InstanceMethods
Defined in:
lib/contrast/agent/hooks/at_exit_hook.rb

Overview

This module adds an at_exit hook for us to send messages that may be lost at process exit

Class Method Summary collapse

Methods included from Components::Logger::InstanceMethods

cef_logger, logger

Class Method Details

.exit_hookObject



12
13
14
15
16
17
18
19
# File 'lib/contrast/agent/hooks/at_exit_hook.rb', line 12

def self.exit_hook
  @_exit_hook ||= begin
    at_exit do
      on_exit
    end
    true
  end
end

.on_exitObject

Actions to take when a process exits. Typically called from our exit_hook, but exposed here for other process terminations, like those in Kernel#exec



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/contrast/agent/hooks/at_exit_hook.rb', line 24

def self.on_exit
  logger.debug('at_exit invoked, host application terminating',
               p_id: @pid,
               pp_id: @ppid,
               process_pid: Process.pid,
               process_pp_id: Process.ppid)
  $stdout.puts('[Contrast Agent] Graceful shutdown...')
  report_traces
  context = Contrast::Agent::REQUEST_TRACKER.current
  return unless context

  [
    Contrast::Agent::Inventory::DependencyUsageAnalysis.instance.generate_library_usage,
    context.observed_route
  ].compact.each do |event|
    Contrast::Agent.reporter&.send_event_immediately(event)
  end
  Contrast::Agent.reporter&.send_event_immediately(context.activity)
end

.report_tracesObject



44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/contrast/agent/hooks/at_exit_hook.rb', line 44

def self.report_traces
  return unless Contrast::ASSESS.enabled?
  return if ENV.fetch('CONTRAST__PIPELINE__RUN', nil) == 'true'

  collection = Contrast::Agent::Reporting::ReportingStorage.collection

  # report gathered traces:
  return if collection.empty?

  collection.each do |_id, finding|
    preflight = Contrast::Agent::Reporting::BuildPreflight.generate(finding)
    Contrast::Agent.reporter&.send_event_immediately(preflight)
  end
end