Class: Vagrant::Util::Subprocess

Inherits:
Object
  • Object
show all
Defined in:
lib/vagrant/util/subprocess.rb

Overview

Execute a command in a subprocess, gathering the results and exit status.

This class also allows you to read the data as it is outputted from the subprocess in real time, by simply passing a block to the execute method.

Defined Under Namespace

Classes: LaunchError, Result, TimeoutExceeded

Constant Summary collapse

READ_CHUNK_SIZE =

The chunk size for reading from subprocess IO.

4096

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*command) ⇒ Subprocess

Returns a new instance of Subprocess.



23
24
25
26
27
# File 'lib/vagrant/util/subprocess.rb', line 23

def initialize(*command)
  @options = command.last.is_a?(Hash) ? command.pop : {}
  @command = command
  @logger  = Log4r::Logger.new("vagrant::util::subprocess")
end

Class Method Details

.execute(*command, &block) ⇒ Object

Convenience method for executing a method.



19
20
21
# File 'lib/vagrant/util/subprocess.rb', line 19

def self.execute(*command, &block)
  new(*command).execute(&block)
end

Instance Method Details

#executeObject



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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
# File 'lib/vagrant/util/subprocess.rb', line 29

def execute
  # Get the timeout, if we have one
  timeout = @options[:timeout]
  workdir = @options[:workdir] || Dir.pwd

  # Build the ChildProcess
  @logger.info("Starting process: #{@command.inspect}")
  process = ChildProcess.build(*@command)

  # Create the pipes so we can read the output in real time as
  # we execute the command.
  stdout, stdout_writer = IO.pipe
  stderr, stderr_writer = IO.pipe
  process.io.stdout = stdout_writer
  process.io.stderr = stderr_writer
  process.duplex = true

  # Set the environment on the process if we must
  if @options[:env]
    @options[:env].each do |k, v|
      process.environment[k] = v
    end
  end

  # Start the process
  begin
    Dir.chdir(workdir) do
      process.start
    end
  rescue ChildProcess::LaunchError
    # Raise our own version of the error so that users of the class
    # don't need to be aware of ChildProcess
    raise LaunchError
  end

  # Make sure the stdin does not buffer
  process.io.stdin.sync = true

  if RUBY_PLATFORM != "java"
    # On Java, we have to close after. See down the method...
    # Otherwise, we close the writers right here, since we're
    # not on the writing side.
    stdout_writer.close
    stderr_writer.close
  end

  # Create a dictionary to store all the output we see.
  io_data = { :stdout => "", :stderr => "" }

  # Record the start time for timeout purposes
  start_time = Time.now.to_i

  @logger.debug("Selecting on IO")
  while true
    results = IO.select([stdout, stderr], [process.io.stdin], nil, timeout || 5)
    readers, writers = results

    # Check if we have exceeded our timeout
    raise TimeoutExceeded, process.pid if timeout && (Time.now.to_i - start_time) > timeout

    # Check the readers to see if they're ready
    if !readers.empty?
      readers.each do |r|
        # Read from the IO object
        data = read_io(r)

        # We don't need to do anything if the data is empty
        next if data.empty?

        io_name = r == stdout ? :stdout : :stderr
        @logger.debug("#{io_name}: #{data}")

        io_data[io_name] += data
        yield io_name, data if block_given?
      end
    end

    # Break out if the process exited. We have to do this before
    # attempting to write to stdin otherwise we'll get a broken pipe
    # error.
    break if process.exited?

    # Check the writers to see if they're ready, and notify any listeners
    if !writers.empty?
      yield :stdin, process.io.stdin if block_given?
    end
  end

  # Wait for the process to end.
  begin
    remaining = (timeout || 32000) - (Time.now.to_i - start_time)
    remaining = 0 if remaining < 0
    @logger.debug("Waiting for process to exit. Remaining to timeout: #{remaining}")

    process.poll_for_exit(remaining)
  rescue ChildProcess::TimeoutError
    raise TimeoutExceeded, process.pid
  end

  @logger.debug("Exit status: #{process.exit_code}")

  # Read the final output data, since it is possible we missed a small
  # amount of text between the time we last read data and when the
  # process exited.
  [stdout, stderr].each do |io|
    # Read the extra data, ignoring if there isn't any
    extra_data = read_io(io)
    next if extra_data == ""

    # Log it out and accumulate
    @logger.debug(extra_data)
    io_name = io == stdout ? :stdout : :stderr
    io_data[io_name] += extra_data

    # Yield to any listeners any remaining data
    yield io_name, extra_data if block_given?
  end

  if RUBY_PLATFORM == "java"
    # On JRuby, we need to close the writers after the process,
    # for some reason. See GH-711.
    stdout_writer.close
    stderr_writer.close
  end

  # Return an exit status container
  return Result.new(process.exit_code, io_data[:stdout], io_data[:stderr])
end