fix(monitors): 限制外部报告输出并可靠终止超时子进程
This commit is contained in:
@@ -33,24 +33,8 @@ actor SystemBatteryHealthMonitor {
|
||||
}
|
||||
|
||||
nonisolated private static func readReport() async -> Double? {
|
||||
await withCheckedContinuation { continuation in
|
||||
// Process/pipe waits use a utility queue rather than the cooperative executor.
|
||||
DispatchQueue.global(qos: .utility).async {
|
||||
let process = Process()
|
||||
process.executableURL = URL(fileURLWithPath: "/usr/sbin/system_profiler")
|
||||
process.arguments = ["SPPowerDataType", "-json", "-detailLevel", "mini", "-timeout", "5"]
|
||||
let pipe = Pipe()
|
||||
process.standardOutput = pipe
|
||||
process.standardError = FileHandle.nullDevice
|
||||
do { try process.run() }
|
||||
catch { continuation.resume(returning: nil); return }
|
||||
let deadline = DispatchWorkItem { if process.isRunning { process.terminate() } }
|
||||
DispatchQueue.global(qos: .utility).asyncAfter(deadline: .now() + 10, execute: deadline)
|
||||
let data = pipe.fileHandleForReading.readDataToEndOfFile()
|
||||
process.waitUntilExit()
|
||||
deadline.cancel()
|
||||
continuation.resume(returning: process.terminationStatus == 0 && data.count <= 262_144 ? parse(data) : nil)
|
||||
}
|
||||
}
|
||||
guard let data = await BoundedProcess.read(executable: URL(fileURLWithPath: "/usr/sbin/system_profiler"),
|
||||
arguments: ["SPPowerDataType", "-json", "-detailLevel", "mini", "-timeout", "5"]) else { return nil }
|
||||
return parse(data)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
import Foundation
|
||||
import Darwin
|
||||
|
||||
/// Short read-only reports. Both retained output and the child lifetime are bounded.
|
||||
nonisolated enum BoundedProcess {
|
||||
static func read(executable: URL, arguments: [String], limit: Int = 262_144,
|
||||
timeout: TimeInterval = 10) async -> Data? {
|
||||
guard limit >= 0, limit < Int.max, timeout.isFinite, timeout > 0 else { return nil }
|
||||
let wake = Wakeup()
|
||||
return await withTaskCancellationHandler {
|
||||
await withCheckedContinuation { continuation in
|
||||
DispatchQueue.global(qos: .utility).async {
|
||||
defer { wake.close() }
|
||||
continuation.resume(returning: collect(executable: executable, arguments: arguments,
|
||||
limit: limit, timeout: timeout, wake: wake))
|
||||
}
|
||||
}
|
||||
} onCancel: { wake.cancel() }
|
||||
}
|
||||
|
||||
private static func collect(executable: URL, arguments: [String], limit: Int,
|
||||
timeout: TimeInterval, wake: Wakeup) -> Data? {
|
||||
guard !wake.cancelled else { return nil }
|
||||
let process = Process()
|
||||
let output = Pipe()
|
||||
process.executableURL = executable
|
||||
process.arguments = arguments
|
||||
process.standardOutput = output
|
||||
process.standardError = FileHandle.nullDevice
|
||||
process.terminationHandler = { _ in wake.signal() }
|
||||
do { try process.run() } catch { return nil }
|
||||
try? output.fileHandleForWriting.close()
|
||||
defer {
|
||||
// Only the direct child we launched; never signal a process group or unrelated PID.
|
||||
if process.isRunning { Darwin.kill(process.processIdentifier, SIGKILL) }
|
||||
process.waitUntilExit()
|
||||
process.terminationHandler = nil
|
||||
try? output.fileHandleForReading.close()
|
||||
}
|
||||
let deadline = ProcessInfo.processInfo.systemUptime + timeout
|
||||
var data = Data()
|
||||
var buffer = [UInt8](repeating: 0, count: min(8192, limit + 1))
|
||||
var eof = false
|
||||
while true {
|
||||
guard !wake.cancelled else { return nil }
|
||||
if eof && !process.isRunning { return process.terminationStatus == 0 ? data : nil }
|
||||
let remaining = deadline - ProcessInfo.processInfo.systemUptime
|
||||
guard remaining > 0 else { return nil }
|
||||
var fds = [pollfd(fd: eof ? -1 : output.fileHandleForReading.fileDescriptor, events: Int16(POLLIN), revents: 0),
|
||||
pollfd(fd: wake.reader, events: Int16(POLLIN), revents: 0)]
|
||||
let ready = poll(&fds, nfds_t(fds.count), Int32(min(Double(Int32.max), ceil(remaining * 1000))))
|
||||
if ready < 0 { if errno == EINTR { continue }; return nil }
|
||||
if ready == 0 { return nil }
|
||||
if fds[1].revents != 0 { wake.drain() }
|
||||
guard !wake.cancelled else { return nil }
|
||||
if fds[0].revents & Int16(POLLERR | POLLNVAL) != 0 { return nil }
|
||||
if fds[0].revents & Int16(POLLIN | POLLHUP) != 0 {
|
||||
// One extra byte detects overflow without ever retaining oversized output.
|
||||
let count = Darwin.read(output.fileHandleForReading.fileDescriptor, &buffer, min(buffer.count, limit - data.count + 1))
|
||||
if count < 0 { if errno == EINTR { continue }; return nil }
|
||||
if count == 0 { eof = true; continue }
|
||||
guard count <= limit - data.count else { return nil }
|
||||
data.append(contentsOf: buffer.prefix(count))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A pipe wakes blocking poll on cancellation or exit; no periodic polling timer.
|
||||
private final class Wakeup: @unchecked Sendable {
|
||||
private let lock = NSLock()
|
||||
private let pipe = Pipe()
|
||||
private var didCancel = false
|
||||
private var closed = false
|
||||
var reader: Int32 { pipe.fileHandleForReading.fileDescriptor }
|
||||
var cancelled: Bool { lock.lock(); defer { lock.unlock() }; return didCancel }
|
||||
func cancel() { notify(cancel: true) }
|
||||
func signal() { notify(cancel: false) }
|
||||
private func notify(cancel: Bool) {
|
||||
lock.lock(); defer { lock.unlock() }
|
||||
guard !closed else { return }
|
||||
if cancel { didCancel = true }
|
||||
var byte: UInt8 = 1
|
||||
_ = Darwin.write(pipe.fileHandleForWriting.fileDescriptor, &byte, 1)
|
||||
}
|
||||
func drain() {
|
||||
var bytes = [UInt8](repeating: 0, count: 16)
|
||||
_ = Darwin.read(reader, &bytes, bytes.count)
|
||||
}
|
||||
func close() {
|
||||
lock.lock(); defer { lock.unlock() }
|
||||
closed = true
|
||||
try? pipe.fileHandleForReading.close()
|
||||
try? pipe.fileHandleForWriting.close()
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user