Class: ProcessExecuter::Commands::StandardStreamGuard Private

Inherits:
Object
  • Object
show all
Defined in:
lib/process_executer/commands/standard_stream_guard.rb

Overview

This class is part of a private API. You should avoid using this class if possible, as it may be removed or be changed in the future.

Puts stdout and stderr back after a failed spawn left them pointed at pipes

A workaround for Ruby Bug #22540, used only on Windows MRI. There, Process.spawn points this process's stdout and stderr at the redirection targets before it spawns and doesn't point them back when a later option fails, such as a chdir: the process can't enter. When the targets are MonitoredPipes that Run attached, the caller is left writing into pipes nobody reads -- something Process.spawn given the caller's own options would not have done.

#call copies descriptors 1 and 2, runs the spawn, and after a spawn that doesn't return, points the descriptors back at the copies -- but only when the pipes show that they leaked. A restore after every failed spawn would disturb other threads for failures that leak nothing: on Ruby 3.1 through 3.4, reopening descriptor 1 or 2 raises IOError in any thread that is writing to it.

What this class does not repair:

  • Env, umask, and stdin. They leak the same way through Process.spawn, so this gem leaves the caller no worse off than Process.spawn does.
  • Ruby's descriptor leak. Each spawn that fails this way leaves open the two copies Ruby itself made of the descriptors it redirected, and Ruby code can't find them to close them. After about 4,090 such failures the process is out of descriptors and every later call that attaches a pipe raises SpawnError (Too many open files) at once; stdout and stderr still work.
  • A thread writing to stdout or stderr while a leak is repaired. It gets an Errno::EPIPE from the pipe whose reader the leak check closed, and on Ruby 3.1 through 3.4 an IOError from the reopen. Without the repair every later write fails.
  • A stream the caller closed before the call. There is no copy to put back, so a leaked descriptor stays pointed at the pipe and closing the pipes waits out MonitoredPipe::DEFAULT_CLOSE_TIMEOUT.

Known limits

Each needs code that is unlikely to be written, and each fix would cost more than the case is worth:

  • Code that runs while LOCK is held must not wait for another thread to run a command through this class: the two deadlock. Such code runs in two places. Process.spawn calls coercion methods such as an env value's #to_str. And while a leak is checked, a pipe's destination may be in #write with what another thread wrote to the leaked stream; the check waits for that write to return. The thread that holds the lock can itself run a command.
  • A signal handler that raises IOError or a SystemCallError is taken for an I/O failure. Raised while a pipe is closed for the leak check, it is dropped and the caller gets the spawn's error. Raised during the restore, it ends the restore, and a leaked stream stays pointed at its pipe. A handler that raises any other class, or throws, is handled.
  • A signal handler that raises or throws while the copies are being closed leaves one or both of them open until garbage collection closes them. Stdout and stderr are not affected.

Operations this class avoids

While a descriptor is leaked, another thread may be writing to stdout or stderr. Ruby writes to descriptors 1 and 2 with a synchronous call, but the pipe they now point at was opened for overlapped I/O, and on such a handle a synchronous write that has to wait can miss its completion when any other operation touches the same pipe end. The writer then waits forever holding the C runtime's lock on the descriptor, and the next thread to use that descriptor while holding the GVL stops the process. That is a Ruby bug of its own, tracked in issue 210.

Two things Ruby does are such operations, so nothing here does either to a pipe end or to a standard stream:

  • IO#close, which calls UnlockFile on the handle. A descriptor is pointed at the null device with IO#reopen first, which swaps the handle under the C runtime's lock, and then closed. That goes for the copies of the standard streams and for each pipe's own write end.
  • IO.for_fd, which queries the handle. Copies are made with IO#dup, and the two IO objects a restore reopens are made once per process, before any spawn.

The code this leads to looks roundabout, and the direct form of each step (copy.close, IO.for_fd(fd), STDOUT.reopen) passes every example. No example can show the difference: the hang is a race with no deterministic trigger. Before simplifying anything here, run the script in issue 210 against the change. Code outside this class that closes, stats, or wraps a standard descriptor while one is leaked can still trigger the hang.

Remove this class, and its use in Run, when the gem's minimum supported Ruby is a release line in which every patch version has the fix for Ruby Bug #22540. Until then, once the fixed versions are known, gate its use on RUBY_VERSION so a fixed Ruby doesn't pay for the copies and the lock.

Constant Summary collapse

LOCK =

This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.

