feat(monitors): 接入统一面板数据与按需进程采样
This commit is contained in:
@@ -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 }
|
||||
|
||||
@@ -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 }
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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: ©) { 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
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user