feat(monitors): 实现 C 阶段网络存储电池监控与三语详情
This commit is contained in:
@@ -0,0 +1,50 @@
|
||||
import Foundation
|
||||
import IOKit
|
||||
|
||||
nonisolated struct DiskIOMetrics: Sendable {
|
||||
let read: Double?
|
||||
let written: Double?
|
||||
}
|
||||
|
||||
/// Driver counters describe physical block IO, not per-volume file traffic.
|
||||
nonisolated struct DiskIOMonitor {
|
||||
private var previous: [UInt64: (UInt64, UInt64)] = [:]
|
||||
private var timestamp: TimeInterval?
|
||||
|
||||
mutating func sample() -> DiskIOMetrics? {
|
||||
var iterator: io_iterator_t = 0
|
||||
guard IOServiceGetMatchingServices(kIOMainPortDefault, IOServiceMatching("IOBlockStorageDriver"), &iterator) == KERN_SUCCESS else {
|
||||
previous = [:]; timestamp = nil; return nil
|
||||
}
|
||||
defer { IOObjectRelease(iterator) }
|
||||
var counters: [UInt64: (UInt64, UInt64)] = [:]
|
||||
while true {
|
||||
let service = IOIteratorNext(iterator)
|
||||
guard service != 0 else { break }
|
||||
defer { IOObjectRelease(service) }
|
||||
var identifier: UInt64 = 0
|
||||
guard IORegistryEntryGetRegistryEntryID(service, &identifier) == KERN_SUCCESS,
|
||||
let stats = IORegistryEntryCreateCFProperty(service, "Statistics" as CFString, kCFAllocatorDefault, 0)?.takeRetainedValue() as? [String: Any],
|
||||
let read = stats["Bytes (Read)"] as? UInt64,
|
||||
let written = stats["Bytes (Write)"] as? UInt64 else { continue }
|
||||
counters[identifier] = (read, written)
|
||||
}
|
||||
let now = ProcessInfo.processInfo.systemUptime
|
||||
defer { previous = counters; timestamp = now }
|
||||
guard !counters.isEmpty else { return nil }
|
||||
guard let timestamp, Set(counters.keys) == Set(previous.keys) else {
|
||||
return DiskIOMetrics(read: nil, written: nil)
|
||||
}
|
||||
var read: Double = 0
|
||||
var written: Double = 0
|
||||
for (id, current) in counters {
|
||||
guard let old = previous[id],
|
||||
let r = NetworkMonitor.rate(current: current.0, previous: old.0, elapsed: now - timestamp),
|
||||
let w = NetworkMonitor.rate(current: current.1, previous: old.1, elapsed: now - timestamp) else {
|
||||
return DiskIOMetrics(read: nil, written: nil)
|
||||
}
|
||||
read += r; written += w
|
||||
}
|
||||
return DiskIOMetrics(read: read, written: written)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user