feat(monitors): 接入统一面板数据与按需进程采样
This commit is contained in:
+10
-5
@@ -39,7 +39,9 @@ Kymo 是一款 macOS 菜单栏常驻的资源监控工具,设计目标为「
|
|||||||
`App` 持有一个 `MetricsStore`(MainActor、`@Observable`),注入菜单栏场景与面板。
|
`App` 持有一个 `MetricsStore`(MainActor、`@Observable`),注入菜单栏场景与面板。
|
||||||
仓库创建唯一 Task,调用 `SystemSampler` actor,在后台串行读取 `CPUMonitor`、
|
仓库创建唯一 Task,调用 `SystemSampler` actor,在后台串行读取 `CPUMonitor`、
|
||||||
`MemoryMonitor` 与 `getloadavg`,返回 Sendable `MetricsSnapshot`,再回 MainActor 整体发布。
|
`MemoryMonitor` 与 `getloadavg`,返回 Sendable `MetricsSnapshot`,再回 MainActor 整体发布。
|
||||||
默认每次采样完成后等待 2s,不会重叠采样;当前刷新间隔尚未接入设置。
|
默认每次采样完成后等待 2s,不会重叠快速采样;当前刷新间隔尚未接入设置。
|
||||||
|
SystemSampler 统一协调 SMART、电池健康、卷列表与进程的单次在途任务,快速链路不等待其完成;SMART/电池健康结果带时间戳,成功一小时、失败十分钟后重试,卷列表约三十秒刷新。任务完成清空在途槽;取消/隐藏不释放尚未结束的同步查询槽,不无限补发。
|
||||||
|
进程通过 sysctl 枚举并逐项读取 proc_taskallinfo/proc_pidpath;PID + 启动秒/微秒为身份,读取前后核对枚举身份,未知字段独立降级。CPU 计时为纳秒差分,单核 100%,RSS 不等同活动监视器内存。只在面板可见且未暂停时采样;关闭清空快照、监控器基线与缓存,迟到结果按代次拒绝,重新打开重建基线;其他用户受限行保留覆盖说明。Store 另以发布/可见性代次防止暂停或快速开关后发布旧结果。
|
||||||
|
|
||||||
菜单栏使用 `MenuBarExtra("Kymo", image: "BrandMark")`,仅显示模板品牌图标,点击展开监控面板。2026-11-02 用户确认取消动态数值、指标组合配置及宽度收缩需求,标题固定为品牌名,不读取采样快照。此前 macOS 27 自定义 label 不可见的调查保留在阶段记录中,不再作为待恢复动态文本的问题。
|
菜单栏使用 `MenuBarExtra("Kymo", image: "BrandMark")`,仅显示模板品牌图标,点击展开监控面板。2026-11-02 用户确认取消动态数值、指标组合配置及宽度收缩需求,标题固定为品牌名,不读取采样快照。此前 macOS 27 自定义 label 不可见的调查保留在阶段记录中,不再作为待恢复动态文本的问题。
|
||||||
|
|
||||||
@@ -48,14 +50,13 @@ CPU 计数按 UInt32 回绕计算,`host_processor_info` 分配的缓冲区每
|
|||||||
内存已用口径为 `max(internal - purgeable, 0) + wired + compressor`,上限为物理内存。
|
内存已用口径为 `max(internal - purgeable, 0) + wired + compressor`,上限为物理内存。
|
||||||
Swap 和压力通过 sysctl 分别读取,失败仅令对应子项为空;压力不由占用率推算。
|
Swap 和压力通过 sysctl 分别读取,失败仅令对应子项为空;压力不由占用率推算。
|
||||||
|
|
||||||
GPU 的 IOReport spike 能枚举本机通道,但订阅返回空,当前快照 GPU 为 nil:
|
GPU 通过 IOAccelerator 的 PerformanceStatistics / Device Utilization % 读取单设备总体利用率;有限值须落在 0–100 才归一化,缺失/多设备降级未知。gpu-core-count 只代表拓扑,不代表可读每核利用率;当前没有独立每核数据。旧 IOReport 订阅失败记录保留,不能据此否定已验证的注册表总体路径。
|
||||||
正式面板保留 GPU 行与不可用详情。CPU、内存不受影响。
|
|
||||||
网络、存储、电池及磁盘 SMART 已接入采样与面板;磁盘 SMART 通过签名的辅助 XPC 在
|
网络、存储、电池及磁盘 SMART 已接入采样与面板;磁盘 SMART 通过签名的辅助 XPC 在
|
||||||
应用沙盒外读取,失败时显示 `--`。
|
应用沙盒外读取,失败时显示 `--`。
|
||||||
|
|
||||||
### 面板、历史与外观
|
### 面板、历史与外观
|
||||||
|
|
||||||
- Store 在每次发布时向 `MetricHistory` 追加一项,最多保留 60 个样本(默认间隔约 2 分钟);缺失值保留为空,在趋势图中断开,不伪造为零。暂停不追加历史,恢复保留历史并重新建立 CPU 基线。
|
- Store 在每次发布时向 `MetricHistory` 追加一项,最多保留 60 个样本,包含上/下行和设备读/写;分接口历史按索引/名称有界保存,接口消失清理(跨度由真实时间戳确定);缺失值保留为空,在趋势图中断开,不伪造为零。暂停不追加历史,恢复保留历史并重新建立 CPU 基线。
|
||||||
- `MiniTrendChart` 只接收历史值与颜色,使用 SwiftUI Canvas 绘制圆角平滑曲线,无独立计时器。
|
- `MiniTrendChart` 只接收历史值与颜色,使用 SwiftUI Canvas 绘制圆角平滑曲线,无独立计时器。
|
||||||
- `MetricRow` 接收标题、数值、历史与详情内容;鼠标进入 150ms 后通过 `HoverDetailPresenter` 在独立非激活 NSPanel 中呈现详情,主面板不改变尺寸。详情窗口作为主窗口的 child,默认右侧、空间不足向左,并约束在 screen.visibleFrame 内。鼠标可从指标行移入详情,离开两者有 120ms 跨窗口缓冲后收起;主面板隐藏/关闭或视图拆卸时清理子窗口与观察器。按钮保留键盘与 VoiceOver 入口,不提供移出后点击固定。
|
- `MetricRow` 接收标题、数值、历史与详情内容;鼠标进入 150ms 后通过 `HoverDetailPresenter` 在独立非激活 NSPanel 中呈现详情,主面板不改变尺寸。详情窗口作为主窗口的 child,默认右侧、空间不足向左,并约束在 screen.visibleFrame 内。鼠标可从指标行移入详情,离开两者有 120ms 跨窗口缓冲后收起;主面板隐藏/关闭或视图拆卸时清理子窗口与观察器。按钮保留键盘与 VoiceOver 入口,不提供移出后点击固定。
|
||||||
- 面板宽 320pt,当前包含 CPU / GPU / 内存、负载与开机小时数;CPU 详情含用户/系统与每核热条,内存详情含分类/Swap/压力。网络、存储、电池及各自趋势和详情已接入。
|
- 面板宽 320pt,当前包含 CPU / GPU / 内存、负载与开机小时数;CPU 详情含用户/系统与每核热条,内存详情含分类/Swap/压力。网络、存储、电池及各自趋势和详情已接入。
|
||||||
@@ -171,4 +172,8 @@ Debug 清理构建通过。macOS 27 独立构建副本实测菜单栏显示 `Bra
|
|||||||
|
|
||||||
### 统一面板 P0 探针(已实现)
|
### 统一面板 P0 探针(已实现)
|
||||||
|
|
||||||
SystemSampler 在首次采样前仅当 `KYMO_PANEL_PROBE=1` 执行一次 PanelCapabilityProbe;探针通过 sysctl/proc、getifaddrs、IORegistry 记录覆盖计数、错误码、GPU 原始统计和地址族数量,不输出路径/IP 原文。开启时另输出采样耗时;普通运行不执行系统探测或诊断输出。进程/GPU 尚未接入正式快照;实测边界见 [统一面板验证](unified-panel-validation.md)。
|
SystemSampler 在首次采样前仅当 `KYMO_PANEL_PROBE=1` 执行一次 PanelCapabilityProbe;探针通过 sysctl/proc、getifaddrs、IORegistry 记录覆盖计数、错误码、GPU 原始统计和地址族数量,不输出路径/IP 原文。开启时另输出采样耗时;普通运行不执行系统探测或诊断输出。进程/GPU 已接入正式快照;实测边界见 [统一面板验证](unified-panel-validation.md)。
|
||||||
|
|
||||||
|
### 网络元数据与电池状态(已实现)
|
||||||
|
|
||||||
|
NET_RT_IFLIST2 吞吐枚举活动非 loopback 接口;总体只汇总活动 en 接口,VPN 等接口可独立查看但不计总体。getifaddrs 提供索引和本机 IPv4/IPv6,地址/活动状态改变、计数回退均重新建立速率基线;缺失不作为零。接口历史与总体历史分离,不请求公网地址。电池不存在与系统电源读取失败采用独立状态;健康查询异步完成后在下一次快照发布。
|
||||||
|
|||||||
@@ -19,3 +19,11 @@
|
|||||||
Debug 构建通过;默认执行沙盒阻止 Swift 宏插件,审批后构建成功,应用沙盒始终开启。现有 SamplingChecks 通过 CPU 差分、真实 CPU/内存/负载、历史边界、暂停冻结与恢复基线检查。无 Xcode 测试 Target,未执行 xcodebuild test。
|
Debug 构建通过;默认执行沙盒阻止 Swift 宏插件,审批后构建成功,应用沙盒始终开启。现有 SamplingChecks 通过 CPU 差分、真实 CPU/内存/负载、历史边界、暂停冻结与恢复基线检查。无 Xcode 测试 Target,未执行 xcodebuild test。
|
||||||
|
|
||||||
P0 不包含 UI、可控 GPU 负载关联、进程 CPU 差分或最坏延迟测量;后续阶段继续验证。未改变现有正式面板;长期 CPU、内存和能耗未验收。
|
P0 不包含 UI、可控 GPU 负载关联、进程 CPU 差分或最坏延迟测量;后续阶段继续验证。未改变现有正式面板;长期 CPU、内存和能耗未验收。
|
||||||
|
|
||||||
|
## P2:数据与调度首版
|
||||||
|
|
||||||
|
进程使用 sysctl 枚举、proc 计时/RSS/线程/路径,首帧未知、身份二次核对和退出降级;GPU 接入总体和拓扑;网络增加接口索引、本机地址、独立双向历史及总体防 VPN 双计。基础采样不再等待 SMART、电池健康、卷列表或进程查询,全部由同一协调器按需发起、各限一项在途,无独立轮询时钟。关闭/暂停清除进程基线,代次校验拒绝迟到结果。
|
||||||
|
|
||||||
|
UnifiedPanelChecks 通过:单核 >100% 差分、首帧/计数回退/零时间、真实进程首帧与后续 CPU、GPU 无穷/NaN/越界、VPN 不计总体、接口历史 60 点上限/消失清理、可见/隐藏/重开基线。此检查是独立程序,不替代真实窗口可见性事件和交互验证。完整 GPU 负载关联、低频查询最坏耗时、长期资源与跨机型仍待验证。
|
||||||
|
|
||||||
|
回归发现旧 SamplingChecks 把空接口列表期望为 0;已按新方案改为未知(无符合口径的活动接口不代表测得零速率),其他首帧、真实零和计数差分语义保持。无启动标识的进程每帧使用临时身份且不延续 CPU 差分,防止 PID 复用继承选中项。
|
||||||
|
|||||||
@@ -8,18 +8,36 @@ nonisolated struct TrendSample: Sendable {
|
|||||||
var download: Double?
|
var download: Double?
|
||||||
var disk: Double?
|
var disk: Double?
|
||||||
var battery: Double?
|
var battery: Double?
|
||||||
|
var upload: Double?
|
||||||
|
var read: Double?
|
||||||
|
var write: Double?
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Bounded sampling history; no timer or UI visibility dependence.
|
/// Bounded sampling history; no timer or UI visibility dependence.
|
||||||
nonisolated struct MetricHistory: Sendable {
|
nonisolated struct MetricHistory: Sendable {
|
||||||
static let capacity = 60
|
static let capacity = 60
|
||||||
private(set) var samples: [TrendSample] = []
|
private(set) var samples: [TrendSample] = []
|
||||||
|
private(set) var interfaces: [String: [InterfaceTrendSample]] = [:]
|
||||||
|
|
||||||
mutating func append(_ snapshot: MetricsSnapshot) {
|
mutating func append(_ snapshot: MetricsSnapshot) {
|
||||||
samples.append(TrendSample(date: snapshot.date, cpu: snapshot.cpu?.usage,
|
samples.append(TrendSample(date: snapshot.date, cpu: snapshot.cpu?.usage,
|
||||||
gpu: snapshot.gpuUsage, memory: snapshot.memory?.usage,
|
gpu: snapshot.gpuUsage, memory: snapshot.memory?.usage,
|
||||||
download: snapshot.downloadRate, disk: snapshot.disk?.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) }
|
if samples.count > Self.capacity { samples.removeFirst(samples.count - Self.capacity) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
nonisolated struct InterfaceTrendSample: Sendable {
|
||||||
|
let date: Date
|
||||||
|
let download: Double?
|
||||||
|
let upload: Double?
|
||||||
|
}
|
||||||
|
|||||||
@@ -30,15 +30,32 @@ nonisolated struct MetricsSnapshot: Sendable {
|
|||||||
var battery: BatteryMetrics?
|
var battery: BatteryMetrics?
|
||||||
var load: [Double] = []
|
var load: [Double] = []
|
||||||
var uptime: TimeInterval = 0
|
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
|
var gpuUsage: Double? = nil
|
||||||
}
|
}
|
||||||
|
|
||||||
nonisolated extension MetricsSnapshot {
|
nonisolated extension MetricsSnapshot {
|
||||||
var downloadRate: Double? {
|
var downloadRate: Double? {
|
||||||
guard let network else { return nil }
|
guard let network else { return nil }
|
||||||
let rates = network.compactMap(\.download)
|
let included = network.filter { $0.isIncludedInTotal }
|
||||||
guard rates.count == network.count else { return nil }
|
guard !included.isEmpty else { return nil }
|
||||||
|
let rates = included.compactMap(\.download)
|
||||||
|
guard rates.count == included.count else { return nil }
|
||||||
return rates.reduce(0, +)
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -24,6 +24,16 @@ nonisolated enum BatteryMonitor {
|
|||||||
return max(1, Int((systemSeconds / 60).rounded(.up)))
|
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? {
|
static func sample() -> BatteryMetrics? {
|
||||||
guard let info = IOPSCopyPowerSourcesInfo()?.takeRetainedValue(),
|
guard let info = IOPSCopyPowerSourcesInfo()?.takeRetainedValue(),
|
||||||
let sources = IOPSCopyPowerSourcesList(info)?.takeRetainedValue() as? [CFTypeRef] else { return nil }
|
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 sent: UInt64
|
||||||
let download: Double?
|
let download: Double?
|
||||||
let upload: 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 {
|
nonisolated struct NetworkMonitor {
|
||||||
private var previous: [String: (UInt64, UInt64)] = [:]
|
private var previous: [String: (UInt64, UInt64)] = [:]
|
||||||
private var timestamp: TimeInterval?
|
private var timestamp: TimeInterval?
|
||||||
|
private var identities: [String: String] = [:]
|
||||||
|
|
||||||
static func rate(current: UInt64, previous: UInt64?, elapsed: TimeInterval) -> Double? {
|
static func rate(current: UInt64, previous: UInt64?, elapsed: TimeInterval) -> Double? {
|
||||||
guard let previous, elapsed.isFinite, elapsed > 0, current >= previous else { return nil }
|
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 }
|
guard let counters = Self.counters() else { previous = [:]; timestamp = nil; return nil }
|
||||||
let now = ProcessInfo.processInfo.systemUptime
|
let now = ProcessInfo.processInfo.systemUptime
|
||||||
let elapsed = timestamp.map { now - $0 } ?? 0
|
let elapsed = timestamp.map { now - $0 } ?? 0
|
||||||
|
let metadata = Self.interfaces()
|
||||||
let result = counters.keys.sorted().map { name in
|
let result = counters.keys.sorted().map { name in
|
||||||
let current = counters[name]!
|
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,
|
return NetworkInterfaceMetrics(name: name, received: current.0, sent: current.1,
|
||||||
download: Self.rate(current: current.0, previous: previous[name]?.0, elapsed: elapsed),
|
download: Self.rate(current: current.0, previous: old?.0, elapsed: elapsed),
|
||||||
upload: Self.rate(current: current.1, previous: previous[name]?.1, 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
|
previous = counters
|
||||||
timestamp = now
|
timestamp = now
|
||||||
return result
|
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.
|
/// NET_RT_IFLIST2 exposes 64-bit counters, avoiding getifaddrs' 4 GB wrap.
|
||||||
private static func counters() -> [String: (UInt64, UInt64)]? {
|
private static func counters() -> [String: (UInt64, UInt64)]? {
|
||||||
var mib: [Int32] = [CTL_NET, PF_ROUTE, 0, 0, NET_RT_IFLIST2, 0]
|
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))
|
var name = [CChar](repeating: 0, count: Int(IFNAMSIZ))
|
||||||
if if_indextoname(UInt32(message.ifm_index), &name) != nil {
|
if if_indextoname(UInt32(message.ifm_index), &name) != nil {
|
||||||
let identifier = String(cString: name)
|
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)
|
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 Foundation
|
||||||
import Darwin
|
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 {
|
actor SystemSampler {
|
||||||
private var cpu = CPUMonitor()
|
private var cpu = CPUMonitor()
|
||||||
private var didProbe = false
|
private var didProbe = false
|
||||||
private let diskHealth = DiskHealthMonitor()
|
private let diskHealth = DiskHealthMonitor()
|
||||||
private let batteryHealth = SystemBatteryHealthMonitor()
|
private let batteryHealth = SystemBatteryHealthMonitor()
|
||||||
|
|
||||||
private var network = NetworkMonitor()
|
private var network = NetworkMonitor()
|
||||||
private let networkPath = NetworkPathObserver()
|
private let networkPath = NetworkPathObserver()
|
||||||
private var diskIO = DiskIOMonitor()
|
private var diskIO = DiskIOMonitor()
|
||||||
private var volumes: [VolumeMetrics]?
|
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 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 {
|
if !didProbe {
|
||||||
didProbe = true
|
didProbe = true
|
||||||
if ProcessInfo.processInfo.environment["KYMO_PANEL_PROBE"] == "1" {
|
if ProcessInfo.processInfo.environment["KYMO_PANEL_PROBE"] == "1" { PanelCapabilityProbe.run() }
|
||||||
PanelCapabilityProbe.run()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
let sampleStart = ProcessInfo.processInfo.systemUptime
|
let start = ProcessInfo.processInfo.systemUptime
|
||||||
var result = MetricsSnapshot()
|
var result = MetricsSnapshot()
|
||||||
result.cpu = cpu.sample()
|
result.cpu = cpu.sample()
|
||||||
result.memory = MemoryMonitor.sample()
|
result.memory = MemoryMonitor.sample()
|
||||||
result.network = network.sample()
|
result.network = network.sample()
|
||||||
result.networkPath = networkPath.snapshot()
|
result.networkPath = networkPath.snapshot()
|
||||||
result.disk = DiskMonitor.sample()
|
result.disk = DiskMonitor.sample()
|
||||||
result.diskHealth = await diskHealth.sample()
|
|
||||||
result.diskIO = diskIO.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()
|
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
|
result.uptime = ProcessInfo.processInfo.systemUptime
|
||||||
var load = [Double](repeating: 0, count: 3)
|
var load = [Double](repeating: 0, count: 3)
|
||||||
if getloadavg(&load, 3) == 3 { result.load = load }
|
if getloadavg(&load, 3) == 3 { result.load = load }
|
||||||
if ProcessInfo.processInfo.environment["KYMO_PANEL_PROBE"] == "1" {
|
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))
|
try? FileHandle.standardOutput.write(contentsOf: Data(line.utf8))
|
||||||
}
|
}
|
||||||
return result
|
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
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,6 +6,9 @@ final class MetricsStore {
|
|||||||
private(set) var snapshot = MetricsSnapshot()
|
private(set) var snapshot = MetricsSnapshot()
|
||||||
private(set) var history = MetricHistory()
|
private(set) var history = MetricHistory()
|
||||||
private(set) var isPaused = false
|
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 var task: Task<Void, Never>?
|
||||||
@ObservationIgnored private let sampler = SystemSampler()
|
@ObservationIgnored private let sampler = SystemSampler()
|
||||||
|
|
||||||
@@ -14,11 +17,16 @@ final class MetricsStore {
|
|||||||
func start() {
|
func start() {
|
||||||
guard task == nil else { return }
|
guard task == nil else { return }
|
||||||
isPaused = false
|
isPaused = false
|
||||||
|
generation += 1
|
||||||
|
let currentGeneration = generation
|
||||||
task = Task { [weak self, sampler] in
|
task = Task { [weak self, sampler] in
|
||||||
await sampler.reset()
|
await sampler.reset()
|
||||||
|
await sampler.setProcessVisible(self?.isPanelVisible == true)
|
||||||
while !Task.isCancelled {
|
while !Task.isCancelled {
|
||||||
let next = await sampler.sample()
|
let visibleGeneration = self?.visibilityGeneration
|
||||||
guard !Task.isCancelled else { return }
|
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?.snapshot = next
|
||||||
self?.history.append(next)
|
self?.history.append(next)
|
||||||
SamplingDiagnostics.record(next)
|
SamplingDiagnostics.record(next)
|
||||||
@@ -31,12 +39,23 @@ final class MetricsStore {
|
|||||||
func togglePause() {
|
func togglePause() {
|
||||||
if isPaused { start() }
|
if isPaused { start() }
|
||||||
else {
|
else {
|
||||||
|
generation += 1
|
||||||
task?.cancel()
|
task?.cancel()
|
||||||
task = nil
|
task = nil
|
||||||
|
Task { await sampler.setProcessVisible(false) }
|
||||||
isPaused = true
|
isPaused = true
|
||||||
SamplingDiagnostics.record(snapshot, event: "pause")
|
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() }
|
deinit { task?.cancel() }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,6 +14,10 @@ nonisolated enum SamplingDiagnostics {
|
|||||||
]
|
]
|
||||||
payload["cpu"] = snapshot.cpu?.usage
|
payload["cpu"] = snapshot.cpu?.usage
|
||||||
payload["cores"] = snapshot.cpu?.cores.count
|
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["memoryUsed"] = snapshot.memory?.used
|
||||||
payload["memoryTotal"] = snapshot.memory?.total
|
payload["memoryTotal"] = snapshot.memory?.total
|
||||||
payload["swapUsed"] = snapshot.memory?.swapUsed
|
payload["swapUsed"] = snapshot.memory?.swapUsed
|
||||||
|
|||||||
@@ -35,7 +35,8 @@ import Foundation
|
|||||||
extendedHistory.append(extended)
|
extendedHistory.append(extended)
|
||||||
precondition(extendedHistory.samples.last?.download == nil)
|
precondition(extendedHistory.samples.last?.download == nil)
|
||||||
extended.network = []
|
extended.network = []
|
||||||
precondition(extended.downloadRate == 0)
|
// No eligible active interfaces has no measured rate; do not manufacture a zero.
|
||||||
|
precondition(extended.downloadRate == nil)
|
||||||
extended.network = nil
|
extended.network = nil
|
||||||
precondition(extended.downloadRate == nil)
|
precondition(extended.downloadRate == nil)
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,42 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
@main struct UnifiedPanelChecks {
|
||||||
|
@MainActor static func main() async {
|
||||||
|
precondition(ProcessMonitor.cpu(current: 4_000_000_000, previous: 1_000_000_000, elapsed: 1) == 3)
|
||||||
|
precondition(ProcessMonitor.cpu(current: 0, previous: nil, elapsed: 1) == nil)
|
||||||
|
precondition(ProcessMonitor.cpu(current: 1, previous: 2, elapsed: 1) == nil)
|
||||||
|
precondition(ProcessMonitor.cpu(current: 1, previous: 0, elapsed: 0) == nil)
|
||||||
|
precondition(GPUMonitor.normalized(53) == 0.53)
|
||||||
|
precondition(GPUMonitor.normalized(101) == nil && GPUMonitor.normalized(.nan) == nil)
|
||||||
|
var snapshot = MetricsSnapshot()
|
||||||
|
snapshot.network = [NetworkInterfaceMetrics(name: "en0", received: 1, sent: 1, download: 12, upload: 8),
|
||||||
|
NetworkInterfaceMetrics(name: "utun0", received: 1, sent: 1, download: 99, upload: 99)]
|
||||||
|
precondition(snapshot.downloadRate == 12 && snapshot.uploadRate == 8)
|
||||||
|
var history = MetricHistory()
|
||||||
|
for _ in 0..<65 { history.append(snapshot) }
|
||||||
|
precondition(history.samples.count == 60 && history.interfaces["0:en0"]?.count == 60)
|
||||||
|
snapshot.network = []
|
||||||
|
history.append(snapshot)
|
||||||
|
precondition(history.interfaces.isEmpty && snapshot.downloadRate == nil)
|
||||||
|
var monitor = ProcessMonitor()
|
||||||
|
let first = monitor.sample()
|
||||||
|
precondition(!first.failed && first.rows.contains { $0.id.pid == getpid() })
|
||||||
|
precondition(first.rows.allSatisfy { $0.cpu == nil })
|
||||||
|
try? await Task.sleep(for: .milliseconds(100))
|
||||||
|
let second = monitor.sample()
|
||||||
|
precondition(second.rows.first { $0.id.pid == getpid() }?.cpu != nil)
|
||||||
|
let sampler = SystemSampler()
|
||||||
|
await sampler.setProcessVisible(true)
|
||||||
|
_ = await sampler.sample()
|
||||||
|
try? await Task.sleep(for: .milliseconds(500))
|
||||||
|
let visible = await sampler.sample()
|
||||||
|
precondition(visible.processes != nil)
|
||||||
|
await sampler.setProcessVisible(false)
|
||||||
|
let hidden = await sampler.sample()
|
||||||
|
precondition(hidden.processes == nil)
|
||||||
|
await sampler.setProcessVisible(true)
|
||||||
|
let reopened = await sampler.sample()
|
||||||
|
precondition(reopened.processes == nil)
|
||||||
|
print("PASS: process CPU boundaries/live baseline, GPU range, VPN total exclusion, bounded interface history, visibility reset")
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user