Files
Kymo/kymo/Core/Monitors/SystemSampler.swift
T

53 lines
2.1 KiB
Swift

import Foundation
import Darwin
/// Serial ownership keeps CPU baselines coherent and system calls off MainActor.
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?
func reset() { cpu = CPUMonitor(); network = NetworkMonitor(); diskIO = DiskIOMonitor() }
func sample() async -> MetricsSnapshot {
if !didProbe {
didProbe = true
if ProcessInfo.processInfo.environment["KYMO_PANEL_PROBE"] == "1" {
PanelCapabilityProbe.run()
}
}
let sampleStart = 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.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"
try? FileHandle.standardOutput.write(contentsOf: Data(line.utf8))
}
return result
}
}