Class: LoggerPipe::Runner

Inherits:
Object
  • Object
show all
Defined in:
lib/logger_pipe/runner.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(logger, cmd, options = {}) ⇒ Runner

Returns a new instance of Runner.



19
20
21
22
23
# File 'lib/logger_pipe/runner.rb', line 19

def initialize(logger, cmd, options = {})
  @logger, @cmd = logger, cmd
  @timeout = options[:timeout]
  @dry_run = options[:dry_run]
end

Instance Attribute Details

#cmdObject

Returns the value of attribute cmd.



17
18
19
# File 'lib/logger_pipe/runner.rb', line 17

def cmd
  @cmd
end

#loggerObject

Returns the value of attribute logger.



17
18
19
# File 'lib/logger_pipe/runner.rb', line 17

def logger
  @logger
end

#timeoutObject

Returns the value of attribute timeout.



17
18
19
# File 'lib/logger_pipe/runner.rb', line 17

def timeout
  @timeout
end

Instance Method Details

#executeObject



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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/logger_pipe/runner.rb', line 25

def execute
  if @dry_run
    logger.info("dry run: #{cmd}")
    return nil
  end
  logger.info("executing: #{cmd}")
  buf = []
  # systemをタイムアウトさせることはできないので、popenの戻り値を使っています。
  # see http://docs.ruby-lang.org/ja/2.0.0/class/Timeout.html
  com, pid = nil, nil
  begin
    Timeout.timeout( @timeout ) do

      # popenにブロックを渡さないと$?がnilになってしまうので敢えてブロックで処理しています。
      com = IO.popen(cmd) do |com|
        pid = com.pid
        while line = com.gets
          buf << line
          logger.info(line.chomp)
        end
      end
      if $?.exitstatus == 0
        logger.info("\e[32mSUCCESS: %s\e[0m" % [cmd])
        return buf.join
      else
        msg = "\e[31mFAILURE: %s\e[0m" % [cmd]
        logger.error(msg)
        raise Failure.new(msg, buf)
      end

    end
  rescue Timeout::Error => e
    logger.error("[#{e.class.name} #{e.message}] now killing process #{pid}: #{cmd}")
    begin
      Process.kill('SIGINT', pid) if pid
    rescue Exception => err
      logger.error("[#{err.class.name}] #{err.message}")
    end
    begin
      Timeout.timeout(10) do
        result = com.read
      end
    rescue Exception => err
      logger.error("failure to get result [#{err.class.name}] #{err.message}")
      result = "<failure to get result>"
    end
    begin
      msg = "\e[31mEXECUTION Timeout: %s\e[0m\n%s\n[result]: %s" % [cmd, buf.join.strip, result]
      logger.error(msg)
    rescue Exception => err
      logger.error("[#{err.class.name}] #{err.message}")
    end
    raise e
  end
end