瀏覽代碼

Use spawn() instead of open3 and avoid use of Dir.chdir

Changing the current directory affects the whole process, so without
eliminating the use of Dir.chdir we cannot safely run threaded workers
or dry-run agents on a threaded rack application server, etc.
Akinori MUSHA 9 年之前
父節點
當前提交
b93e04b36c
共有 1 個文件被更改,包括 18 次插入18 次删除
  1. 18 18
      app/models/agents/shell_command_agent.rb

+ 18 - 18
app/models/agents/shell_command_agent.rb

@@ -1,5 +1,3 @@
-require 'open3'
-
 module Agents
   class ShellCommandAgent < Agent
     default_schedule "never"
@@ -88,23 +86,25 @@ module Agents
     end
 
     def run_command(path, command)
-      result = nil
-      errors = nil
-      exit_status = nil
-
-      Dir.chdir(path){
-        begin
-          stdin, stdout, stderr, wait_thr = Open3.popen3(command)
-          exit_status = wait_thr.value.to_i
-          result = stdout.gets(nil)
-          errors = stderr.gets(nil)
-        rescue Exception => e
-          errors = e.to_s
-        end
-      }
+      begin
+        rout, wout = IO.pipe
+        rerr, werr = IO.pipe
+
+        pid = spawn(command, chdir: path, out: wout, err: werr)
 
-      result = result.to_s.strip
-      errors = errors.to_s.strip
+        wout.close
+        werr.close
+
+        (result = rout.read).strip!
+        (errors = rerr.read).strip!
+
+        _, status = Process.wait2(pid)
+        exit_status = status.exitstatus
+      rescue Exception => e
+        errors = e.to_s
+        result = ''.freeze
+        exit_status = nil
+      end
 
       [result, errors, exit_status]
     end