File: process_runner.rb

package info (click to toggle)
ruby-tty-command 0.10.1-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 452 kB
  • sloc: ruby: 1,990; makefile: 4; sh: 4
file content (204 lines) | stat: -rw-r--r-- 5,608 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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
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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
# frozen_string_literal: true

require "thread"

require_relative "child_process"
require_relative "result"
require_relative "truncator"

module TTY
  class Command
    class ProcessRunner
      # the command to be spawned
      attr_reader :cmd

      # Initialize a Runner object
      #
      # @param [Printer] printer
      #   the printer to use for logging
      #
      # @api private
      def initialize(cmd, printer, &block)
        @cmd     = cmd
        @timeout = cmd.options[:timeout]
        @input   = cmd.options[:input]
        @signal  = cmd.options[:signal] || "SIGKILL"
        @binmode = cmd.options[:binmode]
        @printer = printer
        @block   = block
      end

      # Execute child process
      #
      # Write the input if provided to the child's stdin and read
      # the contents of both the stdout and stderr.
      #
      # If a block is provided then yield the stdout and stderr content
      # as its being read.
      #
      # @api public
      def run!
        @printer.print_command_start(cmd)
        start = Time.now

        pid, stdin, stdout, stderr = ChildProcess.spawn(cmd)

        write_stream(stdin, @input)

        stdout_data, stderr_data = read_streams(stdout, stderr)

        status = waitpid(pid)
        runtime = Time.now - start

        @printer.print_command_exit(cmd, status, runtime)

        Result.new(status, stdout_data, stderr_data, runtime)
      ensure
        [stdin, stdout, stderr].each { |fd| fd.close if fd && !fd.closed? }
        if pid # Ensure no zombie processes
          ::Process.detach(pid)
          terminate(pid)
        end
      end

      # Stop a process marked by pid
      #
      # @param [Integer] pid
      #
      # @api public
      def terminate(pid)
        ::Process.kill(@signal, pid) rescue nil
      end

      private

      # The buffer size for reading stdout and stderr
      BUFSIZE = 16 * 1024

      # @api private
      def handle_timeout(runtime)
        return unless @timeout

        t = @timeout - runtime
        raise TimeoutExceeded if t < 0.0
      end

      # Write the input to the process stdin
      #
      # @api private
      def write_stream(stream, input)
        start = Time.now
        writers = [input && stream].compact

        while writers.any?
          ready = IO.select(nil, writers, writers, @timeout)
          raise TimeoutExceeded if ready.nil?

          ready[1].each do |writer|
            begin
              err   = nil
              size  = writer.write(@input)
              input = input.byteslice(size..-1)
            rescue IO::WaitWritable
            rescue Errno::EPIPE => err
              # The pipe closed before all input written
              # Probably process exited prematurely
              writer.close
              writers.delete(writer)
            end
            if err || input.bytesize == 0
              writer.close
              writers.delete(writer)
            end

            # control total time spent writing
            runtime = Time.now - start
            handle_timeout(runtime)
          end
        end
      end

      # Read stdout & stderr streams in the background
      #
      # @param [IO] stdout
      # @param [IO] stderr
      #
      # @api private
      def read_streams(stdout, stderr)
        stdout_data = []
        stderr_data = Truncator.new

        out_handler = ->(data) {
          stdout_data << data
          @printer.print_command_out_data(cmd, data)
          @block.(data, nil) if @block
        }

        err_handler = ->(data) {
          stderr_data << data
          @printer.print_command_err_data(cmd, data)
          @block.(nil, data) if @block
        }

        stdout_thread = read_stream(stdout, out_handler)
        stderr_thread = read_stream(stderr, err_handler)

        stdout_thread.join
        stderr_thread.join

        encoding = @binmode ? Encoding::BINARY : Encoding::UTF_8

        [
          stdout_data.join.force_encoding(encoding),
          stderr_data.read.dup.force_encoding(encoding)
        ]
      end

      # Read stream and invoke handler when data becomes available
      #
      # @param [IO] stream
      #   the stream to read data from
      # @param [Proc] handler
      #   the handler to call when data becomes available
      #
      # @api private
      def read_stream(stream, handler)
        Thread.new do
          if Thread.current.respond_to?(:report_on_exception)
            Thread.current.report_on_exception = false
          end
          Thread.current[:cmd_start] = Time.now
          readers = [stream]

          while readers.any?
            ready = IO.select(readers, nil, readers, @timeout)
            raise TimeoutExceeded if ready.nil?

            ready[0].each do |reader|
              begin
                chunk = reader.readpartial(BUFSIZE)
                handler.(chunk)

                # control total time spent reading
                runtime = Time.now - Thread.current[:cmd_start]
                handle_timeout(runtime)
              rescue Errno::EAGAIN, Errno::EINTR
              rescue EOFError, Errno::EPIPE, Errno::EIO # thrown by PTY
                readers.delete(reader)
                reader.close
              end
            end
          end
        end
      end

      # @api private
      def waitpid(pid)
        _pid, status = ::Process.waitpid2(pid, ::Process::WUNTRACED)
        status.exitstatus || status.termsig if _pid
      rescue Errno::ECHILD
        # In JRuby, waiting on a finished pid raises.
      end
    end # ProcessRunner
  end # Command
end # TTY