expect-pty 0.5.3 → 0.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/CHANGELOG.md +28 -0
- data/README.md +28 -19
- data/docs/API.md +88 -0
- data/docs/MIGRATION.md +15 -0
- data/lib/expect/cleanup.rb +33 -0
- data/lib/expect/configuration.rb +87 -66
- data/lib/expect/interaction.rb +226 -209
- data/lib/expect/logging.rb +157 -156
- data/lib/expect/matcher.rb +30 -29
- data/lib/expect/pattern.rb +8 -2
- data/lib/expect/pattern_list.rb +35 -5
- data/lib/expect/redactor.rb +11 -4
- data/lib/expect/relay.rb +97 -73
- data/lib/expect/relay_writer.rb +2 -1
- data/lib/expect/result.rb +32 -8
- data/lib/expect/session.rb +508 -0
- data/lib/expect/session_resources.rb +10 -2
- data/lib/expect/terminal.rb +78 -78
- data/lib/expect/version.rb +1 -1
- data/lib/expect.rb +333 -520
- data/sig/expect.rbs +355 -0
- metadata +13 -106
- data/.rubocop.yml +0 -66
- data/CONTRIBUTING.md +0 -29
- data/Gemfile +0 -28
- data/Rakefile +0 -38
- data/benchmark/matching.rb +0 -98
- data/benchmark/redactor.rb +0 -64
- data/benchmark/relay.rb +0 -48
- data/benchmark/scaling.rb +0 -70
- data/benchmark/send_slow.rb +0 -41
- data/benchmark/support.rb +0 -114
- data/docs/COMPATIBILITY.md +0 -98
- data/docs/INTERNAL_CONTRACTS.md +0 -154
- data/docs/PERFORMANCE.md +0 -165
- data/docs/RELEASING.md +0 -84
- data/docs/VERIFICATION.md +0 -456
- data/examples/dialogue.rb +0 -30
- data/examples/kibitz/README.md +0 -81
- data/examples/kibitz/kibitz.rb +0 -142
- data/examples/kibitz/test_kibitz.rb +0 -37
- data/examples/ssh_auto.rb +0 -94
- data/examples/ssh_interact.rb +0 -159
- data/examples/ssh_login.rb +0 -64
- data/expect-pty.gemspec +0 -33
- data/script/ci +0 -121
- data/script/release.rb +0 -319
- data/test/buffer_accounting_test.rb +0 -83
- data/test/cleanup_test.rb +0 -251
- data/test/compare_upstream.rb +0 -157
- data/test/configuration_test.rb +0 -133
- data/test/deadline_test.rb +0 -237
- data/test/diagnostics_test.rb +0 -353
- data/test/edge_case_test.rb +0 -262
- data/test/fixtures/ssh_scripts/01_identity.sh +0 -4
- data/test/fixtures/ssh_scripts/02_output.sh +0 -5
- data/test/fixtures/ssh_scripts/03_delayed.sh +0 -6
- data/test/fixtures/ssh_scripts/04_failure.sh +0 -2
- data/test/fixtures/ssh_scripts/05_recovery.sh +0 -3
- data/test/initialization_failure_test.rb +0 -92
- data/test/integration/README.md +0 -109
- data/test/integration/ssh_scripts.rb +0 -94
- data/test/interact_test.rb +0 -253
- data/test/interconnect_test.rb +0 -425
- data/test/io_test.rb +0 -321
- data/test/kibitz_test.rb +0 -45
- data/test/lifecycle_contract_test.rb +0 -71
- data/test/literal_scan_test.rb +0 -97
- data/test/matching_test.rb +0 -211
- data/test/multi_session_test.rb +0 -66
- data/test/ownership_sequence_test.rb +0 -208
- data/test/pattern_offset_test.rb +0 -43
- data/test/process_interruption_test.rb +0 -296
- data/test/process_test.rb +0 -291
- data/test/redactor_test.rb +0 -183
- data/test/relay_recovery_test.rb +0 -451
- data/test/relay_reentrancy_test.rb +0 -159
- data/test/release_test.rb +0 -375
- data/test/ruby_api_test.rb +0 -515
- data/test/scan_reuse_test.rb +0 -109
- data/test/script_logging_test.rb +0 -124
- data/test/support/interact_probe.rb +0 -125
- data/test/support/kibitz_probe.rb +0 -177
- data/test/support/script_probe.rb +0 -158
- data/test/terminal_cleanup_test.rb +0 -349
- data/test/test_helper.rb +0 -58
- data/test/timeout_test.rb +0 -289
- data/test/write_contract_test.rb +0 -105
|
@@ -0,0 +1,508 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require_relative "logging"
|
|
4
|
+
require_relative "terminal"
|
|
5
|
+
require_relative "interaction"
|
|
6
|
+
|
|
7
|
+
class Expect
|
|
8
|
+
# 会话运行内核;Matcher 与 Relay 直接使用其协议,用户仅接触外层 Expect。
|
|
9
|
+
# @api private
|
|
10
|
+
class Session
|
|
11
|
+
include Logging
|
|
12
|
+
include Terminal
|
|
13
|
+
include Interaction
|
|
14
|
+
|
|
15
|
+
attr_reader :connection, :command, :last_result, :slave, :tty_name, :buffer_discarded_bytes
|
|
16
|
+
|
|
17
|
+
# 唯一的门面到内核转换边界;内核不作为公开会话属性暴露。
|
|
18
|
+
def self.for(connection) = connection.__send__(:session)
|
|
19
|
+
|
|
20
|
+
extend Forwardable
|
|
21
|
+
|
|
22
|
+
# 普通属性委托给会话独立配置;缓冲上限的 setter 还需立即裁剪现有缓冲。
|
|
23
|
+
def_delegators :@configuration, *Configuration::READERS.values
|
|
24
|
+
def_delegators :@configuration, *(Configuration::ATTRIBUTES - [:buffer_limit]).map { |name| :"#{name}=" }
|
|
25
|
+
|
|
26
|
+
# 校验并更新缓冲上限后,立即裁剪已接收的内容;校验失败不改变旧缓冲。
|
|
27
|
+
def buffer_limit=(value)
|
|
28
|
+
@configuration.buffer_limit = value
|
|
29
|
+
trim_buffer
|
|
30
|
+
end
|
|
31
|
+
|
|
32
|
+
# 在新控制终端中执行命令并同步确认 exec 结果;同一会话只能启动一次。
|
|
33
|
+
def spawn(*command, env: {}, chdir: nil)
|
|
34
|
+
validate_spawn!(command)
|
|
35
|
+
|
|
36
|
+
@slave.raw! if raw_pty?
|
|
37
|
+
from_child = to_parent = nil
|
|
38
|
+
Cleanup.always(-> { SessionResources.close_handles(from_child, to_parent) }) do
|
|
39
|
+
# 错误管道的写端在 exec 成功时自动关闭;父进程据此区分成功启动与 exec 前失败。
|
|
40
|
+
from_child, to_parent = IO.pipe
|
|
41
|
+
to_parent.close_on_exec = true
|
|
42
|
+
@command = command.map { |part| part.dup.freeze }.freeze
|
|
43
|
+
child = fork { exec_child(command, env:, chdir:, from_child:, to_parent:) }
|
|
44
|
+
@resources.pid = child
|
|
45
|
+
to_parent.close
|
|
46
|
+
@slave.close
|
|
47
|
+
failure = from_child.read
|
|
48
|
+
Cleanup.always(-> { hard_close }) { raise SpawnError, failure } unless failure.empty?
|
|
49
|
+
trace("spawned pid=#{child}", event: :spawned)
|
|
50
|
+
connection
|
|
51
|
+
end
|
|
52
|
+
end
|
|
53
|
+
|
|
54
|
+
# 暴露底层读写 IO 与终端属性,供 select、终端设置及 IO 适配使用。
|
|
55
|
+
def to_io = @resources.reader
|
|
56
|
+
|
|
57
|
+
def writer = @resources.writer
|
|
58
|
+
|
|
59
|
+
def fileno = closed? ? nil : to_io.fileno
|
|
60
|
+
|
|
61
|
+
def tty? = !closed? && to_io.tty?
|
|
62
|
+
|
|
63
|
+
# 诊断时仅显示进程和描述符状态,避免默认对象展开泄露缓冲或日志内容。
|
|
64
|
+
def inspect = "#<#{connection.class} pid=#{pid.inspect} fd=#{fileno.inspect} closed=#{closed?}>"
|
|
65
|
+
|
|
66
|
+
def pid = @resources.pid
|
|
67
|
+
|
|
68
|
+
# 非阻塞回收并缓存子进程状态;未退出或仅适配 IO 时返回 nil。
|
|
69
|
+
def process_status
|
|
70
|
+
@resources.reap
|
|
71
|
+
rescue Errno::EINTR
|
|
72
|
+
# 单次轮询被中断时状态仍未知;wait/close 会在原期限内继续,不在这里无限重试。
|
|
73
|
+
@resources.status
|
|
74
|
+
end
|
|
75
|
+
|
|
76
|
+
def exit_code = process_status&.exitstatus
|
|
77
|
+
|
|
78
|
+
# 先刷新回收状态,再判断是否仍有未回收的子进程;不以 IO 是否关闭代替进程状态。
|
|
79
|
+
def alive?
|
|
80
|
+
process_status
|
|
81
|
+
!pid.nil?
|
|
82
|
+
end
|
|
83
|
+
|
|
84
|
+
# 区分会话关闭和输入结束,已关闭会话也不能继续读取。
|
|
85
|
+
def closed? = @closed || to_io.closed?
|
|
86
|
+
|
|
87
|
+
def eof? = @eof || closed?
|
|
88
|
+
|
|
89
|
+
# 以下访问器读取最近一次等待结果;未发生匹配时捕获组返回空数组。
|
|
90
|
+
def before = @last_result&.before
|
|
91
|
+
|
|
92
|
+
def after = @last_result&.after
|
|
93
|
+
|
|
94
|
+
def match = @last_result&.match
|
|
95
|
+
|
|
96
|
+
def match_number = @last_result&.number
|
|
97
|
+
|
|
98
|
+
def captures = @last_result&.captures || []
|
|
99
|
+
|
|
100
|
+
def error = @last_result&.error
|
|
101
|
+
|
|
102
|
+
# 返回缓冲副本,防止调用方原地修改绕过裁剪规则。
|
|
103
|
+
def buffer = @buffer.dup
|
|
104
|
+
|
|
105
|
+
# 复制并替换原始字节缓冲,应用当前上限;调用方后续修改原字符串不会影响会话。
|
|
106
|
+
def buffer=(value)
|
|
107
|
+
raise ArgumentError, "buffer must be a String" unless value.is_a?(String)
|
|
108
|
+
|
|
109
|
+
@buffer = value.b
|
|
110
|
+
@buffer_generation += 1
|
|
111
|
+
trim_buffer
|
|
112
|
+
end
|
|
113
|
+
|
|
114
|
+
# 移交旧缓冲并换上新的空字节串,供显式清空或人工转接接管数据。
|
|
115
|
+
def clear_buffer
|
|
116
|
+
previous = @buffer
|
|
117
|
+
@buffer = "".b
|
|
118
|
+
@buffer_generation += 1
|
|
119
|
+
previous
|
|
120
|
+
end
|
|
121
|
+
|
|
122
|
+
# 按 Ruby to_s 规则原样写入所有字节,返回字节数;背压等待受 write_timeout 限制。
|
|
123
|
+
def write(*objects)
|
|
124
|
+
raise IOError, "closed Expect session" if closed? || writer.closed?
|
|
125
|
+
|
|
126
|
+
begin
|
|
127
|
+
data = objects.map { |object| object.to_s.b }.join
|
|
128
|
+
trace_data(:sending, data, level: 2) if debug_level >= 2
|
|
129
|
+
rescue WriteTimeout
|
|
130
|
+
# 转换或诊断中的嵌套写入不属于当前命令;此时尚未向 writer 发送任何字节。
|
|
131
|
+
raise WriteTimeout.new("write interrupted before sending data", bytes_written: 0)
|
|
132
|
+
end
|
|
133
|
+
deadline = write_timeout && (Expect.monotonic + write_timeout)
|
|
134
|
+
offset = 0
|
|
135
|
+
while offset < data.bytesize
|
|
136
|
+
count = write_chunk(data, offset, deadline)
|
|
137
|
+
next unless count
|
|
138
|
+
|
|
139
|
+
if count == :wait_writable
|
|
140
|
+
raise WriteTimeout.new(bytes_written: offset) if deadline && Expect.monotonic >= deadline
|
|
141
|
+
|
|
142
|
+
wait_writable(offset, deadline)
|
|
143
|
+
else
|
|
144
|
+
offset += count
|
|
145
|
+
end
|
|
146
|
+
end
|
|
147
|
+
data.bytesize
|
|
148
|
+
end
|
|
149
|
+
|
|
150
|
+
# 链式写入单个对象,返回当前会话。
|
|
151
|
+
def <<(object)
|
|
152
|
+
write(object)
|
|
153
|
+
connection
|
|
154
|
+
end
|
|
155
|
+
|
|
156
|
+
# 委托 StringIO 处理换行、nil 和递归数组,再统一写入;返回 nil,与 Ruby puts 一致。
|
|
157
|
+
def puts(*objects)
|
|
158
|
+
output = StringIO.new("".b)
|
|
159
|
+
output.puts(*objects)
|
|
160
|
+
write(output.string)
|
|
161
|
+
nil
|
|
162
|
+
end
|
|
163
|
+
|
|
164
|
+
# 逐字符延迟发送,同时收集回复,适配输入处理较慢的交互程序;返回写入字节数。
|
|
165
|
+
def send_slow(*objects, delay:)
|
|
166
|
+
pause = Expect.duration(delay)
|
|
167
|
+
raise ArgumentError, "delay is required" unless pause
|
|
168
|
+
|
|
169
|
+
count = 0
|
|
170
|
+
objects.each do |object|
|
|
171
|
+
object.to_s.each_char do |character|
|
|
172
|
+
sleep(pause) if pause.positive?
|
|
173
|
+
count += write(character)
|
|
174
|
+
read_available if !eof? && to_io.wait_readable(0)
|
|
175
|
+
end
|
|
176
|
+
end
|
|
177
|
+
count
|
|
178
|
+
end
|
|
179
|
+
|
|
180
|
+
# 轮询回收状态直到进程退出或期限到达;返回 Process::Status 或 nil,超时不丢弃 PID。
|
|
181
|
+
def wait(timeout: nil)
|
|
182
|
+
wait_for_child(Expect.duration(timeout))
|
|
183
|
+
end
|
|
184
|
+
|
|
185
|
+
# 先在自然退出期限内收集尾部输出,再关闭句柄并最多发送 TERM;不会发送 KILL。
|
|
186
|
+
# 尚未退出时返回 nil 并保留 PID,调用方可以继续等待或随后硬关闭。
|
|
187
|
+
def soft_close(timeout: 15, term_timeout: 1)
|
|
188
|
+
period = Expect.duration(timeout)
|
|
189
|
+
term_timeout = Expect.duration(term_timeout)
|
|
190
|
+
raise ArgumentError, "term_timeout must be finite" unless term_timeout
|
|
191
|
+
|
|
192
|
+
deadline = period && (Expect.monotonic + period)
|
|
193
|
+
until eof?
|
|
194
|
+
remaining = deadline && [deadline - Expect.monotonic, 0].max
|
|
195
|
+
break if remaining&.zero? || !to_io.wait_readable(remaining)
|
|
196
|
+
|
|
197
|
+
read_available
|
|
198
|
+
end
|
|
199
|
+
close_resources(timeout: deadline ? [deadline - Expect.monotonic, 0].max : nil,
|
|
200
|
+
term_timeout:, force: false)
|
|
201
|
+
end
|
|
202
|
+
|
|
203
|
+
# 立即关闭句柄,再分阶段等待、TERM、KILL;不收集剩余输出,返回已回收状态或 nil。
|
|
204
|
+
def hard_close(timeout: 0.2)
|
|
205
|
+
period = Expect.duration(timeout)
|
|
206
|
+
raise ArgumentError, "hard_close timeout must be finite" unless period
|
|
207
|
+
|
|
208
|
+
close_resources(timeout: period, term_timeout: period, force: true)
|
|
209
|
+
end
|
|
210
|
+
|
|
211
|
+
# 通用生命周期清理:可先软关闭,ensure 中硬关闭兜底;正常完成返回 nil。
|
|
212
|
+
def close(graceful: graceful_close?)
|
|
213
|
+
Cleanup.always(-> { hard_close }) do
|
|
214
|
+
soft_close if graceful
|
|
215
|
+
nil
|
|
216
|
+
end
|
|
217
|
+
end
|
|
218
|
+
|
|
219
|
+
# 账本发布前只按局部所有权清理;发布后沿用完整关闭流程,避免两套生命周期状态。
|
|
220
|
+
def cleanup_session(reader, writer:, own:, slave: nil, graceful: false)
|
|
221
|
+
if @resources
|
|
222
|
+
close(graceful:)
|
|
223
|
+
elsif own
|
|
224
|
+
SessionResources.close_handles(reader, writer, slave)
|
|
225
|
+
end
|
|
226
|
+
end
|
|
227
|
+
|
|
228
|
+
# 统一初始化 PTY 与已有 IO 会话,复制配置并注册不直接捕获会话的资源终结器。
|
|
229
|
+
def initialize_connection(connection, reader, writer:, slave: nil, own: false, diagnostic_output: nil, **)
|
|
230
|
+
# 先登记所有权,后续校验失败也使用同一个资源对象逐个清理所属 IO。
|
|
231
|
+
@connection = connection
|
|
232
|
+
@resources = SessionResources.new(reader, writer:, slave:, own:)
|
|
233
|
+
raise ArgumentError, "reader must be a real IO" unless reader.is_a?(IO) && !reader.closed?
|
|
234
|
+
raise ArgumentError, "writer must be a real IO" unless writer.is_a?(IO) && !writer.closed?
|
|
235
|
+
|
|
236
|
+
@pty = reader.tty?
|
|
237
|
+
@slave = slave
|
|
238
|
+
@tty_name = slave.path if slave
|
|
239
|
+
@configuration = Configuration.new(**connection.class.configuration.to_h, **)
|
|
240
|
+
@buffer = "".b
|
|
241
|
+
@buffer_generation = 0
|
|
242
|
+
@buffer_discarded_bytes = 0
|
|
243
|
+
@listeners = []
|
|
244
|
+
@sequences = {}
|
|
245
|
+
@relay_outputs = []
|
|
246
|
+
@interact_inputs = {}.compare_by_identity
|
|
247
|
+
@interact_output = nil
|
|
248
|
+
@interaction_buffer = @relay_owner = @relay_callback = nil
|
|
249
|
+
@relay_history = "".b
|
|
250
|
+
@relay_history_sequences = {}
|
|
251
|
+
@secrets = @log_redactor = nil
|
|
252
|
+
@diagnostic_redactors = {}
|
|
253
|
+
@last_result = @command = nil
|
|
254
|
+
@closed = @eof = false
|
|
255
|
+
self.diagnostic_output = diagnostic_output
|
|
256
|
+
ObjectSpace.define_finalizer(self, SessionResources.finalizer(@resources))
|
|
257
|
+
end
|
|
258
|
+
|
|
259
|
+
# 开始新一轮等待时清除旧结果并应用缓冲上限,尚未消费的输入继续保留。
|
|
260
|
+
def reset_result
|
|
261
|
+
@last_result = nil
|
|
262
|
+
trim_buffer
|
|
263
|
+
end
|
|
264
|
+
|
|
265
|
+
# 按字节偏移生成 before/match/after;通常只保留 after,preserve_buffer 开启时不消费。
|
|
266
|
+
def record_match(pattern, position)
|
|
267
|
+
offset, length, captures = position
|
|
268
|
+
@last_result = Result.new(number: pattern.number, before: @buffer.byteslice(0, offset),
|
|
269
|
+
match: @buffer.byteslice(offset, length), after: @buffer.byteslice((offset + length)..),
|
|
270
|
+
session: connection, captures:)
|
|
271
|
+
unless preserve_buffer?
|
|
272
|
+
@buffer = @last_result.after.dup
|
|
273
|
+
@buffer_generation += 1
|
|
274
|
+
end
|
|
275
|
+
# 诊断回调可能嵌套等待;恢复本次结果后再交给正式模式回调,不能返回内层等待的结果。
|
|
276
|
+
result = @last_result
|
|
277
|
+
trace("matched pattern #{pattern.number}")
|
|
278
|
+
@last_result = result
|
|
279
|
+
end
|
|
280
|
+
|
|
281
|
+
# 记录超时、EOF 或原始 IO 异常,保留当前缓冲快照并清除旧匹配及捕获组。
|
|
282
|
+
def record_error(error)
|
|
283
|
+
@last_result = Result.new(error:, before: buffer, session: connection, captures: [])
|
|
284
|
+
end
|
|
285
|
+
|
|
286
|
+
# 输入结束时将剩余缓冲放入 before 并清空,尝试回收但不终止仍活跃的子进程。
|
|
287
|
+
def record_eof
|
|
288
|
+
process_status
|
|
289
|
+
record_error(:eof)
|
|
290
|
+
clear_buffer
|
|
291
|
+
@last_result
|
|
292
|
+
end
|
|
293
|
+
|
|
294
|
+
# 先将读取字节交给匹配或转接缓冲,再记录日志;日志失败也能恢复输入。
|
|
295
|
+
def read_available(propagate: true, buffer: @buffer, trim: true)
|
|
296
|
+
return nil if eof?
|
|
297
|
+
|
|
298
|
+
# 写入背压也会读取;转接期间统一交给转义处理器,不能直接转发或另存匹配缓冲。
|
|
299
|
+
if @interaction_buffer
|
|
300
|
+
buffer = @interaction_buffer
|
|
301
|
+
propagate = false
|
|
302
|
+
trim = false
|
|
303
|
+
end
|
|
304
|
+
|
|
305
|
+
begin
|
|
306
|
+
data = to_io.read_nonblock(READ_SIZE, exception: false)
|
|
307
|
+
rescue Errno::EIO
|
|
308
|
+
# 某些系统用 PTY 的 EIO 表示对端关闭;普通 IO 的同类错误仍按异常处理。
|
|
309
|
+
raise unless @pty
|
|
310
|
+
|
|
311
|
+
return mark_eof
|
|
312
|
+
rescue EOFError
|
|
313
|
+
return mark_eof
|
|
314
|
+
end
|
|
315
|
+
return nil if data == :wait_readable
|
|
316
|
+
|
|
317
|
+
return mark_eof if data.nil?
|
|
318
|
+
|
|
319
|
+
data = data.b
|
|
320
|
+
buffer << data
|
|
321
|
+
trim_buffer if trim
|
|
322
|
+
trace_data(:received, data, level: 2) if debug_level >= 2
|
|
323
|
+
trace_data(:buffer, @buffer, level: 3) if debug_level >= 3
|
|
324
|
+
# 仅在真实读取时记录日志,后续匹配或人工转接重用缓冲时不会重复记录。
|
|
325
|
+
write_log(data)
|
|
326
|
+
propagate(data) if propagate
|
|
327
|
+
data
|
|
328
|
+
end
|
|
329
|
+
|
|
330
|
+
private
|
|
331
|
+
|
|
332
|
+
# 参数校验先于任何进程和终端修改。
|
|
333
|
+
def validate_spawn!(command)
|
|
334
|
+
raise SpawnError, "cannot reuse a spawned session" if @command
|
|
335
|
+
raise SpawnError, "only a new PTY session can spawn" unless @slave && !@slave.closed? && !closed?
|
|
336
|
+
raise ArgumentError, "command is required" if command.empty?
|
|
337
|
+
raise ArgumentError, "command arguments must be strings" unless command.all? do |part|
|
|
338
|
+
part.is_a?(String) && !part.include?("\0")
|
|
339
|
+
end
|
|
340
|
+
raise ArgumentError, "command is empty" if command.first.empty?
|
|
341
|
+
end
|
|
342
|
+
|
|
343
|
+
# 子进程独占控制终端;成功 exec 关闭错误管道,失败时回传后立即退出。
|
|
344
|
+
def exec_child(command, env:, chdir:, from_child:, to_parent:)
|
|
345
|
+
from_child.close
|
|
346
|
+
Process.setsid
|
|
347
|
+
# 创建独立进程会话后重新打开 slave,使它成为子进程的控制终端。
|
|
348
|
+
File.open(@tty_name, File::RDWR) do |terminal|
|
|
349
|
+
# 重定向操作系统的标准描述符;即使宿主替换过 Ruby 标准流,也能正确连接子进程。
|
|
350
|
+
# rubocop:disable Style/GlobalStdStream
|
|
351
|
+
STDIN.reopen(terminal)
|
|
352
|
+
STDOUT.reopen(terminal)
|
|
353
|
+
STDERR.reopen(terminal)
|
|
354
|
+
# rubocop:enable Style/GlobalStdStream
|
|
355
|
+
end
|
|
356
|
+
@resources.close_handles
|
|
357
|
+
Dir.chdir(chdir) if chdir
|
|
358
|
+
exec(env, *command, close_others: true)
|
|
359
|
+
rescue Exception => error # rubocop:disable Lint/RescueException -- 子进程回传启动异常后立即退出。
|
|
360
|
+
begin
|
|
361
|
+
to_parent.write("#{error.class}: #{error.message}")
|
|
362
|
+
ensure
|
|
363
|
+
exit! 127
|
|
364
|
+
end
|
|
365
|
+
end
|
|
366
|
+
|
|
367
|
+
# EINTR 未确认交付时不移动游标;其他写入计数必须落在当前块范围内。
|
|
368
|
+
def write_chunk(data, offset, deadline)
|
|
369
|
+
chunk = data.byteslice(offset, READ_SIZE)
|
|
370
|
+
count = writer.write_nonblock(chunk, exception: false)
|
|
371
|
+
return count if count == :wait_writable
|
|
372
|
+
unless count.is_a?(Integer) && count.positive? && count <= chunk.bytesize
|
|
373
|
+
raise IOError, "write must return the number of accepted bytes"
|
|
374
|
+
end
|
|
375
|
+
|
|
376
|
+
count
|
|
377
|
+
rescue Errno::EINTR
|
|
378
|
+
raise WriteTimeout.new(bytes_written: offset) if deadline && Expect.monotonic >= deadline
|
|
379
|
+
|
|
380
|
+
nil
|
|
381
|
+
end
|
|
382
|
+
|
|
383
|
+
# 背压等待同时排空读端,期限不因 EINTR 重算,异常始终报告外层写入进度。
|
|
384
|
+
def wait_writable(offset, deadline)
|
|
385
|
+
remaining = deadline && [deadline - Expect.monotonic, 0].max
|
|
386
|
+
# 子进程也可能因输出管道填满而停止读取;等可写时同时排空它的输出,避免双向死锁。
|
|
387
|
+
readers = eof? ? [] : [to_io]
|
|
388
|
+
begin
|
|
389
|
+
ready = IO.select(readers, [writer], nil, remaining)
|
|
390
|
+
raise WriteTimeout.new(bytes_written: offset) unless ready
|
|
391
|
+
|
|
392
|
+
if ready[0].include?(to_io)
|
|
393
|
+
begin
|
|
394
|
+
read_available
|
|
395
|
+
rescue WriteTimeout
|
|
396
|
+
# 日志或监听器可嵌套写入;对外报告本次写入进度,原异常通过 cause 保留。
|
|
397
|
+
raise WriteTimeout.new("write interrupted by an output timeout", bytes_written: offset)
|
|
398
|
+
end
|
|
399
|
+
end
|
|
400
|
+
rescue Errno::EINTR
|
|
401
|
+
nil
|
|
402
|
+
end
|
|
403
|
+
end
|
|
404
|
+
|
|
405
|
+
# 共用的进程关闭流程;force 控制是否允许 KILL,只有资源创建者能够操作直属子进程。
|
|
406
|
+
def close_resources(timeout:, term_timeout:, force:)
|
|
407
|
+
failure = nil
|
|
408
|
+
# 预期的清理错误延后传播,保证其余所属资源和直属子进程仍能完成清理。
|
|
409
|
+
cleanup = lambda do |&step|
|
|
410
|
+
step.call
|
|
411
|
+
rescue IOError, SystemCallError => error
|
|
412
|
+
failure ||= error
|
|
413
|
+
nil
|
|
414
|
+
end
|
|
415
|
+
# IO 关闭与进程退出独立记录:软关闭可能已经 closed?,但仍保留活跃 PID。
|
|
416
|
+
cleanup.call { @resources.close_handles }
|
|
417
|
+
@closed = true
|
|
418
|
+
@interact_inputs&.delete_if do |_io, input|
|
|
419
|
+
cleanup.call do
|
|
420
|
+
input.close(graceful: false)
|
|
421
|
+
true
|
|
422
|
+
end
|
|
423
|
+
end
|
|
424
|
+
@interact_output = nil
|
|
425
|
+
@relay_outputs&.clear
|
|
426
|
+
@relay_history&.clear
|
|
427
|
+
@relay_callback = nil
|
|
428
|
+
status = close_child(timeout:, term_timeout:, force:)
|
|
429
|
+
completed = true
|
|
430
|
+
status
|
|
431
|
+
ensure
|
|
432
|
+
begin
|
|
433
|
+
cleanup.call { flush_diagnostics }
|
|
434
|
+
ensure
|
|
435
|
+
cleanup.call { self.log_output = nil }
|
|
436
|
+
end
|
|
437
|
+
# 用本次流程的完成状态判断异常传播,不能误把调用者 rescue 中的异常当成当前错误。
|
|
438
|
+
raise failure if failure && completed
|
|
439
|
+
end
|
|
440
|
+
|
|
441
|
+
# 句柄清理失败不改变进程策略;未回收 PID 保留给重复关闭或终结器继续处理。
|
|
442
|
+
def close_child(timeout:, term_timeout:, force:)
|
|
443
|
+
return process_status unless @resources.owner == Process.pid && pid
|
|
444
|
+
|
|
445
|
+
status = wait(timeout:)
|
|
446
|
+
return status if status || !pid
|
|
447
|
+
|
|
448
|
+
status = wait_for_child(term_timeout, signal: "TERM")
|
|
449
|
+
return status if status || !pid
|
|
450
|
+
return unless force
|
|
451
|
+
|
|
452
|
+
wait_for_child(1, signal: "KILL")
|
|
453
|
+
end
|
|
454
|
+
|
|
455
|
+
# 每阶段只计算一次期限;回收或信号被中断后仍沿用剩余预算,零预算也先做一次尝试。
|
|
456
|
+
def wait_for_child(period, signal: nil)
|
|
457
|
+
deadline = period && (Expect.monotonic + period)
|
|
458
|
+
loop do
|
|
459
|
+
status = process_status
|
|
460
|
+
return status if status || !pid || @resources.owner != Process.pid
|
|
461
|
+
|
|
462
|
+
begin
|
|
463
|
+
signal_child(signal) if signal
|
|
464
|
+
signal = nil
|
|
465
|
+
rescue Errno::EINTR
|
|
466
|
+
# 下轮先回收再重试信号,避免在无限等待或持续中断时忙等。
|
|
467
|
+
nil
|
|
468
|
+
end
|
|
469
|
+
# ESRCH 后可能已完成回收;即使预算耗尽,也要返回刚获得的状态。
|
|
470
|
+
return process_status unless pid
|
|
471
|
+
|
|
472
|
+
remaining = deadline && (deadline - Expect.monotonic)
|
|
473
|
+
return nil if remaining && remaining <= 0
|
|
474
|
+
|
|
475
|
+
sleep(remaining ? [0.01, remaining].min : 0.01)
|
|
476
|
+
end
|
|
477
|
+
end
|
|
478
|
+
|
|
479
|
+
def mark_eof
|
|
480
|
+
@eof = true
|
|
481
|
+
flush_log
|
|
482
|
+
flush_diagnostics(:received)
|
|
483
|
+
nil
|
|
484
|
+
end
|
|
485
|
+
|
|
486
|
+
# 缓冲超过上限时只保留最新尾部字节,不对编码做隐式修改。
|
|
487
|
+
def trim_buffer
|
|
488
|
+
limit = buffer_limit
|
|
489
|
+
return unless limit && @buffer.bytesize > limit
|
|
490
|
+
|
|
491
|
+
# 只累计匹配窗口裁剪,消费、清空及转接交接不算丢弃;关闭后仍可读取累计值。
|
|
492
|
+
@buffer_discarded_bytes += @buffer.bytesize - limit
|
|
493
|
+
@buffer = @buffer.byteslice(-limit, limit)
|
|
494
|
+
@buffer_generation += 1
|
|
495
|
+
end
|
|
496
|
+
|
|
497
|
+
# 仅由资源创建者向仍未回收的子进程发送信号;若进程刚好退出,则尝试回收。
|
|
498
|
+
def signal_child(signal)
|
|
499
|
+
return unless pid && @resources.owner == Process.pid
|
|
500
|
+
|
|
501
|
+
Process.kill(signal, pid)
|
|
502
|
+
rescue Errno::ESRCH
|
|
503
|
+
@resources.reap
|
|
504
|
+
end
|
|
505
|
+
end
|
|
506
|
+
|
|
507
|
+
private_constant :Session
|
|
508
|
+
end
|
|
@@ -3,10 +3,11 @@
|
|
|
3
3
|
class Expect
|
|
4
4
|
# 独立保存句柄、PID 和日志所有权,让终结器无需直接捕获会话即可清理遗弃资源。
|
|
5
5
|
# IO 是否关闭与子进程是否退出分别记录;不能仅凭句柄状态清空 PID 或伪造退出状态。
|
|
6
|
+
# @api private
|
|
6
7
|
class SessionResources
|
|
7
8
|
# owned_log 只保存库打开的文件;借用的 IO/日志回调留在会话中,不能成为终结器的引用根。
|
|
8
|
-
attr_accessor :
|
|
9
|
-
attr_reader :reader, :writer, :slave, :owner, :own
|
|
9
|
+
attr_accessor :status, :owned_log
|
|
10
|
+
attr_reader :pid, :reader, :writer, :slave, :owner, :own
|
|
10
11
|
|
|
11
12
|
# 记录创建资源的进程;fork 后的副本不能向父进程拥有的子进程发信号。
|
|
12
13
|
def initialize(reader, writer:, slave: nil, own: false)
|
|
@@ -17,6 +18,13 @@ class Expect
|
|
|
17
18
|
@owner = Process.pid
|
|
18
19
|
end
|
|
19
20
|
|
|
21
|
+
# 新进程由实际启动者负责;预先建立的 PTY 可能在 fork 后才启动命令。
|
|
22
|
+
# 仅继承已有 PID 的副本仍保留原所有者,不能清理父进程的子进程。
|
|
23
|
+
def pid=(value)
|
|
24
|
+
@owner = Process.pid if value
|
|
25
|
+
@pid = value
|
|
26
|
+
end
|
|
27
|
+
|
|
20
28
|
# 只关闭由本库拥有的 IO;借用的 reader、writer 由调用方管理。
|
|
21
29
|
# 常规关闭错误延后到所有句柄尝试完再抛出,失败句柄仍留在账本内供下一次关闭重试。
|
|
22
30
|
def close_handles
|