Class: ACE::ForkUtil

Inherits:
Object
  • Object
show all
Defined in:
lib/ace/fork_util.rb

Class Method Summary collapse

Class Method Details

.isolateObject

Forks and calls a function It is expected that the function returns a JSON response Throws an exception if JSON.generate fails to generate



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/ace/fork_util.rb', line 13

def self.isolate
  reader, writer = IO.pipe
  pid = fork {
    # :nocov:
    success = true
    begin
      response = yield
      writer.puts JSON.generate(response)
    rescue ACE::Error => e
      writer.puts({
        msg: e.message,
        kind: e.kind,
        details: {
          class: e.class,
          backtrace: e.backtrace
        }
      }.to_json)
      success = false
    rescue Exception => e # rubocop:disable Lint/RescueException
      writer.puts({
        msg: e.message,
        kind: e.class,
        details: {
          class: e.class,
          backtrace: e.backtrace
        }
      }.to_json)
      success = false
    ensure
      writer.flush
      Process.exit! success
    end
    # :nocov:
  }
  unless pid
    warn "Could not fork"
    exit 1
  end
  writer.close
  output = reader.readlines('')[0]
  Process.wait(pid)
  if $CHILD_STATUS != 0
    error = JSON.parse(output)
    raise ACE::Error.new(error['msg'], error['kind'], error['details'])
  elsif output.nil?
    raise ACE::Error.new('spawned process returned no result', 'puppetlabs/ace/fork_util', 'no details')
  else
    JSON.parse(output)
  end
end