Serializes the save, the spawn, and the restore across threads

Without it, one thread can save descriptors that another thread's failed spawn has just leaked, and then restore the leak.

A Monitor, not a Mutex, so the thread that holds it can enter again: Process.spawn calls coercion methods such as an env value's #to_str inside the lock, and one of those may itself run a command through this class.

Returns:

  • (Monitor)
Monitor.new
STREAMS =

This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.

The descriptors to guard and the IO objects that own them

The constants and not $stdout and $stderr: a caller can point the globals at a StringIO, and the leak is in descriptors 1 and 2.

Returns:

  • (Hash{Integer => IO})
{ 1 => STDOUT, 2 => STDERR }.freeze

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(pipes) ⇒ StandardStreamGuard

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Create a guard for a spawn that redirects to the given pipes

Examples:

pipes = { out: ProcessExecuter::MonitoredPipe.new(StringIO.new) }
guard = ProcessExecuter::Commands::StandardStreamGuard.new(pipes)

Parameters:



136
137
138
139
# File 'lib/process_executer/commands/standard_stream_guard.rb', line 136

def initialize(pipes)
  @pipes = pipes
  @pipes_closed = false
end

Class Method Details

.null_device ⇒ File

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

An IO object open on the null device, shared by every guard

Examples:

ProcessExecuter::Commands::StandardStreamGuard.null_device.closed? #=> false

Returns:

  • (File)


448
449
450
451
# File 'lib/process_executer/commands/standard_stream_guard.rb', line 448

def null_device
  @null_device = File.open(File::NULL, 'wb') if @null_device.nil? || @null_device.closed?
  @null_device
end

.target(descriptor) ⇒ IO

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

An IO object for descriptor 1 or 2 that a restore reopens

Made once and kept, and first asked for before a spawn: IO.for_fd queries the descriptor's handle, which must not happen while the descriptor is leaked. It doesn't own the descriptor, so garbage collection never closes a standard stream. Its mode doesn't matter: IO#reopen takes the mode of the copy.

Examples:

ProcessExecuter::Commands::StandardStreamGuard.target(2).fileno #=> 2

Parameters:

  • descriptor (Integer) —

    1 or 2

Returns:

  • (IO)


435
436
437
# File 'lib/process_executer/commands/standard_stream_guard.rb', line 435

def target(descriptor)
  (@targets ||= {})[descriptor] ||= IO.for_fd(descriptor, 'w', autoclose: false)
end

Instance Method Details

#call { ... } ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Run the spawn in the block, undoing a stdout or stderr leak if it is unwound

The block can be left by an exception of any class or by a throw; the leak is checked for and undone in each case.

Exceptions raised from other threads are deferred for the length of the block (one spawn). One that landed between the failed spawn and the restore would leave the leak in place and then close the copies the restore needed. A deferred exception is delivered as this method returns, including after a spawn that succeeded, so the block must record the pid itself for the caller to know a subprocess is running. The mask is on Object, not Exception, so that it also defers Thread#kill, which is not delivered as an exception.

A signal handler is not deferred: it runs on the main thread whenever the signal arrives, and may raise or throw there. So the check and the restore are started again, from an ensure, each time they are unwound before they finish; what unwound them carries on once they are done.

Examples:

pid = guard.call { Process.spawn('echo hello', out: pipes[:out]) }

Yields:

  • the call to Process.spawn

Returns:

  • (Object) —

    the value of the block

Raises:

  • (Exception) —

    whatever the block raised

  • (SystemCallError) —

    the null device could not be opened or a stream could not be copied, as when the process is out of descriptors; the block was not run



186
187
188
189
190
191
192
193
# File 'lib/process_executer/commands/standard_stream_guard.rb', line 186

def call(&spawn)
  LOCK.synchronize do
    # Opened now, not on first use: the leak check and the release both
    # need it, and neither can do its work if the open fails then
    self.class.null_device
    Thread.handle_interrupt(Object => :never) { spawn_and_repair(save, &spawn) }
  end
end

#pipes_closed? ⇒ Boolean

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Whether #call closed the pipes while checking them for a leak

True after a spawn that didn't return: the leak check has to close every pipe to see whether it reaches end-of-file, so the owner of the pipes must not close them again or report what the check left in them.

Examples:

guard.pipes_closed? #=> false

Returns:

  • (Boolean)


152
# File 'lib/process_executer/commands/standard_stream_guard.rb', line 152

def pipes_closed? = @pipes_closed