Class: Ruboty::ExecCommand::Actions::Command

Inherits:
Actions::Base
  • Object
show all
Defined in:
lib/ruboty/exec_command/actions/command.rb

Instance Method Summary collapse

Instance Method Details

#callObject



5
6
7
8
9
# File 'lib/ruboty/exec_command/actions/command.rb', line 5

def call
  # TODO: add timeout
  c = Ruboty::ExecCommand::Command.new(command_args: command_body)
  run_and_monitor(c)
end

#command_bodyObject



68
69
70
# File 'lib/ruboty/exec_command/actions/command.rb', line 68

def command_body
  message.body.sub(robot_prefix_pattern,'')
end

#command_slotObject



11
12
13
# File 'lib/ruboty/exec_command/actions/command.rb', line 11

def command_slot
  message.robot.brain.data[:command_slot] ||= Ruboty::ExecCommand::CommandSlot.new
end

#kill_commandObject



19
20
21
22
23
24
25
# File 'lib/ruboty/exec_command/actions/command.rb', line 19

def kill_command
  # TODO: command list lock
  # kill running process, command is "kill command <index>"
  if command_slot.kill(message.body.split.last.to_i).nil?
    message.reply("Command [#{message.body.split.last}] not found.")
  end
end

#list_commandsObject



15
16
17
# File 'lib/ruboty/exec_command/actions/command.rb', line 15

def list_commands
  message.reply(command_slot.list_commands)
end

#robot_prefix_patternObject



64
65
66
# File 'lib/ruboty/exec_command/actions/command.rb', line 64

def robot_prefix_pattern
  Ruboty::Action.prefix_pattern(message.original[:robot].name)
end

#run_and_monitor(comm) ⇒ Object



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/ruboty/exec_command/actions/command.rb', line 27

def run_and_monitor(comm)
  pid = command_slot.run(comm)
  msg = "[#{comm.command_name}] invoked. PID: #{comm.pid}"
  Ruboty.logger.info { "[EXEC_COMMAND] #{msg}" }
  message.reply(msg)

  # Waiter thread
  thread = Thread.new do
    begin
      ignore_pid, status = Process.wait2(pid)
      command_slot.forget(pid)

      if status.exitstatus == 0
        msg = "[#{comm.command_name}] completed successfully. PID: #{comm.pid}"
        Ruboty.logger.info { "[EXEC_COMMAND] #{msg}" }
        message.reply(msg)
        message.reply(comm.stdout_log.chomp)
      elsif status.signaled?
        msg = "[#{comm.command_name}] killed by signal #{status.termsig} PID: #{comm.pid}"
        Ruboty.logger.info { "[EXEC_COMMAND] #{msg}" }
        message.reply(msg)
      else
        msg = "[#{comm.command_name}] exit status with #{status} PID: #{comm.pid}\n" +
          comm.stdout_log + "stderr: " + comm.stderr_log.chomp
          Ruboty.logger.info { "[EXEC_COMMAND] #{msg}" }
          message.reply(msg)
      end
    rescue Exception => e
      Ruboty.logger.error { "[EXEC_COMMAND] #{e.class} #{e.message} #{e.backtrace.first}" }
    end
  end

  if ENV['RUBOTY_ENV'] == 'blocked_test'
    thread.join
  end
end