feat(monitors): 实现 C 阶段网络存储电池监控与三语详情
This commit is contained in:
@@ -0,0 +1,54 @@
|
||||
import Foundation
|
||||
import IOKit.ps
|
||||
|
||||
nonisolated struct BatteryMetrics: Sendable {
|
||||
let charge: Double?
|
||||
let charging: Bool
|
||||
let externalPower: Bool
|
||||
var minutesRemaining: Int?
|
||||
var cycles: Int?
|
||||
var health: Double?
|
||||
}
|
||||
|
||||
nonisolated enum BatteryMonitor {
|
||||
static func positiveMinutes(_ value: Int?) -> Int? {
|
||||
value.flatMap { $0 > 0 ? $0 : nil }
|
||||
}
|
||||
|
||||
static func estimatedMinutes(charging: Bool, externalPower: Bool, sourceMinutes: Int?, systemSeconds: Double) -> Int? {
|
||||
guard charging || !externalPower else { return nil }
|
||||
if let minutes = positiveMinutes(sourceMinutes) { return minutes }
|
||||
// The global estimate applies to discharge only and reports seconds.
|
||||
guard !charging, !externalPower, systemSeconds.isFinite,
|
||||
systemSeconds > 0, systemSeconds < Double(Int.max) else { return nil }
|
||||
return max(1, Int((systemSeconds / 60).rounded(.up)))
|
||||
}
|
||||
|
||||
static func sample() -> BatteryMetrics? {
|
||||
guard let info = IOPSCopyPowerSourcesInfo()?.takeRetainedValue(),
|
||||
let sources = IOPSCopyPowerSourcesList(info)?.takeRetainedValue() as? [CFTypeRef] else { return nil }
|
||||
for source in sources {
|
||||
guard let item = IOPSGetPowerSourceDescription(info, source)?.takeUnretainedValue() as? [String: Any],
|
||||
item[kIOPSTypeKey] as? String == kIOPSInternalBatteryType else { continue }
|
||||
let current = item[kIOPSCurrentCapacityKey] as? Double
|
||||
let maximum = item[kIOPSMaxCapacityKey] as? Double
|
||||
let charge = current.flatMap { c in maximum.flatMap { $0 > 0 ? min(1, max(0, c / $0)) : nil } }
|
||||
let service = IOServiceGetMatchingService(kIOMainPortDefault, IOServiceMatching("AppleSmartBattery"))
|
||||
var properties: [String: Any] = [:]
|
||||
if service != 0 {
|
||||
defer { IOObjectRelease(service) }
|
||||
var raw: Unmanaged<CFMutableDictionary>?
|
||||
if IORegistryEntryCreateCFProperties(service, &raw, kCFAllocatorDefault, 0) == KERN_SUCCESS {
|
||||
properties = raw?.takeRetainedValue() as? [String: Any] ?? [:]
|
||||
}
|
||||
}
|
||||
let charging = item[kIOPSIsChargingKey] as? Bool ?? false
|
||||
let external = item[kIOPSPowerSourceStateKey] as? String == kIOPSACPowerValue
|
||||
let minutes = charging ? item[kIOPSTimeToFullChargeKey] as? Int : external ? nil : item[kIOPSTimeToEmptyKey] as? Int
|
||||
return BatteryMetrics(charge: charge, charging: item[kIOPSIsChargingKey] as? Bool ?? false,
|
||||
externalPower: external, minutesRemaining: estimatedMinutes(charging: charging, externalPower: external, sourceMinutes: minutes, systemSeconds: IOPSGetTimeRemainingEstimate()),
|
||||
cycles: (properties["CycleCount"] as? Int).flatMap { $0 >= 0 ? $0 : nil })
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import Foundation
|
||||
|
||||
nonisolated struct DiskMetrics: Sendable {
|
||||
let total: UInt64
|
||||
let available: UInt64
|
||||
var usage: Double { total == 0 ? 0 : Double(total - min(total, available)) / Double(total) }
|
||||
}
|
||||
|
||||
nonisolated enum DiskMonitor {
|
||||
static func sample() -> DiskMetrics? {
|
||||
guard let values = try? URL(fileURLWithPath: NSHomeDirectory()).resourceValues(forKeys: [.volumeTotalCapacityKey, .volumeAvailableCapacityKey]),
|
||||
let total = values.volumeTotalCapacity, let available = values.volumeAvailableCapacity,
|
||||
total > 0, available >= 0 else { return nil }
|
||||
return DiskMetrics(total: UInt64(total), available: UInt64(available))
|
||||
}
|
||||
}
|
||||
|
||||
nonisolated struct VolumeMetrics: Sendable {
|
||||
let path: String
|
||||
let name: String
|
||||
let capacity: DiskMetrics
|
||||
}
|
||||
|
||||
nonisolated extension DiskMonitor {
|
||||
static func volumes() -> [VolumeMetrics]? {
|
||||
let keys: Set<URLResourceKey> = [.volumeNameKey, .volumeTotalCapacityKey, .volumeAvailableCapacityKey, .volumeIsLocalKey]
|
||||
guard let urls = FileManager.default.mountedVolumeURLs(includingResourceValuesForKeys: Array(keys), options: [.skipHiddenVolumes]) else { return nil }
|
||||
return urls.compactMap { url in
|
||||
guard let values = try? url.resourceValues(forKeys: keys), values.volumeIsLocal == true,
|
||||
let total = values.volumeTotalCapacity, total > 0,
|
||||
let available = values.volumeAvailableCapacity, available >= 0 else { return nil }
|
||||
return VolumeMetrics(path: url.path, name: values.volumeName ?? url.lastPathComponent,
|
||||
capacity: DiskMetrics(total: UInt64(total), available: UInt64(available)))
|
||||
}.sorted { $0.path < $1.path }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import Foundation
|
||||
import Darwin
|
||||
|
||||
nonisolated struct NetworkInterfaceMetrics: Sendable {
|
||||
let name: String
|
||||
let received: UInt64
|
||||
let sent: UInt64
|
||||
let download: Double?
|
||||
let upload: Double?
|
||||
}
|
||||
|
||||
nonisolated struct NetworkMonitor {
|
||||
private var previous: [String: (UInt64, UInt64)] = [:]
|
||||
private var timestamp: TimeInterval?
|
||||
|
||||
static func rate(current: UInt64, previous: UInt64?, elapsed: TimeInterval) -> Double? {
|
||||
guard let previous, elapsed.isFinite, elapsed > 0, current >= previous else { return nil }
|
||||
return Double(current - previous) / elapsed
|
||||
}
|
||||
|
||||
mutating func sample() -> [NetworkInterfaceMetrics]? {
|
||||
guard let counters = Self.counters() else { previous = [:]; timestamp = nil; return nil }
|
||||
let now = ProcessInfo.processInfo.systemUptime
|
||||
let elapsed = timestamp.map { now - $0 } ?? 0
|
||||
let result = counters.keys.sorted().map { name in
|
||||
let current = counters[name]!
|
||||
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))
|
||||
}
|
||||
previous = counters
|
||||
timestamp = now
|
||||
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]
|
||||
// The interface list can grow between size and data queries.
|
||||
for _ in 0..<3 {
|
||||
var count = 0
|
||||
guard sysctl(&mib, u_int(mib.count), nil, &count, nil, 0) == 0 else { return nil }
|
||||
guard count > 0 else { return [:] }
|
||||
var bytes = [UInt8](repeating: 0, count: count)
|
||||
let success = bytes.withUnsafeMutableBytes { raw in
|
||||
sysctl(&mib, u_int(mib.count), raw.baseAddress, &count, nil, 0)
|
||||
}
|
||||
if success != 0 { if errno == ENOMEM { continue }; return nil }
|
||||
return bytes.withUnsafeBytes { raw -> [String: (UInt64, UInt64)]? in
|
||||
var result: [String: (UInt64, UInt64)] = [:]
|
||||
var offset = 0
|
||||
while offset < count {
|
||||
guard count - offset >= 4 else { return nil }
|
||||
let length = Int(raw.loadUnaligned(fromByteOffset: offset, as: UInt16.self))
|
||||
guard length >= 4, length <= count - offset else { return nil }
|
||||
let type = raw[offset + 3]
|
||||
if type == UInt8(RTM_IFINFO2) {
|
||||
guard length >= MemoryLayout<if_msghdr2>.size else { return nil }
|
||||
let message = raw.loadUnaligned(fromByteOffset: offset, as: if_msghdr2.self)
|
||||
let flags = message.ifm_flags
|
||||
if flags & IFF_LOOPBACK == 0 && flags & (IFF_UP | IFF_RUNNING) == (IFF_UP | IFF_RUNNING) {
|
||||
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") {
|
||||
result[identifier] = (message.ifm_data.ifi_ibytes, message.ifm_data.ifi_obytes)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
offset += length
|
||||
}
|
||||
return result
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import Foundation
|
||||
import Network
|
||||
|
||||
nonisolated enum NetworkPathStatus: Sendable {
|
||||
case available, unavailable, requiresConnection
|
||||
}
|
||||
|
||||
/// OS route status only; no probes and no independent polling timer.
|
||||
nonisolated final class NetworkPathObserver: @unchecked Sendable {
|
||||
private let monitor = NWPathMonitor()
|
||||
private let lock = NSLock()
|
||||
private var status: NetworkPathStatus?
|
||||
|
||||
init() {
|
||||
monitor.pathUpdateHandler = { [weak self] path in
|
||||
guard let self else { return }
|
||||
let next: NetworkPathStatus
|
||||
switch path.status {
|
||||
case .satisfied: next = .available
|
||||
case .requiresConnection: next = .requiresConnection
|
||||
default: next = .unavailable
|
||||
}
|
||||
self.lock.lock()
|
||||
self.status = next
|
||||
self.lock.unlock()
|
||||
}
|
||||
monitor.start(queue: DispatchQueue(label: "cn.airnan.kymo.network-path"))
|
||||
}
|
||||
|
||||
func snapshot() -> NetworkPathStatus? {
|
||||
lock.lock()
|
||||
defer { lock.unlock() }
|
||||
return status
|
||||
}
|
||||
|
||||
deinit { monitor.cancel() }
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import Foundation
|
||||
|
||||
/// Uses the System Information report's own maximum-capacity field.
|
||||
/// Slow-changing data is cached independently of the two-second resource samples.
|
||||
actor SystemBatteryHealthMonitor {
|
||||
private var cached: Double?
|
||||
private var nextRead: TimeInterval = 0
|
||||
private var pending: Task<Double?, Never>?
|
||||
|
||||
func sample() async -> Double? {
|
||||
if let pending { return await pending.value }
|
||||
guard ProcessInfo.processInfo.systemUptime >= nextRead else { return cached }
|
||||
let task = Task { await Self.readReport() }
|
||||
pending = task
|
||||
cached = await task.value
|
||||
pending = nil
|
||||
nextRead = ProcessInfo.processInfo.systemUptime + (cached == nil ? 600 : 3600)
|
||||
return cached
|
||||
}
|
||||
|
||||
nonisolated static func parse(_ data: Data) -> Double? {
|
||||
guard let root = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
|
||||
let reports = root["SPPowerDataType"] as? [[String: Any]] else { return nil }
|
||||
for report in reports {
|
||||
guard let health = report["sppower_battery_health_info"] as? [String: Any],
|
||||
let text = health["sppower_battery_health_maximum_capacity"] as? String,
|
||||
text.trimmingCharacters(in: .whitespacesAndNewlines).hasSuffix("%"),
|
||||
let percent = Double(text.trimmingCharacters(in: .whitespacesAndNewlines).dropLast().trimmingCharacters(in: .whitespaces)),
|
||||
percent.isFinite, (0...100).contains(percent) else { continue }
|
||||
return percent / 100
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,13 +4,32 @@ import Darwin
|
||||
/// Serial ownership keeps CPU baselines coherent and system calls off MainActor.
|
||||
actor SystemSampler {
|
||||
private var cpu = CPUMonitor()
|
||||
private let batteryHealth = SystemBatteryHealthMonitor()
|
||||
|
||||
func reset() { cpu = CPUMonitor() }
|
||||
private var network = NetworkMonitor()
|
||||
private let networkPath = NetworkPathObserver()
|
||||
private var diskIO = DiskIOMonitor()
|
||||
private var volumes: [VolumeMetrics]?
|
||||
private var volumeSampleTime: TimeInterval?
|
||||
|
||||
func sample() -> MetricsSnapshot {
|
||||
func reset() { cpu = CPUMonitor(); network = NetworkMonitor(); diskIO = DiskIOMonitor() }
|
||||
|
||||
func sample() async -> MetricsSnapshot {
|
||||
var result = MetricsSnapshot()
|
||||
result.cpu = cpu.sample()
|
||||
result.memory = MemoryMonitor.sample()
|
||||
result.network = network.sample()
|
||||
result.networkPath = networkPath.snapshot()
|
||||
result.disk = DiskMonitor.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.uptime = ProcessInfo.processInfo.systemUptime
|
||||
var load = [Double](repeating: 0, count: 3)
|
||||
if getloadavg(&load, 3) == 3 { result.load = load }
|
||||
|
||||
Reference in New Issue
Block a user