feat(monitors): 接入统一面板数据与按需进程采样

This commit is contained in:
2026-11-02 22:58:33 +08:00
parent 7df2bbc7c1
commit 604086bbbb
14 changed files with 391 additions and 32 deletions
+19 -1
View File
@@ -8,18 +8,36 @@ nonisolated struct TrendSample: Sendable {
var download: Double?
var disk: Double?
var battery: Double?
var upload: Double?
var read: Double?
var write: Double?
}
/// Bounded sampling history; no timer or UI visibility dependence.
nonisolated struct MetricHistory: Sendable {
static let capacity = 60
private(set) var samples: [TrendSample] = []
private(set) var interfaces: [String: [InterfaceTrendSample]] = [:]
mutating func append(_ snapshot: MetricsSnapshot) {
samples.append(TrendSample(date: snapshot.date, cpu: snapshot.cpu?.usage,
gpu: snapshot.gpuUsage, memory: snapshot.memory?.usage,
download: snapshot.downloadRate, disk: snapshot.disk?.usage,
battery: snapshot.battery?.charge))
battery: snapshot.battery?.charge, upload: snapshot.uploadRate,
read: snapshot.diskIO?.read, write: snapshot.diskIO?.written))
let current = snapshot.network ?? []
let keys = Set(current.map(\.identity))
interfaces = interfaces.filter { keys.contains($0.key) }
for item in current {
interfaces[item.identity, default: []].append(InterfaceTrendSample(date: snapshot.date, download: item.download, upload: item.upload))
if interfaces[item.identity, default: []].count > Self.capacity { interfaces[item.identity]?.removeFirst() }
}
if samples.count > Self.capacity { samples.removeFirst(samples.count - Self.capacity) }
}
}
nonisolated struct InterfaceTrendSample: Sendable {
let date: Date
let download: Double?
let upload: Double?
}
+20 -3
View File
@@ -30,15 +30,32 @@ nonisolated struct MetricsSnapshot: Sendable {
var battery: BatteryMetrics?
var load: [Double] = []
var uptime: TimeInterval = 0
// GPU remains unavailable until a reliable IOReport subscription is validated.
var gpu: GPUMetrics?
var processes: ProcessSnapshot?
var diskHealthDate: Date?
var batteryHealthDate: Date?
var batteryState: BatteryAvailability = .unknown
// GPU total is backed by validated IOAccelerator device statistics.
var gpuUsage: Double? = nil
}
nonisolated extension MetricsSnapshot {
var downloadRate: Double? {
guard let network else { return nil }
let rates = network.compactMap(\.download)
guard rates.count == network.count else { return nil }
let included = network.filter { $0.isIncludedInTotal }
guard !included.isEmpty else { return nil }
let rates = included.compactMap(\.download)
guard rates.count == included.count else { return nil }
return rates.reduce(0, +)
}
}
nonisolated enum BatteryAvailability: Sendable { case unknown, present, absent, failed }
nonisolated extension MetricsSnapshot {
var uploadRate: Double? {
guard let included = network?.filter({ $0.isIncludedInTotal }), !included.isEmpty else { return nil }
let values = included.compactMap(\.upload)
return values.count == included.count ? values.reduce(0, +) : nil
}
}
+25
View File
@@ -0,0 +1,25 @@
import Foundation
nonisolated struct ProcessIdentity: Hashable, Sendable {
let pid: Int32
let seconds: UInt64
let microseconds: UInt64
}
nonisolated struct ProcessMetrics: Identifiable, Sendable {
let id: ProcessIdentity
let name: String
let path: String?
let cpu: Double? // One logical CPU = 100%; may exceed 1.
let residentBytes: UInt64?
let threads: Int?
let restricted: Bool
}
nonisolated struct ProcessSnapshot: Sendable {
let date: Date
let enumerated: Int
let readable: Int
let rows: [ProcessMetrics]
let failed: Bool
}
+10
View File
@@ -24,6 +24,16 @@ nonisolated enum BatteryMonitor {
return max(1, Int((systemSeconds / 60).rounded(.up)))
}
static func availability() -> BatteryAvailability {
guard let info = IOPSCopyPowerSourcesInfo()?.takeRetainedValue(),
let sources = IOPSCopyPowerSourcesList(info)?.takeRetainedValue() as? [CFTypeRef] else { return .failed }
for source in sources {
guard let item = IOPSGetPowerSourceDescription(info, source)?.takeUnretainedValue() as? [String: Any] else { return .failed }
if item[kIOPSTypeKey] as? String == kIOPSInternalBatteryType { return .present }
}
return .absent
}
static func sample() -> BatteryMetrics? {
guard let info = IOPSCopyPowerSourcesInfo()?.takeRetainedValue(),
let sources = IOPSCopyPowerSourcesList(info)?.takeRetainedValue() as? [CFTypeRef] else { return nil }
+32
View File
@@ -0,0 +1,32 @@
import Foundation
import IOKit
nonisolated struct GPUMetrics: Sendable {
let usage: Double?
let coreCount: Int?
// Independent per-core counters have not been obtained. Never split total usage.
}
nonisolated enum GPUMonitor {
static func sample() -> GPUMetrics? {
var iterator: io_iterator_t = 0
guard IOServiceGetMatchingServices(kIOMainPortDefault, IOServiceMatching("IOAccelerator"), &iterator) == KERN_SUCCESS else { return nil }
defer { IOObjectRelease(iterator) }
var devices: [GPUMetrics] = []
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]
let raw = (stats?["Device Utilization %"] as? NSNumber)?.doubleValue
let cores = (IORegistryEntryCreateCFProperty(service, "gpu-core-count" as CFString, kCFAllocatorDefault, 0)?.takeRetainedValue() as? NSNumber)?.intValue
devices.append(GPUMetrics(usage: normalized(raw), coreCount: cores.flatMap { $0 > 0 ? $0 : nil }))
}
// Do not average incompatible utilization counters on multi-GPU machines.
return devices.count == 1 ? devices[0] : nil
}
static func normalized(_ value: Double?) -> Double? {
value.flatMap { $0.isFinite && (0...100).contains($0) ? $0 / 100 : nil }
}
}
+41 -3
View File
@@ -7,11 +7,17 @@ nonisolated struct NetworkInterfaceMetrics: Sendable {
let sent: UInt64
let download: Double?
let upload: Double?
var index: UInt32 = 0
var addresses: [String] = []
var active: Bool = true
var isIncludedInTotal: Bool { name.hasPrefix("en") && active }
var identity: String { "\(index):\(name)" }
}
nonisolated struct NetworkMonitor {
private var previous: [String: (UInt64, UInt64)] = [:]
private var timestamp: TimeInterval?
private var identities: [String: String] = [:]
static func rate(current: UInt64, previous: UInt64?, elapsed: TimeInterval) -> Double? {
guard let previous, elapsed.isFinite, elapsed > 0, current >= previous else { return nil }
@@ -22,17 +28,49 @@ nonisolated struct NetworkMonitor {
guard let counters = Self.counters() else { previous = [:]; timestamp = nil; return nil }
let now = ProcessInfo.processInfo.systemUptime
let elapsed = timestamp.map { now - $0 } ?? 0
let metadata = Self.interfaces()
let result = counters.keys.sorted().map { name in
let current = counters[name]!
let item = metadata[name]
let identity = "\(item?.index ?? 0):\(name):\(item?.active ?? false):\(item?.addresses.joined(separator: ",") ?? "")"
let old = identities[name] == identity ? previous[name] : nil
return NetworkInterfaceMetrics(name: name, received: current.0, sent: current.1,
download: Self.rate(current: current.0, previous: previous[name]?.0, elapsed: elapsed),
upload: Self.rate(current: current.1, previous: previous[name]?.1, elapsed: elapsed))
download: Self.rate(current: current.0, previous: old?.0, elapsed: elapsed),
upload: Self.rate(current: current.1, previous: old?.1, elapsed: elapsed),
index: item?.index ?? 0, addresses: item?.addresses ?? [], active: item?.active ?? false)
}
identities = Dictionary(uniqueKeysWithValues: result.map {
($0.name, "\($0.index):\($0.name):\($0.active):\($0.addresses.joined(separator: ","))")
})
previous = counters
timestamp = now
return result
}
private static func interfaces() -> [String: (index: UInt32, addresses: [String], active: Bool)] {
var head: UnsafeMutablePointer<ifaddrs>?
guard getifaddrs(&head) == 0 else { return [:] }
defer { freeifaddrs(head) }
var result: [String: (index: UInt32, addresses: [String], active: Bool)] = [:]
var cursor = head
while let entry = cursor {
defer { cursor = entry.pointee.ifa_next }
let name = String(cString: entry.pointee.ifa_name)
let flags = entry.pointee.ifa_flags
let active = flags & UInt32(IFF_UP | IFF_RUNNING) == UInt32(IFF_UP | IFF_RUNNING)
var item = result[name] ?? (if_nametoindex(entry.pointee.ifa_name), [], active)
if let address = entry.pointee.ifa_addr, [UInt8(AF_INET), UInt8(AF_INET6)].contains(address.pointee.sa_family) {
var host = [CChar](repeating: 0, count: Int(NI_MAXHOST))
if getnameinfo(address, socklen_t(address.pointee.sa_len), &host, socklen_t(host.count), nil, 0, NI_NUMERICHOST) == 0 {
item.addresses.append(String(cString: host))
}
}
item.addresses.sort()
result[name] = item
}
return result
}
/// NET_RT_IFLIST2 exposes 64-bit counters, avoiding getifaddrs' 4 GB wrap.
private static func counters() -> [String: (UInt64, UInt64)]? {
var mib: [Int32] = [CTL_NET, PF_ROUTE, 0, 0, NET_RT_IFLIST2, 0]
@@ -62,7 +100,7 @@ nonisolated struct NetworkMonitor {
var name = [CChar](repeating: 0, count: Int(IFNAMSIZ))
if if_indextoname(UInt32(message.ifm_index), &name) != nil {
let identifier = String(cString: name)
if identifier.hasPrefix("en") {
if !identifier.hasPrefix("lo") {
result[identifier] = (message.ifm_data.ifi_ibytes, message.ifm_data.ifi_obytes)
}
}
+81
View File
@@ -0,0 +1,81 @@
import Foundation
import Darwin
nonisolated struct ProcessMonitor: Sendable {
private var previous: [ProcessIdentity: (UInt64, TimeInterval)] = [:]
private var sampleSerial: UInt64 = 0
static func cpu(current: UInt64, previous: UInt64?, elapsed: TimeInterval) -> Double? {
guard let previous, current >= previous, elapsed.isFinite, elapsed > 0 else { return nil }
return Double(current - previous) / 1_000_000_000 / elapsed
}
mutating func sample() -> ProcessSnapshot {
sampleSerial &+= 1
let date = Date()
guard let entries = Self.entries() else {
previous = [:]
return ProcessSnapshot(date: date, enumerated: 0, readable: 0, rows: [], failed: true)
}
let now = ProcessInfo.processInfo.systemUptime
var next: [ProcessIdentity: (UInt64, TimeInterval)] = [:]
var rows: [ProcessMetrics] = []
for entry in entries where entry.kp_proc.p_pid > 0 {
let pid = entry.kp_proc.p_pid
var info = proc_taskallinfo()
let valid = proc_pidinfo(pid, PROC_PIDTASKALLINFO, 0, &info, Int32(MemoryLayout.size(ofValue: info))) == MemoryLayout.size(ofValue: info)
if valid && (info.pbsd.pbi_start_tvsec != UInt64(max(0, entry.kp_proc.p_starttime.tv_sec)) ||
info.pbsd.pbi_start_tvusec != UInt64(max(0, entry.kp_proc.p_starttime.tv_usec))) { continue }
// kinfo_proc carries a start time even when task details are restricted.
let seconds = valid ? info.pbsd.pbi_start_tvsec : UInt64(max(0, entry.kp_proc.p_starttime.tv_sec))
let micros = valid ? info.pbsd.pbi_start_tvusec : UInt64(max(0, entry.kp_proc.p_starttime.tv_usec))
let id = ProcessIdentity(pid: pid, seconds: seconds, microseconds: seconds == 0 ? sampleSerial : micros)
var copy = entry.kp_proc.p_comm
let name = withUnsafeBytes(of: &copy) { raw in
String(decoding: raw.prefix { $0 != 0 }, as: UTF8.self)
}
var path = [CChar](repeating: 0, count: 4 * Int(MAXPATHLEN))
let pathSize = proc_pidpath(pid, &path, UInt32(path.count))
var usage: Double?
if valid && seconds > 0 {
let (total, overflow) = info.ptinfo.pti_total_user.addingReportingOverflow(info.ptinfo.pti_total_system)
if !overflow {
usage = Self.cpu(current: total, previous: previous[id]?.0, elapsed: now - (previous[id]?.1 ?? now))
next[id] = (total, now)
}
}
rows.append(ProcessMetrics(id: id, name: name, path: pathSize > 0 ? String(cString: path) : nil,
cpu: usage, residentBytes: valid ? info.ptinfo.pti_resident_size : nil,
threads: valid ? Int(info.ptinfo.pti_threadnum) : nil, restricted: !valid))
}
// Recheck the enumeration identity after path reads; never attach a reused PID's path.
if let latest = Self.entries() {
let identities = Set(latest.map {
ProcessIdentity(pid: $0.kp_proc.p_pid, seconds: UInt64(max(0, $0.kp_proc.p_starttime.tv_sec)),
microseconds: UInt64(max(0, $0.kp_proc.p_starttime.tv_usec)))
})
rows.removeAll { $0.id.seconds > 0 && !identities.contains($0.id) }
} else {
rows = rows.map { ProcessMetrics(id: $0.id, name: $0.name, path: nil, cpu: $0.cpu,
residentBytes: $0.residentBytes, threads: $0.threads, restricted: $0.restricted) }
}
let retained = Set(rows.map(\.id))
previous = next.filter { retained.contains($0.key) }
return ProcessSnapshot(date: date, enumerated: entries.filter { $0.kp_proc.p_pid > 0 }.count,
readable: rows.filter { !$0.restricted }.count, rows: rows, failed: false)
}
private static func entries() -> [kinfo_proc]? {
var mib: [Int32] = [CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0]
for _ in 0..<3 {
var bytes = 0
guard sysctl(&mib, u_int(mib.count), nil, &bytes, nil, 0) == 0 else { return nil }
var entries = [kinfo_proc](repeating: kinfo_proc(), count: bytes / MemoryLayout<kinfo_proc>.stride + 256)
bytes = entries.count * MemoryLayout<kinfo_proc>.stride
let status = entries.withUnsafeMutableBytes { sysctl(&mib, u_int(mib.count), $0.baseAddress, &bytes, nil, 0) }
if status == 0 { return Array(entries.prefix(bytes / MemoryLayout<kinfo_proc>.stride)) }
if errno != ENOMEM { return nil }
}
return nil
}
}
+76 -17
View File
@@ -1,52 +1,111 @@
import Foundation
import Darwin
/// Serial ownership keeps CPU baselines coherent and system calls off MainActor.
/// One coordinator owns baselines; slow workers have at most one in-flight call each.
actor SystemSampler {
private var cpu = CPUMonitor()
private var didProbe = false
private let diskHealth = DiskHealthMonitor()
private let batteryHealth = SystemBatteryHealthMonitor()
private var network = NetworkMonitor()
private let networkPath = NetworkPathObserver()
private var diskIO = DiskIOMonitor()
private var volumes: [VolumeMetrics]?
private var volumeSampleTime: TimeInterval?
private var volumeSampleTime: TimeInterval = -.infinity
private var volumeTask: Task<Void, Never>?
private var diskTask: Task<Void, Never>?
private var batteryTask: Task<Void, Never>?
private var diskCache: DiskHealthMetrics?
private var batteryCache: Double?
private var diskDate: Date?
private var batteryDate: Date?
private var nextDisk: TimeInterval = 0
private var nextBattery: TimeInterval = 0
private var processMonitor = ProcessMonitor()
private var processTask: Task<Void, Never>?
private var processCache: ProcessSnapshot?
private var processVisible = false
private var processGeneration = 0
func reset() { cpu = CPUMonitor(); network = NetworkMonitor(); diskIO = DiskIOMonitor() }
func sample() async -> MetricsSnapshot {
func setProcessVisible(_ visible: Bool) {
guard visible != processVisible else { return }
processVisible = visible
processGeneration += 1
processCache = nil
processMonitor = ProcessMonitor()
// A synchronous OS read may outlive cancellation. Keep the in-flight slot occupied.
}
func sample() -> MetricsSnapshot {
if !didProbe {
didProbe = true
if ProcessInfo.processInfo.environment["KYMO_PANEL_PROBE"] == "1" {
PanelCapabilityProbe.run()
}
if ProcessInfo.processInfo.environment["KYMO_PANEL_PROBE"] == "1" { PanelCapabilityProbe.run() }
}
let sampleStart = ProcessInfo.processInfo.systemUptime
let start = ProcessInfo.processInfo.systemUptime
var result = MetricsSnapshot()
result.cpu = cpu.sample()
result.memory = MemoryMonitor.sample()
result.network = network.sample()
result.networkPath = networkPath.snapshot()
result.disk = DiskMonitor.sample()
result.diskHealth = await diskHealth.sample()
result.diskIO = diskIO.sample()
let now = ProcessInfo.processInfo.systemUptime
if volumeSampleTime == nil || now - (volumeSampleTime ?? 0) >= 30 {
volumes = DiskMonitor.volumes()
volumeSampleTime = now
}
result.volumes = volumes
result.battery = BatteryMonitor.sample()
if result.battery != nil { result.battery?.health = await batteryHealth.sample() }
result.batteryState = result.battery == nil ? BatteryMonitor.availability() : .present
result.gpu = GPUMonitor.sample()
result.gpuUsage = result.gpu?.usage
if volumeTask == nil && start - volumeSampleTime >= 30 {
volumeTask = Task.detached(priority: .utility) { [self] in
let value = DiskMonitor.volumes()
await finishVolumes(value)
}
}
if diskTask == nil && start >= nextDisk {
diskTask = Task { [self, diskHealth] in await finishDisk(diskHealth.sample()) }
}
if result.battery != nil && batteryTask == nil && start >= nextBattery {
batteryTask = Task { [self, batteryHealth] in await finishBattery(batteryHealth.sample()) }
}
if processVisible && processTask == nil {
let generation = processGeneration
let monitor = processMonitor
processTask = Task.detached(priority: .utility) { [self] in
var worker = monitor
let value = worker.sample()
await finishProcesses(value, monitor: worker, generation: generation)
}
}
result.processes = processVisible ? processCache : nil
result.diskHealth = diskCache
result.diskHealthDate = diskDate
result.battery?.health = batteryCache
result.batteryHealthDate = batteryDate
result.volumes = volumes
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"
let line = "{\"event\":\"sampleDuration\",\"milliseconds\":\((ProcessInfo.processInfo.systemUptime - start) * 1000)}\n"
try? FileHandle.standardOutput.write(contentsOf: Data(line.utf8))
}
return result
}
private func finishVolumes(_ value: [VolumeMetrics]?) {
volumes = value; volumeSampleTime = ProcessInfo.processInfo.systemUptime; volumeTask = nil
}
private func finishDisk(_ value: DiskHealthMetrics?) {
diskCache = value; diskDate = value == nil ? nil : Date()
nextDisk = ProcessInfo.processInfo.systemUptime + (value == nil ? 600 : 3600); diskTask = nil
}
private func finishBattery(_ value: Double?) {
batteryCache = value; batteryDate = value == nil ? nil : Date()
nextBattery = ProcessInfo.processInfo.systemUptime + (value == nil ? 600 : 3600); batteryTask = nil
}
private func finishProcesses(_ value: ProcessSnapshot, monitor: ProcessMonitor, generation: Int) {
processTask = nil
guard processVisible, generation == processGeneration else { return }
processMonitor = monitor; processCache = value
}
}
+21 -2
View File
@@ -6,6 +6,9 @@ final class MetricsStore {
private(set) var snapshot = MetricsSnapshot()
private(set) var history = MetricHistory()
private(set) var isPaused = false
private(set) var isPanelVisible = false
@ObservationIgnored private var generation = 0
@ObservationIgnored private var visibilityGeneration = 0
@ObservationIgnored private var task: Task<Void, Never>?
@ObservationIgnored private let sampler = SystemSampler()
@@ -14,11 +17,16 @@ final class MetricsStore {
func start() {
guard task == nil else { return }
isPaused = false
generation += 1
let currentGeneration = generation
task = Task { [weak self, sampler] in
await sampler.reset()
await sampler.setProcessVisible(self?.isPanelVisible == true)
while !Task.isCancelled {
let next = await sampler.sample()
guard !Task.isCancelled else { return }
let visibleGeneration = self?.visibilityGeneration
var next = await sampler.sample()
guard !Task.isCancelled, self?.generation == currentGeneration else { return }
if self?.isPanelVisible != true || self?.visibilityGeneration != visibleGeneration { next.processes = nil }
self?.snapshot = next
self?.history.append(next)
SamplingDiagnostics.record(next)
@@ -31,12 +39,23 @@ final class MetricsStore {
func togglePause() {
if isPaused { start() }
else {
generation += 1
task?.cancel()
task = nil
Task { await sampler.setProcessVisible(false) }
isPaused = true
SamplingDiagnostics.record(snapshot, event: "pause")
}
}
func setPanelVisible(_ visible: Bool) {
guard isPanelVisible != visible else { return }
visibilityGeneration += 1
isPanelVisible = visible
if !visible { snapshot.processes = nil }
let active = visible && !isPaused
Task { await sampler.setProcessVisible(active) }
}
deinit { task?.cancel() }
}
@@ -14,6 +14,10 @@ nonisolated enum SamplingDiagnostics {
]
payload["cpu"] = snapshot.cpu?.usage
payload["cores"] = snapshot.cpu?.cores.count
payload["gpuUsage"] = snapshot.gpuUsage
payload["gpuCoreCount"] = snapshot.gpu?.coreCount
payload["processEnumerated"] = snapshot.processes?.enumerated
payload["processReadable"] = snapshot.processes?.readable
payload["memoryUsed"] = snapshot.memory?.used
payload["memoryTotal"] = snapshot.memory?.total
payload["swapUsed"] = snapshot.memory?.swapUsed