diff --git a/README.md b/README.md index aa798a1..4725cd5 100644 --- a/README.md +++ b/README.md @@ -19,6 +19,14 @@ SafeShell.execute("echo", "Hello, world!") SafeShell sets the $? operator to the process status, in the same manner as the backtick operator. +If the call is interrupted, by a timeout or a signal, SafeShell sends the command TERM, then KILL if it is still running a second later, and reaps it, so $? describes the terminated command. The call returns once the command has been reaped, normally up to a second after the interruption. Only the command's own process is signalled, not any processes it started. The exceptions: + +- A command that has changed user cannot be signalled and is left running; $? is nil or unchanged from the previous command. +- A command that has not died a second after KILL is left unreaped; $? is nil or unchanged from the previous command. +- A command that something else in the process has already reaped is not signalled; $? is nil or unchanged from the previous command. +- On CRuby, an exception raised from a signal handler installed with `trap` while the command is being waited on cuts the wait short and the command is killed at once; landing elsewhere in the cleanup, it is delivered after the ordinary TERM and KILL. JRuby delivers it after the cleanup. +- Deferred interrupts are delivered while the command is being waited on, even inside a caller's `Thread.handle_interrupt(... => :never)`. + ```ruby # Send stdout and stderr to files: SafeShell.execute("echo", "Hello, world!", :stdout => "output.txt", :stderr => "error.txt") diff --git a/lib/safe_shell.rb b/lib/safe_shell.rb index 97b033a..90fe06e 100644 --- a/lib/safe_shell.rb +++ b/lib/safe_shell.rb @@ -1,32 +1,70 @@ module SafeShell class CommandFailedException < RuntimeError; end + # Seconds a child gets to exit after a signal before the next step. + GRACE_PERIOD = 1.0 + # Seconds between checks for the child having exited. + POLL_INTERVAL = 0.01 + private_constant :GRACE_PERIOD, :POLL_INTERVAL + def self.execute(command, *args) opts = args.last.kind_of?(Hash) ? args.pop : {} - read_end, write_end = IO.pipe - new_stdout = opts[:stdout] ? File.open(opts[:stdout], "w+") : write_end - new_stderr = opts[:stderr] ? File.open(opts[:stderr], "w+") : write_end - env = opts[:env] - # A command that reads stdin gets EOF at once rather than blocking. - opts = {:in => File::NULL, :out => new_stdout, :err => new_stderr} - - # Passing the program as a two-element array forces Kernel#spawn to exec - # it directly. A bare String with no further arguments would go through - # /bin/sh -c whenever it contains shell metacharacters. - program = [command.to_s, command.to_s] - argv = args.map { |a| a.to_s } - - pid = if env - spawn(env, program, *argv, opts) - else - spawn(program, *argv, opts) - end - write_end.close - output = read_end.read - Process.waitpid(pid) - read_end.close - output + # Interrupts Ruby can defer (Thread#raise, which Timeout uses; Thread#kill; + # the default signal handlers) are deferred except around the read and the + # wait, so every descriptor and the pid are assigned when the ensure runs. + # On CRuby an exception raised from a trap handler is not deferred. + Thread.handle_interrupt(Object => :never) do + read_end, write_end = IO.pipe + new_stdout = new_stderr = nil + pid = nil + + begin + # Opened read-write: write-only blocks on a FIFO with no reader. + new_stdout = opts[:stdout] ? File.open(opts[:stdout], "w+") : write_end + new_stderr = opts[:stderr] ? File.open(opts[:stderr], "w+") : write_end + env = opts[:env] + # A command that reads stdin gets EOF at once rather than blocking. + spawn_opts = {:in => File::NULL, :out => new_stdout, :err => new_stderr} + + # Passing the program as a two-element array forces Kernel#spawn to + # exec it directly. A bare String with no further arguments would go + # through /bin/sh -c whenever it contains shell metacharacters. + program = [command.to_s, command.to_s] + argv = args.map { |a| a.to_s } + spawn_args = env ? [env, program] : [program] + + pid = spawn(*spawn_args, *argv, spawn_opts) + + Thread.handle_interrupt(Object => :immediate) do + write_end.close + output = read_end.read + Process.waitpid(pid) + pid = nil + output + end + ensure + begin + # Close first: closing cannot block, and a child stuck writing to a + # full pipe gets SIGPIPE (or EPIPE) and can exit. Neither a failing + # close nor, on CRuby, a trap handler's exception may leave the rest + # open. + interruption = nil + [read_end, write_end, new_stdout, new_stderr].each do |io| + begin + io.close if io && !io.closed? + rescue SystemCallError, IOError + rescue Exception => e + interruption ||= e + end + end + raise interruption if interruption + ensure + # So $? reflects this call, not the previous one. + terminate_and_reap(pid) if pid + end + end + end end def self.execute?(*args) @@ -44,4 +82,58 @@ def self.execute!(*args) end end end + + # Reaps pid, sending TERM and then KILL if it is still running. Each wait + # is one GRACE_PERIOD, so the call returns within about two grace periods, + # or three if an exception lands in it. A child that has not died by then + # is left, and $? is nil or unchanged. + def self.terminate_and_reap(pid) + return if Process.waitpid(pid, Process::WNOHANG) + Process.kill("TERM", pid) + return if reap_by(pid, now + GRACE_PERIOD) + Process.kill("KILL", pid) + reap_by(pid, now + GRACE_PERIOD) + rescue Errno::ESRCH, Errno::ECHILD + # Something else in this process has already reaped it. + rescue SystemCallError + # The child cannot be signalled (it changed uid, say). It is left running + # if it has not exited, and the caller's exception stands. + begin + Process.waitpid(pid, Process::WNOHANG) + rescue Errno::ECHILD + end + rescue Exception => interruption + # On CRuby an exception raised from a trap handler is not deferred by + # handle_interrupt, and a second one can land while the child is reaped. + deadline = now + GRACE_PERIOD + begin + unless Process.waitpid(pid, Process::WNOHANG) + Process.kill("KILL", pid) + reap_by(pid, deadline) + end + rescue SystemCallError + rescue Exception + retry if now < deadline + end + raise interruption + end + private_class_method :terminate_and_reap + + # Waits until the deadline for pid to exit and reaps it. Returns pid once + # reaped, or nil if it has not exited in time. + def self.reap_by(pid, deadline) + loop do + reaped = Process.waitpid(pid, Process::WNOHANG) + return reaped if reaped + return nil if now > deadline + sleep POLL_INTERVAL + end + end + private_class_method :reap_by + + # A clock that cannot step backwards, for deadlines. + def self.now + Process.clock_gettime(Process::CLOCK_MONOTONIC) + end + private_class_method :now end diff --git a/spec/safe_shell_spec.rb b/spec/safe_shell_spec.rb index 6245f15..74f7d0f 100644 --- a/spec/safe_shell_spec.rb +++ b/spec/safe_shell_spec.rb @@ -52,6 +52,299 @@ expect { SafeShell.execute("ls", Pathname.new("/tmp")) }.not_to raise_error end + context "resource handling" do + def open_descriptors + skip "needs /dev/fd" unless File.directory?("/dev/fd") + Dir.entries("/dev/fd").size + end + + it "closes the redirect files it opens" do + before = open_descriptors + 5.times { SafeShell.execute("echo", "x", :stdout => "tmp/output.txt", :stderr => "tmp/error.txt") } + expect(open_descriptors).to eql(before) + end + + it "closes the pipe when the command cannot be started" do + before = open_descriptors + 5.times do + expect { SafeShell.execute("safe-shell-no-such-command") }.to raise_error(Errno::ENOENT) + end + expect(open_descriptors).to eql(before) + end + + it "closes the pipe when a redirect file cannot be opened" do + before = open_descriptors + 5.times do + expect { + SafeShell.execute("echo", "x", :stdout => "tmp/output.txt", :stderr => "tmp/no-such-dir/error.txt") + }.to raise_error(Errno::ENOENT) + end + expect(open_descriptors).to eql(before) + end + + def now + Process.clock_gettime(Process::CLOCK_MONOTONIC) + end + + def spawned_pid + allow(SafeShell).to receive(:spawn).and_wrap_original { |spawn, *args| @spawned = spawn.call(*args) } + lambda { @spawned } + end + + after do + if @spawned + begin + unless Process.waitpid(@spawned, Process::WNOHANG) + Process.kill("KILL", @spawned) + Process.waitpid(@spawned) + end + rescue Errno::ECHILD, Errno::ESRCH + end + end + end + + it "terminates and reaps the child if the read is interrupted" do + pid = spawned_pid + before = open_descriptors + expect { + Timeout.timeout(0.5) { SafeShell.execute("sleep", "30", :stdout => "tmp/output.txt") } + }.to raise_error(Timeout::Error) + expect($?.pid).to eql(pid.call) + expect($?.termsig).to eql(Signal.list["TERM"]) + expect(open_descriptors).to eql(before) + end + + it "terminates and reaps the child if interrupted while spawning" do + pid = nil + allow(SafeShell).to receive(:spawn).and_wrap_original do |spawn, *args| + @spawned = pid = spawn.call(*args) + sleep 0.3 + pid + end + expect { + Timeout.timeout(0.1) { SafeShell.execute("sleep", "30") } + }.to raise_error(Timeout::Error) + expect($?.pid).to eql(pid) + expect($?.termsig).to eql(Signal.list["TERM"]) + end + + it "kills the child if it ignores TERM" do + pid = spawned_pid + started = now + expect { + Timeout.timeout(0.5) { SafeShell.execute("sh", "-c", 'trap "" TERM; exec sleep 30') } + }.to raise_error(Timeout::Error) + expect(now - started).to be < 3 + expect($?.pid).to eql(pid.call) + expect($?.termsig).to eql(Signal.list["KILL"]) + end + + it "gives the child the whole grace period even when its thread is woken early" do + pid = spawned_pid + waiter = Thread.current + sibling = Thread.new { loop { waiter.wakeup; sleep 0.001 } } + begin + expect { + Timeout.timeout(0.3) { SafeShell.execute("sh", "-c", %q(trap 'kill $!; sleep 0.2; exit 0' TERM; sleep 30 & wait)) } + }.to raise_error(Timeout::Error) + ensure + sibling.kill + sibling.join + end + expect($?.pid).to eql(pid.call) + expect($?).to be_success + end + + it "finishes the cleanup if interrupted again while waiting for the child" do + pid = spawned_pid + expect { + Timeout.timeout(0.8) do + Timeout.timeout(0.3) { SafeShell.execute("sh", "-c", 'trap "" TERM; exec sleep 30') } + end + }.to raise_error(Timeout::Error) + expect($?.pid).to eql(pid.call) + expect($?.termsig).to eql(Signal.list["KILL"]) + end + + it "reaps the child if a trap handler raises while waiting for it" do + pid = spawned_pid + previous = trap("USR1") { raise "raised from trap handler" } + allow(Process).to receive(:kill).and_call_original + interruptions = 1 + allow(Process).to receive(:kill).with("TERM", anything).and_wrap_original do |kill, *args| + kill.call(*args) + Process.kill("USR1", Process.pid) if (interruptions -= 1) >= 0 + end + started = now + begin + expect { + Timeout.timeout(0.3) { SafeShell.execute("sh", "-c", 'trap "" TERM; exec sleep 30') } + }.to raise_error(RuntimeError, "raised from trap handler") + ensure + interruptions = 0 + trap("USR1", previous) + end + expect(now - started).to be < (RUBY_ENGINE == "ruby" ? 1 : 3) + expect($?.pid).to eql(pid.call) + expect($?.termsig).to eql(Signal.list["KILL"]) + end + + it "reaps the child if a trap handler raises again while killing it" do + skip "only CRuby delivers a trap handler's exception during the cleanup" unless RUBY_ENGINE == "ruby" + pid = spawned_pid + previous = trap("USR1") { raise "raised from trap handler" } + allow(Process).to receive(:kill).and_call_original + interruptions = 2 + allow(Process).to receive(:kill).with(/TERM|KILL/, anything).and_wrap_original do |kill, *args| + kill.call(*args) + Process.kill("USR1", Process.pid) if (interruptions -= 1) >= 0 + end + started = now + begin + expect { + Timeout.timeout(0.3) { SafeShell.execute("sh", "-c", 'trap "" TERM; exec sleep 30') } + }.to raise_error(RuntimeError, "raised from trap handler") + ensure + interruptions = 0 + trap("USR1", previous) + end + expect(now - started).to be < (RUBY_ENGINE == "ruby" ? 1 : 3) + expect($?.pid).to eql(pid.call) + expect($?.termsig).to eql(Signal.list["KILL"]) + end + + it "stops retrying the kill at the deadline if a trap handler keeps raising" do + skip "only CRuby delivers a trap handler's exception during the cleanup" unless RUBY_ENGINE == "ruby" + pid = spawned_pid + previous = trap("USR1") { raise "raised from trap handler" } + allow(Process).to receive(:kill).and_call_original + armed = true + allow(Process).to receive(:kill).with("TERM", anything).and_wrap_original do |kill, *args| + kill.call(*args) + Process.kill("USR1", Process.pid) if armed + end + allow(Process).to receive(:kill).with("KILL", anything).and_wrap_original do |kill, *args| + armed ? raise("raised from a later trap handler") : kill.call(*args) + end + started = now + begin + expect { + Timeout.timeout(0.3) { SafeShell.execute("sh", "-c", 'trap "" TERM; exec sleep 30') } + }.to raise_error(RuntimeError, "raised from trap handler") + ensure + armed = false + trap("USR1", previous) + end + expect(now - started).to be_between(1, 2.5) + expect { Process.kill(0, pid.call) }.not_to raise_error + end + + it "keeps the trap handler's exception if the kill after it is refused" do + skip "only CRuby delivers a trap handler's exception during the cleanup" unless RUBY_ENGINE == "ruby" + pid = spawned_pid + previous = trap("USR1") { raise "raised from trap handler" } + allow(Process).to receive(:kill).and_call_original + armed = true + allow(Process).to receive(:kill).with("TERM", anything).and_wrap_original do |kill, *args| + kill.call(*args) + Process.kill("USR1", Process.pid) if armed + end + allow(Process).to receive(:kill).with("KILL", anything).and_wrap_original do |kill, *args| + armed ? raise(Errno::EPERM) : kill.call(*args) + end + begin + expect { + Timeout.timeout(0.3) { SafeShell.execute("sh", "-c", 'trap "" TERM; exec sleep 30') } + }.to raise_error(RuntimeError, "raised from trap handler") + ensure + armed = false + trap("USR1", previous) + end + expect { Process.kill(0, pid.call) }.not_to raise_error + end + + it "closes every descriptor if a trap handler raises while closing one" do + skip "only CRuby delivers a trap handler's exception during the cleanup" unless RUBY_ENGINE == "ruby" + pid = spawned_pid + previous = trap("USR1") { raise "raised from trap handler" } + armed = true + allow_any_instance_of(File).to receive(:close).and_wrap_original do |close, *args| + close.call(*args) + Process.kill("USR1", Process.pid) if armed + end + before = open_descriptors + begin + expect { + Timeout.timeout(0.3) { SafeShell.execute("sleep", "30", :stdout => "tmp/output.txt", :stderr => "tmp/error.txt") } + }.to raise_error(RuntimeError, "raised from trap handler") + ensure + armed = false + trap("USR1", previous) + end + expect(open_descriptors).to eql(before) + expect($?.pid).to eql(pid.call) + expect($?.termsig).to eql(Signal.list["TERM"]) + end + + it "leaves a child that does not die after KILL" do + pid = spawned_pid + ignore_kill = true + allow(Process).to receive(:kill).and_call_original + allow(Process).to receive(:kill).with("KILL", anything).and_wrap_original do |kill, *args| + ignore_kill ? 1 : kill.call(*args) + end + started = now + begin + expect { + Timeout.timeout(0.3) { SafeShell.execute("sh", "-c", 'trap "" TERM; exec sleep 30') } + }.to raise_error(Timeout::Error) + expect(now - started).to be < 4 + expect($?).to satisfy("be nil or describe another command") { |status| status.nil? || status.pid != pid.call } + expect { Process.kill(0, pid.call) }.not_to raise_error + ensure + ignore_kill = false + end + end + + it "leaves a child it is not permitted to signal and keeps the caller's exception" do + pid = spawned_pid + allow(Process).to receive(:kill).and_call_original + allow(Process).to receive(:kill).with("TERM", anything).and_raise(Errno::EPERM) + started = now + begin + expect { + Timeout.timeout(0.3) { SafeShell.execute("sleep", "30") } + }.to raise_error(Timeout::Error) + expect(now - started).to be < 1 + expect($?).to satisfy("be nil or describe another command") { |status| status.nil? || status.pid != pid.call } + expect { Process.kill(0, pid.call) }.not_to raise_error + ensure + Process.kill("KILL", pid.call) + Process.waitpid(pid.call) + end + end + + it "reaps a child that has already exited" do + read_end, write_end = IO.pipe + pid = spawn("true", :out => write_end) + write_end.close + read_end.read + read_end.close + SafeShell.send(:terminate_and_reap, pid) + expect($?.pid).to eql(pid) + expect($?).to be_success + end + + it "does nothing for a child another waiter has reaped" do + pid = spawn("true") + Process.waitpid(pid) + status = $? + expect(Process).not_to receive(:kill) + expect { SafeShell.send(:terminate_and_reap, pid) }.not_to raise_error + expect($?).to satisfy("be nil or unchanged") { |after| after.nil? || after.equal?(status) } + end + end + context "output redirection" do before do File.delete("tmp/output.txt") if File.exist?("tmp/output.txt")