Class: Sensu::IO

Inherits:
Object
  • Object
show all
Defined in:
lib/sensu/io.rb

Class Method Summary collapse

Class Method Details

.async_popen(command, data = nil, timeout = nil, &block) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/sensu/io.rb', line 50

def async_popen(command, data=nil, timeout=nil, &block)
  execute = Proc.new do
    begin
      popen(command, 'r+', timeout) do |child|
        unless data.nil?
          child.write(data.to_s)
        end
        child.close_write
      end
    rescue => error
      [error.to_s, 2]
    end
  end
  complete = Proc.new do |output, status|
    block.call(output, status) if block
  end
  @async_popen_worker ||= EM::Worker.new
  @async_popen_worker.enqueue(execute, complete)
end

.popen(command, mode = 'r', timeout = nil, &block) ⇒ Object



9
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
39
40
41
42
43
44
45
46
47
48
# File 'lib/sensu/io.rb', line 9

def popen(command, mode='r', timeout=nil, &block)
  block ||= Proc.new {}
  begin
    if RUBY_VERSION < '1.9.3'
      child = ::IO.popen(command + ' 2>&1', mode)
      block.call(child)
      wait_on_process(child, false)
    else
      options = {
        :err => [:child, :out]
      }
      case RUBY_PLATFORM
      when /(ms|cyg|bcc)win|mingw|win32/
        shell = ['cmd', '/c']
        options[:new_pgroup] = true
      else
        shell = ['sh', '-c']
        options[:pgroup] = true
      end
      child = ::IO.popen(shell + [command, options], mode)
      if timeout
        Timeout.timeout(timeout) do
          block.call(child)
          wait_on_process(child)
        end
      else
        block.call(child)
        wait_on_process(child)
      end
    end
  rescue Timeout::Error
    kill_process_group(child.pid)
    wait_on_process_group(child.pid)
    ['Execution timed out', 2]
  rescue => error
    kill_process_group(child.pid)
    wait_on_process_group(child.pid)
    raise error
  end
end