/
Process.swift
376 lines (336 loc) · 12.5 KB
/
Process.swift
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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
@_implementationOnly import NIO
import SystemPackage
/**
A value which represents a child process
*/
public struct Process {
/**
Runs an executable in a separate process, returns once that process terminates.
*/
public static func run(
executablePath: FilePath,
arguments: [String],
environment: Environment,
workingDirectory: FilePath,
fileDescriptorMapping: FileDescriptorMapping,
logger: ProcessLogger? = nil,
in context: Context
) async throws {
try await launch(
executablePath: executablePath,
arguments: arguments,
environment: environment,
workingDirectory: workingDirectory,
fileDescriptorMapping: fileDescriptorMapping,
logger: logger,
in: context
)
.value
}
/**
Runs an executable in a separate process, and returns once that process has been launched.
- Returns: A task which represents the running of the external process.
*/
public static func launch(
executablePath: FilePath,
arguments: [String],
environment: Environment,
workingDirectory: FilePath,
fileDescriptorMapping: FileDescriptorMapping,
logger: ProcessLogger? = nil,
in context: Context
) async throws -> Task<Void, Error> {
let process: Process
let monitor: FileDescriptorMonitor
(process, monitor) = try await FileDescriptorMonitor.create(in: context) {
monitoredDescriptor in
do {
var fileDescriptorMapping = fileDescriptorMapping
/// Map the monitored descriptor to the lowest unmapped target descriptor
let mappedFileDescriptors = Set(fileDescriptorMapping.entries.map(\.target))
fileDescriptorMapping.addMapping(
from: monitoredDescriptor,
to: (0...).first(where: { !mappedFileDescriptors.contains($0) })!)
let process = try await Process(
executablePath: executablePath,
arguments: arguments,
environment: environment,
workingDirectory: workingDirectory,
fileDescriptorMapping: fileDescriptorMapping,
context: context)
logger?.didLaunch(process)
return process
} catch {
logger?.failedToLaunchProcess(dueTo: error)
throw error
}
}
return Task {
try await withTaskCancellationHandler {
try await monitor.wait()
logger?.willWait(on: process)
do {
try await process.wait(in: context)
logger?.process(process, didTerminateWithError: nil)
} catch {
logger?.process(process, didTerminateWithError: error)
throw error
}
} onCancel: {
process.terminate()
}
}
}
private init(
executablePath: FilePath,
arguments: [String],
environment: Environment,
workingDirectory: FilePath,
fileDescriptorMapping: FileDescriptorMapping,
context: Context
) async throws {
var attributes = try PosixSpawn.Attributes()
defer { try! attributes.destroy() }
#if canImport(Darwin)
try attributes.setFlags([
.closeFileDescriptorsByDefault,
.setSignalMask,
])
#elseif canImport(Glibc)
/// Linux does not support `closeFileDescriptorsByDefault`, so we emulate it below
try attributes.setFlags([
.setSignalMask
])
#else
#error("Unsupported Platform")
#endif
try attributes.setBlockedSignals(to: .none)
var actions = try PosixSpawn.FileActions()
defer { try! actions.destroy() }
try actions.addChangeDirectory(to: workingDirectory)
for entry in fileDescriptorMapping.entries {
try actions.addDuplicate(entry.source, as: entry.target)
}
#if canImport(Darwin)
/// Darwin support `closeFileDescriptorsByDefault`, so no need to emulate it
#elseif canImport(Glibc)
/// In order to emulate `POSIX_SPAWN_CLOEXEC_DEFAULT`, we use `posix_spawn_file_actions_addclosefrom_np`.
/// This only works if passed a lower bound file descriptor, so this emulation only works if the file descriptors we are mapping have contiguous values starting at 0.
/// Instead of supporting the general case (which is unlikely) we enforce that fileDescriptorMapping provides us our descriptors in order starting at 0.
var availableFileDescriptors = (CInt(0)...).makeIterator()
for (_, target) in fileDescriptorMapping.entries {
guard target == availableFileDescriptors.next() else {
/// `ENOSYS` seems like a good error to throw here:
/// Reference: https://github.com/apple/swift-tools-support-core/blob/main/Sources/TSCclibc/process.c
throw Errno(rawValue: ENOSYS)
}
}
guard let lowestFileDescriptorValueToClose = availableFileDescriptors.next() else {
throw Errno(rawValue: ENOSYS)
}
try actions.addCloseFileDescriptors(from: lowestFileDescriptorValueToClose)
#else
#error("Unsupported Platform")
#endif
id = ID(
rawValue: try PosixSpawn.spawn(
executablePath,
arguments: [executablePath.string] + arguments,
environment: environment.strings,
fileActions: &actions,
attributes: &attributes))!
}
private func terminate() {
let returnValue = kill(id.rawValue, SIGTERM)
assert(returnValue == 0)
}
/**
Waits on the process. This call is nonblocking and expects that the process represented by `processID` has already terminated
*/
private func wait(in context: Context) async throws {
/// Some key paths are different on Linux and macOS
#if canImport(Darwin)
let pid = \siginfo_t.si_pid
let sigchldInfo = \siginfo_t.self
let killingSignal = \siginfo_t.si_status
#elseif canImport(Glibc)
let pid = \siginfo_t._sifields._sigchld.si_pid
let sigchldInfo = \siginfo_t._sifields._sigchld
let killingSignal = \siginfo_t._sifields._rt.si_sigval.sival_int
#else
#error("Unsupported Platform")
#endif
var info = siginfo_t()
while true {
/**
We use a process ID of `0` to detect the case when the child is not in a waitable state.
Since we use the control channel to detect termination, this _shouldn't_ happen (unless the child decides to call `close(3)` for some reason).
*/
info[keyPath: pid] = 0
do {
errno = 0
var flags = WEXITED | WNOHANG
#if canImport(Glibc)
flags |= __WALL
#endif
let returnValue = waitid(P_PID, id_t(id.rawValue), &info, flags)
guard returnValue == 0 else {
throw TerminationError.waitFailed(returnValue: returnValue, errno: errno)
}
}
/**
By monitoring a file descriptor to detect when a process has terminated, we introduce the possibility of performing a nonblocking wait on a process before it is actually ready to be waited on. This can happen if we win the race with the kernel setting the child process into a waitable state after the kernel closes the file descriptor we are monitoring (this is rare, but has been observed and should only ever result in a 1 second delay). This could also be caused by unusual behavior in the child process (for instance, iterating over all of its own descriptors and closing the ones it doesn't know about, including the one we use for monitoring; in this case the overhead of polling should still be minimal).
*/
guard info[keyPath: pid] != 0 else {
/// Reset `info`
info = siginfo_t()
/// Wait for 1 second (we can't use `Task.sleep` because we want to wait on the child process even if it was cancelled)
let _: Void = await withCheckedContinuation { continuation in
context.eventLoopGroup.next().scheduleTask(in: .seconds(1)) {
continuation.resume()
}
}
/// Try `wait` again
continue
}
/// If we reached this point, the process was successfully waited on
break
}
/**
If the task has been cancelled, we want cancellation to supercede the temination status of the executable (often a SIGTERM).
*/
try Task.checkCancellation()
switch Int(info.si_code) {
case Int(CLD_EXITED):
let terminationStatus = info[keyPath: sigchldInfo].si_status
guard terminationStatus == 0 else {
throw TerminationError.nonzeroTerminationStatus(terminationStatus)
}
case Int(CLD_KILLED):
throw TerminationError.uncaughtSignal(info[keyPath: killingSignal], coreDumped: false)
case Int(CLD_DUMPED):
throw TerminationError.uncaughtSignal(info[keyPath: killingSignal], coreDumped: true)
default:
fatalError()
}
}
public struct ID: CustomStringConvertible {
init?(rawValue: pid_t) {
guard rawValue != -1 else {
return nil
}
self.rawValue = rawValue
}
let rawValue: pid_t
public var description: String { rawValue.description }
}
public let id: ID
}
// MARK: - Logging
public protocol ProcessLogger {
func failedToLaunchProcess(dueTo error: Error)
func didLaunch(_ process: Process)
func willWait(on process: Process)
func process(_ process: Process, didTerminateWithError: Error?)
}
// MARK: - File Descriptor Mapping
public extension Process {
struct FileDescriptorMapping: ExpressibleByDictionaryLiteral {
public init() {
self.init(entries: [])
}
public init(
standardInput: SystemPackage.FileDescriptor,
standardOutput: SystemPackage.FileDescriptor,
standardError: SystemPackage.FileDescriptor,
additionalFileDescriptors: KeyValuePairs<CInt, SystemPackage.FileDescriptor> = [:]
) {
self.init(
entries: [
(source: standardInput, target: STDIN_FILENO),
(source: standardOutput, target: STDOUT_FILENO),
(source: standardError, target: STDERR_FILENO),
] + additionalFileDescriptors.map { (source: $0.value, target: $0.key) })
}
public init(dictionaryLiteral elements: (CInt, SystemPackage.FileDescriptor)...) {
self.init(entries: elements.map { (source: $0.1, target: $0.0) })
}
private init(entries: [Entry]) {
/// Ensure each file descriptor is only mapped to once
precondition(Set(entries.map(\.target)).count == entries.count)
self.entries = entries
}
public mutating func addMapping(
from source: SystemPackage.FileDescriptor,
to target: CInt
) {
precondition(!entries.contains(where: { $0.target == target }))
entries.append((source: source, target: target))
}
fileprivate typealias Entry = (source: SystemPackage.FileDescriptor, target: CInt)
fileprivate private(set) var entries: [Entry]
}
}
// MARK: - Errors
extension Process {
struct SpawnError: Swift.Error {
let file: String
let line: Int
let returnValue: Int
let errorNumber: CInt
}
/**
An error which caused a spawned process to terminate
*/
public enum TerminationError: Swift.Error {
/**
Waiting on the process failed.
*/
case waitFailed(returnValue: CInt, errno: CInt)
/**
The process terminated successfully, but the termination status was nonzero.
*/
case nonzeroTerminationStatus(CInt)
/**
The process terminated due to an uncaught signal.
*/
case uncaughtSignal(CInt, coreDumped: Bool)
}
}
// MARK: - File Descriptor Monitor
private struct FileDescriptorMonitor {
static func create<T>(
in context: Context,
_ forwardMonitoredDescriptor: (SystemPackage.FileDescriptor) async throws -> T
) async throws -> (outcome: T, monitor: FileDescriptorMonitor) {
let future: EventLoopFuture<Void>
let outcome: T
(future, outcome) = try await FileDescriptor.withPipe { pipe in
let channel = try await context.withNullOutputDevice { nullOutput in
try await NIOPipeBootstrap(group: context.eventLoopGroup)
.channelInitializer { channel in
channel.pipeline.addHandler(Handler())
}
.duplicating(
inputDescriptor: pipe.readEnd,
outputDescriptor: nullOutput)
}
let outcome = try await forwardMonitoredDescriptor(pipe.writeEnd)
return (channel.closeFuture, outcome)
}
return (outcome, FileDescriptorMonitor(future: future))
}
func wait() async throws {
try await future.get()
}
private let future: EventLoopFuture<Void>
private final class Handler: ChannelInboundHandler {
typealias InboundIn = ByteBuffer
func channelRead(context: ChannelHandlerContext, data: NIOAny) {
/**
Writing data on the monitor descriptor is probably an error. In the future we might want to make incoming data cancel the invocation.
*/
assertionFailure()
}
}
}