feat(storage): 新增只读 SMART 辅助服务与寿命通电详情
This commit is contained in:
@@ -0,0 +1,7 @@
|
||||
import Foundation
|
||||
|
||||
nonisolated struct DiskHealthMetrics: Sendable {
|
||||
/// NVMe vendor endurance estimate, not a probability of remaining failure-free.
|
||||
let remainingLife: Double?
|
||||
let powerOnHours: UInt64?
|
||||
}
|
||||
@@ -24,6 +24,7 @@ nonisolated struct MetricsSnapshot: Sendable {
|
||||
var network: [NetworkInterfaceMetrics]?
|
||||
var networkPath: NetworkPathStatus?
|
||||
var disk: DiskMetrics?
|
||||
var diskHealth: DiskHealthMetrics?
|
||||
var diskIO: DiskIOMetrics?
|
||||
var volumes: [VolumeMetrics]?
|
||||
var battery: BatteryMetrics?
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import Foundation
|
||||
|
||||
/// SMART belongs to the physical storage backing the home volume, not each APFS volume.
|
||||
actor DiskHealthMonitor {
|
||||
private var cached: DiskHealthMetrics?
|
||||
private var nextRead: TimeInterval = 0
|
||||
private var pending: Task<DiskHealthMetrics?, Never>?
|
||||
|
||||
func sample() async -> DiskHealthMetrics? {
|
||||
if let pending { return await pending.value }
|
||||
guard ProcessInfo.processInfo.systemUptime >= nextRead else { return cached }
|
||||
let task = Task { await SMARTServiceClient.read() }
|
||||
pending = task
|
||||
cached = await task.value
|
||||
pending = nil
|
||||
nextRead = ProcessInfo.processInfo.systemUptime + (cached == nil ? 600 : 3600)
|
||||
return cached
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import Foundation
|
||||
|
||||
nonisolated enum DiskHealthReport {
|
||||
static func parse(_ data: Data) -> DiskHealthMetrics? {
|
||||
guard let root = try? PropertyListSerialization.propertyList(from: data, format: nil) as? [String: Any],
|
||||
let smart = root["SMARTDeviceSpecificKeysMayVaryNotGuaranteed"] as? [String: Any] else { return nil }
|
||||
// Multiple physical stores cannot be represented as one device's lifetime.
|
||||
if let stores = root["APFSPhysicalStores"] as? [Any], stores.count != 1 { return nil }
|
||||
func integer(_ key: String) -> UInt64? {
|
||||
guard let value = smart[key] as? NSNumber,
|
||||
CFGetTypeID(value) != CFBooleanGetTypeID() else { return nil }
|
||||
return UInt64(value.stringValue)
|
||||
}
|
||||
let used = integer("PERCENTAGE_USED").flatMap { $0 <= 255 ? $0 : nil }
|
||||
let remaining = used.map { Double(100 - min(100, $0)) / 100 }
|
||||
let hours = integer("POWER_ON_HOURS_1") == 0 ? integer("POWER_ON_HOURS_0") : nil
|
||||
guard remaining != nil || hours != nil else { return nil }
|
||||
return DiskHealthMetrics(remainingLife: remaining, powerOnHours: hours)
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import Darwin
|
||||
/// Serial ownership keeps CPU baselines coherent and system calls off MainActor.
|
||||
actor SystemSampler {
|
||||
private var cpu = CPUMonitor()
|
||||
private let diskHealth = DiskHealthMonitor()
|
||||
private let batteryHealth = SystemBatteryHealthMonitor()
|
||||
|
||||
private var network = NetworkMonitor()
|
||||
@@ -21,6 +22,7 @@ actor SystemSampler {
|
||||
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 {
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
import Foundation
|
||||
import Security
|
||||
|
||||
nonisolated enum CodeIdentity {
|
||||
static func requirement(at url: URL) -> String? {
|
||||
var code: SecStaticCode?
|
||||
guard SecStaticCodeCreateWithPath(url as CFURL, [], &code) == errSecSuccess,
|
||||
let code else { return nil }
|
||||
var requirement: SecRequirement?
|
||||
guard SecCodeCopyDesignatedRequirement(code, [], &requirement) == errSecSuccess,
|
||||
let requirement else { return nil }
|
||||
var text: CFString?
|
||||
guard SecRequirementCopyString(requirement, [], &text) == errSecSuccess else { return nil }
|
||||
return text as String?
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import Foundation
|
||||
|
||||
nonisolated enum SMARTServiceClient {
|
||||
static func read() async -> DiskHealthMetrics? {
|
||||
let url = Bundle.main.bundleURL.appendingPathComponent("Contents/XPCServices/SMARTService.xpc")
|
||||
guard let requirement = CodeIdentity.requirement(at: url) else { return nil }
|
||||
return await withCheckedContinuation { continuation in
|
||||
let connection = NSXPCConnection(serviceName: "cn.airnan.kymo.SMARTService")
|
||||
connection.setCodeSigningRequirement(requirement)
|
||||
connection.remoteObjectInterface = NSXPCInterface(with: SMARTServiceProtocol.self)
|
||||
let reply = Reply(connection: connection, continuation: continuation)
|
||||
connection.invalidationHandler = { reply.finish(nil) }
|
||||
connection.interruptionHandler = { reply.finish(nil) }
|
||||
connection.resume()
|
||||
guard let proxy = connection.remoteObjectProxyWithErrorHandler({ _ in reply.finish(nil) }) as? SMARTServiceProtocol else {
|
||||
reply.finish(nil); return
|
||||
}
|
||||
proxy.readSMART { remaining, hours in
|
||||
let life = remaining?.doubleValue
|
||||
let validLife = life.flatMap { $0.isFinite && (0...1).contains($0) ? $0 : nil }
|
||||
let validHours = hours.flatMap { UInt64($0.stringValue) }
|
||||
reply.finish(validLife != nil || validHours != nil ? DiskHealthMetrics(remainingLife: validLife, powerOnHours: validHours) : nil)
|
||||
}
|
||||
DispatchQueue.global(qos: .utility).asyncAfter(deadline: .now() + 15) { reply.finish(nil) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Error, interruption, timeout and reply may race; resume exactly once.
|
||||
private final class Reply: @unchecked Sendable {
|
||||
private let lock = NSLock()
|
||||
private var continuation: CheckedContinuation<DiskHealthMetrics?, Never>?
|
||||
private let connection: NSXPCConnection
|
||||
|
||||
init(connection: NSXPCConnection, continuation: CheckedContinuation<DiskHealthMetrics?, Never>) {
|
||||
self.connection = connection
|
||||
self.continuation = continuation
|
||||
}
|
||||
|
||||
func finish(_ value: DiskHealthMetrics?) {
|
||||
lock.lock()
|
||||
let callback = continuation
|
||||
continuation = nil
|
||||
lock.unlock()
|
||||
guard let callback else { return }
|
||||
connection.invalidationHandler = nil
|
||||
connection.interruptionHandler = nil
|
||||
connection.invalidate()
|
||||
callback.resume(returning: value)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import Foundation
|
||||
|
||||
/// Fixed read-only operation: no caller-supplied paths or commands.
|
||||
@objc protocol SMARTServiceProtocol {
|
||||
nonisolated func readSMART(withReply reply: @escaping (NSNumber?, NSNumber?) -> Void)
|
||||
}
|
||||
@@ -21,6 +21,8 @@ nonisolated enum SamplingDiagnostics {
|
||||
payload["networkPath"] = snapshot.networkPath.map { String(describing: $0) }
|
||||
payload["networkDownload"] = snapshot.downloadRate
|
||||
payload["networkInterfaces"] = snapshot.network?.map(\.name)
|
||||
payload["diskRemainingLife"] = snapshot.diskHealth?.remainingLife
|
||||
payload["diskPowerOnHours"] = snapshot.diskHealth?.powerOnHours
|
||||
payload["diskRead"] = snapshot.diskIO?.read
|
||||
payload["diskWrite"] = snapshot.diskIO?.written
|
||||
payload["volumeCount"] = snapshot.volumes?.count
|
||||
|
||||
@@ -55,6 +55,14 @@ struct MenuPanelView: View {
|
||||
Text("disk.homeVolume").foregroundStyle(.secondary)
|
||||
detailLine("disk.total", MetricFormat.bytes(metrics.snapshot.disk?.total))
|
||||
detailLine("memory.available", MetricFormat.bytes(metrics.snapshot.disk?.available))
|
||||
detailLine("disk.remainingLife", MetricFormat.percent(metrics.snapshot.diskHealth?.remainingLife))
|
||||
HStack {
|
||||
Text("disk.powerOnHours").foregroundStyle(.secondary)
|
||||
Spacer()
|
||||
if let hours = metrics.snapshot.diskHealth?.powerOnHours {
|
||||
Text("disk.hours \(hours)").monospacedDigit()
|
||||
} else { Text(verbatim: "--") }
|
||||
}
|
||||
Divider()
|
||||
Text("disk.physicalIO").foregroundStyle(.secondary)
|
||||
detailLine("disk.read", rate(metrics.snapshot.diskIO?.read))
|
||||
|
||||
@@ -1583,6 +1583,72 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"disk.remainingLife": {
|
||||
"localizations": {
|
||||
"en": {
|
||||
"stringUnit": {
|
||||
"state": "translated",
|
||||
"value": "Estimated remaining life"
|
||||
}
|
||||
},
|
||||
"zh-Hans": {
|
||||
"stringUnit": {
|
||||
"state": "translated",
|
||||
"value": "预计剩余寿命"
|
||||
}
|
||||
},
|
||||
"zh-Hant": {
|
||||
"stringUnit": {
|
||||
"state": "translated",
|
||||
"value": "預計剩餘壽命"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"disk.powerOnHours": {
|
||||
"localizations": {
|
||||
"en": {
|
||||
"stringUnit": {
|
||||
"state": "translated",
|
||||
"value": "Power-on time"
|
||||
}
|
||||
},
|
||||
"zh-Hans": {
|
||||
"stringUnit": {
|
||||
"state": "translated",
|
||||
"value": "通电时间"
|
||||
}
|
||||
},
|
||||
"zh-Hant": {
|
||||
"stringUnit": {
|
||||
"state": "translated",
|
||||
"value": "通電時間"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"disk.hours %llu": {
|
||||
"localizations": {
|
||||
"en": {
|
||||
"stringUnit": {
|
||||
"state": "translated",
|
||||
"value": "%llu hours"
|
||||
}
|
||||
},
|
||||
"zh-Hans": {
|
||||
"stringUnit": {
|
||||
"state": "translated",
|
||||
"value": "%llu 小时"
|
||||
}
|
||||
},
|
||||
"zh-Hant": {
|
||||
"stringUnit": {
|
||||
"state": "translated",
|
||||
"value": "%llu 小時"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"version": "1.0"
|
||||
|
||||
Reference in New Issue
Block a user