Class: Spool::Spawner

Inherits:
Object
  • Object
show all
Defined in:
lib/spool/spawner.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(configuration) ⇒ Spawner

Returns a new instance of Spawner.



6
7
8
# File 'lib/spool/spawner.rb', line 6

def initialize(configuration)
  @configuration = configuration
end

Instance Attribute Details

#configurationObject (readonly)

Returns the value of attribute configuration.



4
5
6
# File 'lib/spool/spawner.rb', line 4

def configuration
  @configuration
end

Class Method Details

.spawn(configuration) ⇒ Object



40
41
42
# File 'lib/spool/spawner.rb', line 40

def self.spawn(configuration)
  new(configuration).spawn
end

Instance Method Details

#spawnObject



10
11
12
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
# File 'lib/spool/spawner.rb', line 10

def spawn
  base_file = File.join Dir.tmpdir, SecureRandom.uuid
  pid_file = "#{base_file}.pid"
  out_file = "#{base_file}.out"
  script_file = "#{base_file}.sh"

  File.write script_file, %Q{
    #!/usr/bin/env bash
    #{configuration.command.strip} &
    echo $! > #{pid_file}
  }

  ::Process.spawn configuration.env, 
                  "sh #{script_file}", 
                  chdir: configuration.dir, 
                  out: out_file, 
                  err: out_file

  pid = wait_for_pid pid_file

  Datacenter::Process.new(pid).tap do |process|
    raise "Invalid command: #{configuration.command}\n#{IO.read(out_file)}" unless process.alive?
  end

ensure
  [script_file, out_file, pid_file].each do |filename|
    File.delete filename if File.exists? filename
  end
end