feat(diagnostics): 验证统一面板沙盒指标读取能力

This commit is contained in:
2026-11-02 22:43:27 +08:00
parent 3518dbad7f
commit 7df2bbc7c1
6 changed files with 179 additions and 5 deletions
+12
View File
@@ -4,6 +4,7 @@ import Darwin
/// Serial ownership keeps CPU baselines coherent and system calls off MainActor.
actor SystemSampler {
private var cpu = CPUMonitor()
private var didProbe = false
private let diskHealth = DiskHealthMonitor()
private let batteryHealth = SystemBatteryHealthMonitor()
@@ -16,6 +17,13 @@ actor SystemSampler {
func reset() { cpu = CPUMonitor(); network = NetworkMonitor(); diskIO = DiskIOMonitor() }
func sample() async -> MetricsSnapshot {
if !didProbe {
didProbe = true
if ProcessInfo.processInfo.environment["KYMO_PANEL_PROBE"] == "1" {
PanelCapabilityProbe.run()
}
}
let sampleStart = ProcessInfo.processInfo.systemUptime
var result = MetricsSnapshot()
result.cpu = cpu.sample()
result.memory = MemoryMonitor.sample()
@@ -35,6 +43,10 @@ actor SystemSampler {
result.uptime = ProcessInfo.processInfo.systemUptime
var load = [Double](repeating: 0, count: 3)
if getloadavg(&load, 3) == 3 { result.load = load }
if ProcessInfo.processInfo.environment["KYMO_PANEL_PROBE"] == "1" {
let line = "{\"event\":\"sampleDuration\",\"milliseconds\":\((ProcessInfo.processInfo.systemUptime - sampleStart) * 1000)}\n"
try? FileHandle.standardOutput.write(contentsOf: Data(line.utf8))
}
return result
}
}
@@ -0,0 +1,134 @@
import Foundation
import Darwin
import IOKit
/// One-shot, explicit local diagnostics. Never runs during ordinary sampling.
/// Reports coverage and errors without logging process paths or network addresses.
nonisolated enum PanelCapabilityProbe {
static func run() {
let start = ProcessInfo.processInfo.systemUptime
var result: [String: Any] = ["event": "panelCapabilities", "pid": getpid()]
errno = 0
let required = proc_listpids(UInt32(PROC_ALL_PIDS), 0, nil, 0)
result["enumerationErrno"] = errno
var pids = [Int32](repeating: 0, count: max(1, Int(required) / MemoryLayout<Int32>.size + 256))
errno = 0
let capacity = Int32(pids.count * MemoryLayout<Int32>.size)
let bytes = pids.withUnsafeMutableBytes { proc_listpids(UInt32(PROC_ALL_PIDS), 0, $0.baseAddress, capacity) }
result["listErrno"] = errno
var listed = bytes > 0 ? Array(pids.prefix(Int(bytes) / MemoryLayout<Int32>.size)).filter { $0 > 0 } : []
result["enumerated"] = listed.count
var mib: [Int32] = [CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0]
var processBytes = 0
errno = 0
let sysctlStatus = sysctl(&mib, u_int(mib.count), nil, &processBytes, nil, 0)
result["sysctlProcessStatus"] = sysctlStatus
result["sysctlProcessErrno"] = errno
result["sysctlProcessRequiredBytes"] = processBytes
var owners: [Int32: uid_t] = [:]
if sysctlStatus == 0 {
for _ in 0..<3 {
var entries = [kinfo_proc](repeating: kinfo_proc(), count: processBytes / MemoryLayout<kinfo_proc>.stride + 256)
var actualBytes = entries.count * MemoryLayout<kinfo_proc>.stride
errno = 0
let status = entries.withUnsafeMutableBytes { sysctl(&mib, u_int(mib.count), $0.baseAddress, &actualBytes, nil, 0) }
result["sysctlDataStatus"] = status
result["sysctlDataErrno"] = errno
if status == 0 {
for entry in entries.prefix(actualBytes / MemoryLayout<kinfo_proc>.stride) where entry.kp_proc.p_pid > 0 {
owners[entry.kp_proc.p_pid] = entry.kp_eproc.e_ucred.cr_uid
}
result["sysctlEnumerated"] = owners.count
listed = Array(Set(listed).union(owners.keys))
break
}
if errno != ENOMEM { break }
processBytes = max(actualBytes, processBytes * 2)
}
}
result["possiblyTruncated"] = bytes == capacity
// Always probe self and launchd even when enumeration is denied.
var groups: [String: [String: Int]] = [:]
for pid in Set(listed + [getpid(), 1]).sorted() {
var info = proc_taskallinfo()
errno = 0
let read = proc_pidinfo(pid, PROC_PIDTASKALLINFO, 0, &info, Int32(MemoryLayout.size(ofValue: info)))
let readError = errno
let valid = read == MemoryLayout.size(ofValue: info)
let owner = valid ? info.pbsd.pbi_uid : owners[pid]
let group = pid == getpid() ? "self" : (owner.map { $0 == getuid() ? "sameUser" : "otherUser" } ?? "unknownOwner")
var counts = groups[group, default: [:]]
counts["attempted", default: 0] += 1
counts[valid ? "taskAndIdentityReadable" : "taskFailed", default: 0] += 1
if !valid { counts["taskErrno_\(readError)", default: 0] += 1 }
if valid {
counts["rssReadable", default: 0] += 1
counts["threadsReadable", default: 0] += 1
counts["cpuCountersReadable", default: 0] += 1
if info.pbsd.pbi_start_tvsec > 0 { counts["startIdentityReadable", default: 0] += 1 }
}
var bsd = proc_bsdinfo()
errno = 0
let bsdBytes = proc_pidinfo(pid, PROC_PIDTBSDINFO, 0, &bsd, Int32(MemoryLayout.size(ofValue: bsd)))
counts[bsdBytes == MemoryLayout.size(ofValue: bsd) ? "bsdReadable" : "bsdFailed", default: 0] += 1
if bsdBytes != MemoryLayout.size(ofValue: bsd) { counts["bsdErrno_\(errno)", default: 0] += 1 }
var task = proc_taskinfo()
errno = 0
let taskBytes = proc_pidinfo(pid, PROC_PIDTASKINFO, 0, &task, Int32(MemoryLayout.size(ofValue: task)))
counts[taskBytes == MemoryLayout.size(ofValue: task) ? "taskOnlyReadable" : "taskOnlyFailed", default: 0] += 1
if taskBytes != MemoryLayout.size(ofValue: task) { counts["taskOnlyErrno_\(errno)", default: 0] += 1 }
var path = [CChar](repeating: 0, count: 4 * Int(MAXPATHLEN))
errno = 0
let pathBytes = proc_pidpath(pid, &path, UInt32(path.count))
counts[pathBytes > 0 ? "pathReadable" : "pathFailed", default: 0] += 1
if pathBytes <= 0 { counts["pathErrno_\(errno)", default: 0] += 1 }
groups[group] = counts
if pid == 1 { result["launchdTaskBytes"] = read; result["launchdTaskErrno"] = readError }
}
result["processCoverage"] = groups
var addresses: [String: [String: Int]] = [:]
var head: UnsafeMutablePointer<ifaddrs>?
errno = 0
let addressStatus = getifaddrs(&head)
result["addressStatus"] = addressStatus
result["addressErrno"] = errno
if addressStatus == 0 {
defer { freeifaddrs(head) }
var cursor = head
while let entry = cursor {
defer { cursor = entry.pointee.ifa_next }
guard let address = entry.pointee.ifa_addr else { continue }
let family = Int32(address.pointee.sa_family)
guard family == AF_INET || family == AF_INET6 else { continue }
let name = String(cString: entry.pointee.ifa_name)
addresses[name, default: [:]][family == AF_INET ? "ipv4" : "ipv6", default: 0] += 1
}
}
result["addressFamiliesByInterface"] = addresses
var iterator: io_iterator_t = 0
let gpuStatus = IOServiceGetMatchingServices(kIOMainPortDefault, IOServiceMatching("IOAccelerator"), &iterator)
result["gpuRegistryStatus"] = gpuStatus
var accelerators: [[String: Any]] = []
if gpuStatus == KERN_SUCCESS {
defer { IOObjectRelease(iterator) }
while true {
let service = IOIteratorNext(iterator)
guard service != 0 else { break }
defer { IOObjectRelease(service) }
let stats = IORegistryEntryCreateCFProperty(service, "PerformanceStatistics" as CFString, kCFAllocatorDefault, 0)?.takeRetainedValue() as? [String: Any]
var item: [String: Any] = ["performanceKeys": stats?.keys.sorted() ?? []]
// Raw values only: no claim about units or independent core counters.
item["numericStatistics"] = stats?.filter { $0.value is NSNumber }
item["gpuCoreCount"] = IORegistryEntryCreateCFProperty(service, "gpu-core-count" as CFString, kCFAllocatorDefault, 0)?.takeRetainedValue() as? NSNumber
accelerators.append(item)
}
}
result["accelerators"] = accelerators
result["elapsedMilliseconds"] = (ProcessInfo.processInfo.systemUptime - start) * 1000
if let data = try? JSONSerialization.data(withJSONObject: result, options: [.sortedKeys]) {
try? FileHandle.standardOutput.write(contentsOf: data + Data([10]))
}
}
}