#26 #28 #56: machine memory pressure, memory and GPU load in /rzb/status and rzb tui
SystemMonitor (Core): memory pressure level (kern.memorystatus_vm_pressure_level), available and compressed memory (host_statistics64), swap (vm.swapusage), process footprint (proc_pid_rusage), GPU utilisation (IOAccelerator PerformanceStatistics, hidden when absent); /proc on Linux. Measured on each status request; /rzb/status gains a system object (explicit nulls). rzb tui: a Machine line on the Dashboard, gpu and pressure (coloured) in the status bar. Tests: Linux 327, Mac 353. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1dea285 parent: 041f8f0 added
Sources/RazorbillCore/System/SystemMonitor.swift +170 -0 | new file mode 100644 | ||
| @@ -0,0 +1,170 @@ | ||
| 1 | +import Foundation | |
| 2 | + | |
| 3 | +#if canImport(Darwin) | |
| 4 | +import Darwin | |
| 5 | +import IOKit | |
| 6 | +#endif | |
| 7 | + | |
| 8 | +/// The machine's state as `GET /rzb/status` reports it (#26, #28). Every measure is optional: | |
| 9 | +/// what the platform cannot give is `nil` (on Linux: the pressure level and the GPU load). | |
| 10 | +/// | |
| 11 | +/// ```swift | |
| 12 | +/// let system = SystemMonitor.measure() | |
| 13 | +/// print(system.pressure ?? "unknown", system.gpuUtilization.map { "\($0)%" } ?? "-") | |
| 14 | +/// ``` | |
| 15 | +public struct SystemSnapshot: Sendable, Equatable { | |
| 16 | + /// Installed memory. | |
| 17 | + public var physicalBytes: Int64 | |
| 18 | + /// `normal`, `warning` or `critical`, as Activity Monitor's memory pressure. | |
| 19 | + public var pressure: String? | |
| 20 | + /// Memory the system can hand out without swapping (free and speculative pages on macOS, | |
| 21 | + /// `MemAvailable` on Linux). | |
| 22 | + public var availableBytes: Int64? | |
| 23 | + /// Memory held compressed (macOS). | |
| 24 | + public var compressedBytes: Int64? | |
| 25 | + /// Swap in use. | |
| 26 | + public var swapUsedBytes: Int64? | |
| 27 | + /// The server process's memory footprint. | |
| 28 | + public var processBytes: Int64? | |
| 29 | + /// GPU utilisation in percent, from IOKit's `IOAccelerator` statistics (macOS). | |
| 30 | + public var gpuUtilization: Int? | |
| 31 | + | |
| 32 | + public init( | |
| 33 | + physicalBytes: Int64, pressure: String? = nil, availableBytes: Int64? = nil, | |
| 34 | + compressedBytes: Int64? = nil, swapUsedBytes: Int64? = nil, processBytes: Int64? = nil, | |
| 35 | + gpuUtilization: Int? = nil | |
| 36 | + ) { | |
| 37 | + self.physicalBytes = physicalBytes | |
| 38 | + self.pressure = pressure | |
| 39 | + self.availableBytes = availableBytes | |
| 40 | + self.compressedBytes = compressedBytes | |
| 41 | + self.swapUsedBytes = swapUsedBytes | |
| 42 | + self.processBytes = processBytes | |
| 43 | + self.gpuUtilization = gpuUtilization | |
| 44 | + } | |
| 45 | +} | |
| 46 | + | |
| 47 | +/// Reads a ``SystemSnapshot``; servers take one so tests can give fixed values. | |
| 48 | +public typealias SystemReporter = @Sendable () -> SystemSnapshot | |
| 49 | + | |
| 50 | +/// Measures the machine. Each read is cheap (a few `sysctl` and one IORegistry walk), so it is done | |
| 51 | +/// on each status request rather than on a timer. | |
| 52 | +public enum SystemMonitor { | |
| 53 | + public static let measure: SystemReporter = { | |
| 54 | + var snapshot = SystemSnapshot(physicalBytes: Int64(ProcessInfo.processInfo.physicalMemory)) | |
| 55 | + #if canImport(Darwin) | |
| 56 | + snapshot.pressure = pressureLevel() | |
| 57 | + if let pages = pageCounts() { | |
| 58 | + snapshot.availableBytes = pages.available | |
| 59 | + snapshot.compressedBytes = pages.compressed | |
| 60 | + } | |
| 61 | + snapshot.swapUsedBytes = swapUsed() | |
| 62 | + snapshot.processBytes = footprint() | |
| 63 | + snapshot.gpuUtilization = gpuUtilization() | |
| 64 | + #elseif os(Linux) | |
| 65 | + let meminfo = (try? String(contentsOfFile: "/proc/meminfo", encoding: .utf8)) ?? "" | |
| 66 | + let fields = parseMeminfo(meminfo) | |
| 67 | + snapshot.availableBytes = fields["MemAvailable"] | |
| 68 | + if let total = fields["SwapTotal"], let free = fields["SwapFree"] { | |
| 69 | + snapshot.swapUsedBytes = total - free | |
| 70 | + } | |
| 71 | + let status = (try? String(contentsOfFile: "/proc/self/status", encoding: .utf8)) ?? "" | |
| 72 | + snapshot.processBytes = parseMeminfo(status)["VmRSS"] | |
| 73 | + #endif | |
| 74 | + return snapshot | |
| 75 | + } | |
| 76 | + | |
| 77 | + /// `/proc/meminfo`-style lines (`MemAvailable: 123456 kB`) as bytes, by name. | |
| 78 | + public static func parseMeminfo(_ text: String) -> [String: Int64] { | |
| 79 | + var fields: [String: Int64] = [:] | |
| 80 | + for line in text.split(separator: "\n") { | |
| 81 | + let parts = line.split(whereSeparator: { $0 == ":" || $0.isWhitespace }) | |
| 82 | + guard parts.count >= 2, let value = Int64(parts[1]) else { continue } | |
| 83 | + let kilobytes = parts.count >= 3 && parts[2] == "kB" | |
| 84 | + fields[String(parts[0])] = kilobytes ? value * 1024 : value | |
| 85 | + } | |
| 86 | + return fields | |
| 87 | + } | |
| 88 | + | |
| 89 | + #if canImport(Darwin) | |
| 90 | + /// `kern.memorystatus_vm_pressure_level`: 1 normal, 2 warning, 4 critical. | |
| 91 | + static func pressureLevel() -> String? { | |
| 92 | + var level: Int32 = 0 | |
| 93 | + var size = MemoryLayout<Int32>.size | |
| 94 | + guard sysctlbyname("kern.memorystatus_vm_pressure_level", &level, &size, nil, 0) == 0 | |
| 95 | + else { return nil } | |
| 96 | + switch level { | |
| 97 | + case 1: return "normal" | |
| 98 | + case 2: return "warning" | |
| 99 | + case 4: return "critical" | |
| 100 | + default: return nil | |
| 101 | + } | |
| 102 | + } | |
| 103 | + | |
| 104 | + /// Free + speculative pages, and compressed pages, in bytes (`host_statistics64`). | |
| 105 | + static func pageCounts() -> (available: Int64, compressed: Int64)? { | |
| 106 | + var statistics = vm_statistics64() | |
| 107 | + var count = mach_msg_type_number_t( | |
| 108 | + MemoryLayout<vm_statistics64>.size / MemoryLayout<integer_t>.size) | |
| 109 | + let result = withUnsafeMutablePointer(to: &statistics) { pointer in | |
| 110 | + pointer.withMemoryRebound(to: integer_t.self, capacity: Int(count)) { | |
| 111 | + host_statistics64(mach_host_self(), HOST_VM_INFO64, $0, &count) | |
| 112 | + } | |
| 113 | + } | |
| 114 | + guard result == KERN_SUCCESS, let page = sysctlInt64("hw.pagesize") else { return nil } | |
| 115 | + let available = Int64(statistics.free_count) + Int64(statistics.speculative_count) | |
| 116 | + return (available * page, Int64(statistics.compressor_page_count) * page) | |
| 117 | + } | |
| 118 | + | |
| 119 | + /// `vm.swapusage`. | |
| 120 | + static func swapUsed() -> Int64? { | |
| 121 | + var usage = xsw_usage() | |
| 122 | + var size = MemoryLayout<xsw_usage>.size | |
| 123 | + guard sysctlbyname("vm.swapusage", &usage, &size, nil, 0) == 0 else { return nil } | |
| 124 | + return Int64(usage.xsu_used) | |
| 125 | + } | |
| 126 | + | |
| 127 | + /// The process's physical footprint, as Activity Monitor's Memory column. | |
| 128 | + static func footprint() -> Int64? { | |
| 129 | + var info = rusage_info_v4() | |
| 130 | + let result = withUnsafeMutablePointer(to: &info) { pointer in | |
| 131 | + pointer.withMemoryRebound(to: rusage_info_t?.self, capacity: 1) { | |
| 132 | + proc_pid_rusage(getpid(), RUSAGE_INFO_V4, $0) | |
| 133 | + } | |
| 134 | + } | |
| 135 | + return result == 0 ? Int64(info.ri_phys_footprint) : nil | |
| 136 | + } | |
| 137 | + | |
| 138 | + /// The highest `Device Utilization %` among the `IOAccelerator` services; `nil` when no | |
| 139 | + /// service publishes it (the key is undocumented and may change). | |
| 140 | + static func gpuUtilization() -> Int? { | |
| 141 | + var iterator: io_iterator_t = 0 | |
| 142 | + guard | |
| 143 | + IOServiceGetMatchingServices( | |
| 144 | + kIOMainPortDefault, IOServiceMatching("IOAccelerator"), &iterator) == KERN_SUCCESS | |
| 145 | + else { return nil } | |
| 146 | + defer { IOObjectRelease(iterator) } | |
| 147 | + var highest: Int? | |
| 148 | + var service = IOIteratorNext(iterator) | |
| 149 | + while service != 0 { | |
| 150 | + if let value = deviceUtilization(of: service) { highest = max(highest ?? 0, value) } | |
| 151 | + IOObjectRelease(service) | |
| 152 | + service = IOIteratorNext(iterator) | |
| 153 | + } | |
| 154 | + return highest | |
| 155 | + } | |
| 156 | + | |
| 157 | + private static func deviceUtilization(of service: io_object_t) -> Int? { | |
| 158 | + let property = IORegistryEntryCreateCFProperty( | |
| 159 | + service, "PerformanceStatistics" as CFString, kCFAllocatorDefault, 0) | |
| 160 | + guard let statistics = property?.takeRetainedValue() as? [String: Any] else { return nil } | |
| 161 | + return (statistics["Device Utilization %"] as? NSNumber)?.intValue | |
| 162 | + } | |
| 163 | + | |
| 164 | + private static func sysctlInt64(_ name: String) -> Int64? { | |
| 165 | + var value: Int64 = 0 | |
| 166 | + var size = MemoryLayout<Int64>.size | |
| 167 | + return sysctlbyname(name, &value, &size, nil, 0) == 0 ? value : nil | |
| 168 | + } | |
| 169 | + #endif | |
| 170 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,170 @@ | |||
| 1 | +import Foundation | ||
| 2 | + | ||
| 3 | +#if canImport(Darwin) | ||
| 4 | +import Darwin | ||
| 5 | +import IOKit | ||
| 6 | +#endif | ||
| 7 | + | ||
| 8 | +/// The machine's state as `GET /rzb/status` reports it (#26, #28). Every measure is optional: | ||
| 9 | +/// what the platform cannot give is `nil` (on Linux: the pressure level and the GPU load). | ||
| 10 | +/// | ||
| 11 | +/// ```swift | ||
| 12 | +/// let system = SystemMonitor.measure() | ||
| 13 | +/// print(system.pressure ?? "unknown", system.gpuUtilization.map { "\($0)%" } ?? "-") | ||
| 14 | +/// ``` | ||
| 15 | +public struct SystemSnapshot: Sendable, Equatable { | ||
| 16 | + /// Installed memory. | ||
| 17 | + public var physicalBytes: Int64 | ||
| 18 | + /// `normal`, `warning` or `critical`, as Activity Monitor's memory pressure. | ||
| 19 | + public var pressure: String? | ||
| 20 | + /// Memory the system can hand out without swapping (free and speculative pages on macOS, | ||
| 21 | + /// `MemAvailable` on Linux). | ||
| 22 | + public var availableBytes: Int64? | ||
| 23 | + /// Memory held compressed (macOS). | ||
| 24 | + public var compressedBytes: Int64? | ||
| 25 | + /// Swap in use. | ||
| 26 | + public var swapUsedBytes: Int64? | ||
| 27 | + /// The server process's memory footprint. | ||
| 28 | + public var processBytes: Int64? | ||
| 29 | + /// GPU utilisation in percent, from IOKit's `IOAccelerator` statistics (macOS). | ||
| 30 | + public var gpuUtilization: Int? | ||
| 31 | + | ||
| 32 | + public init( | ||
| 33 | + physicalBytes: Int64, pressure: String? = nil, availableBytes: Int64? = nil, | ||
| 34 | + compressedBytes: Int64? = nil, swapUsedBytes: Int64? = nil, processBytes: Int64? = nil, | ||
| 35 | + gpuUtilization: Int? = nil | ||
| 36 | + ) { | ||
| 37 | + self.physicalBytes = physicalBytes | ||
| 38 | + self.pressure = pressure | ||
| 39 | + self.availableBytes = availableBytes | ||
| 40 | + self.compressedBytes = compressedBytes | ||
| 41 | + self.swapUsedBytes = swapUsedBytes | ||
| 42 | + self.processBytes = processBytes | ||
| 43 | + self.gpuUtilization = gpuUtilization | ||
| 44 | + } | ||
| 45 | +} | ||
| 46 | + | ||
| 47 | +/// Reads a ``SystemSnapshot``; servers take one so tests can give fixed values. | ||
| 48 | +public typealias SystemReporter = @Sendable () -> SystemSnapshot | ||
| 49 | + | ||
| 50 | +/// Measures the machine. Each read is cheap (a few `sysctl` and one IORegistry walk), so it is done | ||
| 51 | +/// on each status request rather than on a timer. | ||
| 52 | +public enum SystemMonitor { | ||
| 53 | + public static let measure: SystemReporter = { | ||
| 54 | + var snapshot = SystemSnapshot(physicalBytes: Int64(ProcessInfo.processInfo.physicalMemory)) | ||
| 55 | + #if canImport(Darwin) | ||
| 56 | + snapshot.pressure = pressureLevel() | ||
| 57 | + if let pages = pageCounts() { | ||
| 58 | + snapshot.availableBytes = pages.available | ||
| 59 | + snapshot.compressedBytes = pages.compressed | ||
| 60 | + } | ||
| 61 | + snapshot.swapUsedBytes = swapUsed() | ||
| 62 | + snapshot.processBytes = footprint() | ||
| 63 | + snapshot.gpuUtilization = gpuUtilization() | ||
| 64 | + #elseif os(Linux) | ||
| 65 | + let meminfo = (try? String(contentsOfFile: "/proc/meminfo", encoding: .utf8)) ?? "" | ||
| 66 | + let fields = parseMeminfo(meminfo) | ||
| 67 | + snapshot.availableBytes = fields["MemAvailable"] | ||
| 68 | + if let total = fields["SwapTotal"], let free = fields["SwapFree"] { | ||
| 69 | + snapshot.swapUsedBytes = total - free | ||
| 70 | + } | ||
| 71 | + let status = (try? String(contentsOfFile: "/proc/self/status", encoding: .utf8)) ?? "" | ||
| 72 | + snapshot.processBytes = parseMeminfo(status)["VmRSS"] | ||
| 73 | + #endif | ||
| 74 | + return snapshot | ||
| 75 | + } | ||
| 76 | + | ||
| 77 | + /// `/proc/meminfo`-style lines (`MemAvailable: 123456 kB`) as bytes, by name. | ||
| 78 | + public static func parseMeminfo(_ text: String) -> [String: Int64] { | ||
| 79 | + var fields: [String: Int64] = [:] | ||
| 80 | + for line in text.split(separator: "\n") { | ||
| 81 | + let parts = line.split(whereSeparator: { $0 == ":" || $0.isWhitespace }) | ||
| 82 | + guard parts.count >= 2, let value = Int64(parts[1]) else { continue } | ||
| 83 | + let kilobytes = parts.count >= 3 && parts[2] == "kB" | ||
| 84 | + fields[String(parts[0])] = kilobytes ? value * 1024 : value | ||
| 85 | + } | ||
| 86 | + return fields | ||
| 87 | + } | ||
| 88 | + | ||
| 89 | + #if canImport(Darwin) | ||
| 90 | + /// `kern.memorystatus_vm_pressure_level`: 1 normal, 2 warning, 4 critical. | ||
| 91 | + static func pressureLevel() -> String? { | ||
| 92 | + var level: Int32 = 0 | ||
| 93 | + var size = MemoryLayout<Int32>.size | ||
| 94 | + guard sysctlbyname("kern.memorystatus_vm_pressure_level", &level, &size, nil, 0) == 0 | ||
| 95 | + else { return nil } | ||
| 96 | + switch level { | ||
| 97 | + case 1: return "normal" | ||
| 98 | + case 2: return "warning" | ||
| 99 | + case 4: return "critical" | ||
| 100 | + default: return nil | ||
| 101 | + } | ||
| 102 | + } | ||
| 103 | + | ||
| 104 | + /// Free + speculative pages, and compressed pages, in bytes (`host_statistics64`). | ||
| 105 | + static func pageCounts() -> (available: Int64, compressed: Int64)? { | ||
| 106 | + var statistics = vm_statistics64() | ||
| 107 | + var count = mach_msg_type_number_t( | ||
| 108 | + MemoryLayout<vm_statistics64>.size / MemoryLayout<integer_t>.size) | ||
| 109 | + let result = withUnsafeMutablePointer(to: &statistics) { pointer in | ||
| 110 | + pointer.withMemoryRebound(to: integer_t.self, capacity: Int(count)) { | ||
| 111 | + host_statistics64(mach_host_self(), HOST_VM_INFO64, $0, &count) | ||
| 112 | + } | ||
| 113 | + } | ||
| 114 | + guard result == KERN_SUCCESS, let page = sysctlInt64("hw.pagesize") else { return nil } | ||
| 115 | + let available = Int64(statistics.free_count) + Int64(statistics.speculative_count) | ||
| 116 | + return (available * page, Int64(statistics.compressor_page_count) * page) | ||
| 117 | + } | ||
| 118 | + | ||
| 119 | + /// `vm.swapusage`. | ||
| 120 | + static func swapUsed() -> Int64? { | ||
| 121 | + var usage = xsw_usage() | ||
| 122 | + var size = MemoryLayout<xsw_usage>.size | ||
| 123 | + guard sysctlbyname("vm.swapusage", &usage, &size, nil, 0) == 0 else { return nil } | ||
| 124 | + return Int64(usage.xsu_used) | ||
| 125 | + } | ||
| 126 | + | ||
| 127 | + /// The process's physical footprint, as Activity Monitor's Memory column. | ||
| 128 | + static func footprint() -> Int64? { | ||
| 129 | + var info = rusage_info_v4() | ||
| 130 | + let result = withUnsafeMutablePointer(to: &info) { pointer in | ||
| 131 | + pointer.withMemoryRebound(to: rusage_info_t?.self, capacity: 1) { | ||
| 132 | + proc_pid_rusage(getpid(), RUSAGE_INFO_V4, $0) | ||
| 133 | + } | ||
| 134 | + } | ||
| 135 | + return result == 0 ? Int64(info.ri_phys_footprint) : nil | ||
| 136 | + } | ||
| 137 | + | ||
| 138 | + /// The highest `Device Utilization %` among the `IOAccelerator` services; `nil` when no | ||
| 139 | + /// service publishes it (the key is undocumented and may change). | ||
| 140 | + static func gpuUtilization() -> Int? { | ||
| 141 | + var iterator: io_iterator_t = 0 | ||
| 142 | + guard | ||
| 143 | + IOServiceGetMatchingServices( | ||
| 144 | + kIOMainPortDefault, IOServiceMatching("IOAccelerator"), &iterator) == KERN_SUCCESS | ||
| 145 | + else { return nil } | ||
| 146 | + defer { IOObjectRelease(iterator) } | ||
| 147 | + var highest: Int? | ||
| 148 | + var service = IOIteratorNext(iterator) | ||
| 149 | + while service != 0 { | ||
| 150 | + if let value = deviceUtilization(of: service) { highest = max(highest ?? 0, value) } | ||
| 151 | + IOObjectRelease(service) | ||
| 152 | + service = IOIteratorNext(iterator) | ||
| 153 | + } | ||
| 154 | + return highest | ||
| 155 | + } | ||
| 156 | + | ||
| 157 | + private static func deviceUtilization(of service: io_object_t) -> Int? { | ||
| 158 | + let property = IORegistryEntryCreateCFProperty( | ||
| 159 | + service, "PerformanceStatistics" as CFString, kCFAllocatorDefault, 0) | ||
| 160 | + guard let statistics = property?.takeRetainedValue() as? [String: Any] else { return nil } | ||
| 161 | + return (statistics["Device Utilization %"] as? NSNumber)?.intValue | ||
| 162 | + } | ||
| 163 | + | ||
| 164 | + private static func sysctlInt64(_ name: String) -> Int64? { | ||
| 165 | + var value: Int64 = 0 | ||
| 166 | + var size = MemoryLayout<Int64>.size | ||
| 167 | + return sysctlbyname(name, &value, &size, nil, 0) == 0 ? value : nil | ||
| 168 | + } | ||
| 169 | + #endif | ||
| 170 | +} | ||
modified
Sources/RazorbillServer/AdminRoutes.swift +37 -2 | @@ -20,6 +20,7 @@ struct AdminRoutes { | ||
| 20 | 20 | let history: RequestHistory |
| 21 | 21 | let settings: ServerSettings |
| 22 | 22 | let memory: MemoryReporter? |
| 23 | + var system: SystemReporter = SystemMonitor.measure | |
| 23 | 24 | let reloader: ConfigReloader? |
| 24 | 25 | /// When the router was built: the start of the server's uptime. |
| 25 | 26 | let startedAt: ContinuousClock.Instant |
| @@ -75,7 +76,8 @@ struct AdminRoutes { | ||
| 75 | 76 | configFile: settings.configFile.map(Self.absolutePath), |
| 76 | 77 | models: await models.status(now: now).map(StatusModel.init), |
| 77 | 78 | recentRequests: history.recent, |
| 78 | - memory: memory?().map(StatusMemory.init)) | |
| 79 | + memory: memory?().map(StatusMemory.init), | |
| 80 | + system: StatusSystem(system())) | |
| 79 | 81 | } |
| 80 | 82 | } |
| 81 | 83 | |
| @@ -130,9 +132,11 @@ struct ServerStatus: Encodable { | ||
| 130 | 132 | let recentRequests: [RequestRecord] |
| 131 | 133 | /// `null` when the engine cannot measure it (the Linux build). |
| 132 | 134 | let memory: StatusMemory? |
| 135 | + /// The machine (#26, #28). | |
| 136 | + let system: StatusSystem | |
| 133 | 137 | |
| 134 | 138 | enum CodingKeys: String, CodingKey { |
| 135 | - case version, host, port, models, memory | |
| 139 | + case version, host, port, models, memory, system | |
| 136 | 140 | case uptimeSeconds = "uptime_seconds" |
| 137 | 141 | case recentRequests = "recent_requests" |
| 138 | 142 | case configFile = "config_file" |
| @@ -149,6 +153,7 @@ struct ServerStatus: Encodable { | ||
| 149 | 153 | try container.encode(models, forKey: .models) |
| 150 | 154 | try container.encode(recentRequests, forKey: .recentRequests) |
| 151 | 155 | try container.encode(memory, forKey: .memory) |
| 156 | + try container.encode(system, forKey: .system) | |
| 152 | 157 | } |
| 153 | 158 | } |
| 154 | 159 | |
| @@ -225,3 +230,33 @@ struct StatusMemory: Encodable { | ||
| 225 | 230 | case limitBytes = "limit_bytes" |
| 226 | 231 | } |
| 227 | 232 | } |
| 233 | + | |
| 234 | +/// The machine of `GET /rzb/status`: absent measures are explicit `null`s. | |
| 235 | +struct StatusSystem: Encodable { | |
| 236 | + let snapshot: SystemSnapshot | |
| 237 | + | |
| 238 | + init(_ snapshot: SystemSnapshot) { | |
| 239 | + self.snapshot = snapshot | |
| 240 | + } | |
| 241 | + | |
| 242 | + enum CodingKeys: String, CodingKey { | |
| 243 | + case pressure | |
| 244 | + case physicalBytes = "physical_bytes" | |
| 245 | + case availableBytes = "available_bytes" | |
| 246 | + case compressedBytes = "compressed_bytes" | |
| 247 | + case swapUsedBytes = "swap_used_bytes" | |
| 248 | + case processBytes = "process_bytes" | |
| 249 | + case gpuUtilization = "gpu_utilization" | |
| 250 | + } | |
| 251 | + | |
| 252 | + func encode(to encoder: any Encoder) throws { | |
| 253 | + var container = encoder.container(keyedBy: CodingKeys.self) | |
| 254 | + try container.encode(snapshot.physicalBytes, forKey: .physicalBytes) | |
| 255 | + try container.encode(snapshot.pressure, forKey: .pressure) | |
| 256 | + try container.encode(snapshot.availableBytes, forKey: .availableBytes) | |
| 257 | + try container.encode(snapshot.compressedBytes, forKey: .compressedBytes) | |
| 258 | + try container.encode(snapshot.swapUsedBytes, forKey: .swapUsedBytes) | |
| 259 | + try container.encode(snapshot.processBytes, forKey: .processBytes) | |
| 260 | + try container.encode(snapshot.gpuUtilization, forKey: .gpuUtilization) | |
| 261 | + } | |
| 262 | +} | |
| @@ -20,6 +20,7 @@ struct AdminRoutes { | |||
| 20 | let history: RequestHistory | 20 | let history: RequestHistory |
| 21 | let settings: ServerSettings | 21 | let settings: ServerSettings |
| 22 | let memory: MemoryReporter? | 22 | let memory: MemoryReporter? |
| 23 | + var system: SystemReporter = SystemMonitor.measure | ||
| 23 | let reloader: ConfigReloader? | 24 | let reloader: ConfigReloader? |
| 24 | /// When the router was built: the start of the server's uptime. | 25 | /// When the router was built: the start of the server's uptime. |
| 25 | let startedAt: ContinuousClock.Instant | 26 | let startedAt: ContinuousClock.Instant |
| @@ -75,7 +76,8 @@ struct AdminRoutes { | |||
| 75 | configFile: settings.configFile.map(Self.absolutePath), | 76 | configFile: settings.configFile.map(Self.absolutePath), |
| 76 | models: await models.status(now: now).map(StatusModel.init), | 77 | models: await models.status(now: now).map(StatusModel.init), |
| 77 | recentRequests: history.recent, | 78 | recentRequests: history.recent, |
| 78 | - memory: memory?().map(StatusMemory.init)) | 79 | + memory: memory?().map(StatusMemory.init), |
| 80 | + system: StatusSystem(system())) | ||
| 79 | } | 81 | } |
| 80 | } | 82 | } |
| 81 | 83 | ||
| @@ -130,9 +132,11 @@ struct ServerStatus: Encodable { | |||
| 130 | let recentRequests: [RequestRecord] | 132 | let recentRequests: [RequestRecord] |
| 131 | /// `null` when the engine cannot measure it (the Linux build). | 133 | /// `null` when the engine cannot measure it (the Linux build). |
| 132 | let memory: StatusMemory? | 134 | let memory: StatusMemory? |
| 135 | + /// The machine (#26, #28). | ||
| 136 | + let system: StatusSystem | ||
| 133 | 137 | ||
| 134 | enum CodingKeys: String, CodingKey { | 138 | enum CodingKeys: String, CodingKey { |
| 135 | - case version, host, port, models, memory | 139 | + case version, host, port, models, memory, system |
| 136 | case uptimeSeconds = "uptime_seconds" | 140 | case uptimeSeconds = "uptime_seconds" |
| 137 | case recentRequests = "recent_requests" | 141 | case recentRequests = "recent_requests" |
| 138 | case configFile = "config_file" | 142 | case configFile = "config_file" |
| @@ -149,6 +153,7 @@ struct ServerStatus: Encodable { | |||
| 149 | try container.encode(models, forKey: .models) | 153 | try container.encode(models, forKey: .models) |
| 150 | try container.encode(recentRequests, forKey: .recentRequests) | 154 | try container.encode(recentRequests, forKey: .recentRequests) |
| 151 | try container.encode(memory, forKey: .memory) | 155 | try container.encode(memory, forKey: .memory) |
| 156 | + try container.encode(system, forKey: .system) | ||
| 152 | } | 157 | } |
| 153 | } | 158 | } |
| 154 | 159 | ||
| @@ -225,3 +230,33 @@ struct StatusMemory: Encodable { | |||
| 225 | case limitBytes = "limit_bytes" | 230 | case limitBytes = "limit_bytes" |
| 226 | } | 231 | } |
| 227 | } | 232 | } |
| 233 | + | ||
| 234 | +/// The machine of `GET /rzb/status`: absent measures are explicit `null`s. | ||
| 235 | +struct StatusSystem: Encodable { | ||
| 236 | + let snapshot: SystemSnapshot | ||
| 237 | + | ||
| 238 | + init(_ snapshot: SystemSnapshot) { | ||
| 239 | + self.snapshot = snapshot | ||
| 240 | + } | ||
| 241 | + | ||
| 242 | + enum CodingKeys: String, CodingKey { | ||
| 243 | + case pressure | ||
| 244 | + case physicalBytes = "physical_bytes" | ||
| 245 | + case availableBytes = "available_bytes" | ||
| 246 | + case compressedBytes = "compressed_bytes" | ||
| 247 | + case swapUsedBytes = "swap_used_bytes" | ||
| 248 | + case processBytes = "process_bytes" | ||
| 249 | + case gpuUtilization = "gpu_utilization" | ||
| 250 | + } | ||
| 251 | + | ||
| 252 | + func encode(to encoder: any Encoder) throws { | ||
| 253 | + var container = encoder.container(keyedBy: CodingKeys.self) | ||
| 254 | + try container.encode(snapshot.physicalBytes, forKey: .physicalBytes) | ||
| 255 | + try container.encode(snapshot.pressure, forKey: .pressure) | ||
| 256 | + try container.encode(snapshot.availableBytes, forKey: .availableBytes) | ||
| 257 | + try container.encode(snapshot.compressedBytes, forKey: .compressedBytes) | ||
| 258 | + try container.encode(snapshot.swapUsedBytes, forKey: .swapUsedBytes) | ||
| 259 | + try container.encode(snapshot.processBytes, forKey: .processBytes) | ||
| 260 | + try container.encode(snapshot.gpuUtilization, forKey: .gpuUtilization) | ||
| 261 | + } | ||
| 262 | +} | ||
modified
Sources/RazorbillServer/RazorbillServer.swift +2 -2 | @@ -31,7 +31,7 @@ public enum RazorbillServer { | ||
| 31 | 31 | public static func makeRouter( |
| 32 | 32 | _ settings: ServerSettings, models: ModelManager, streamKeepAlive: Duration = .seconds(5), |
| 33 | 33 | history: RequestHistory = RequestHistory(), memory: MemoryReporter? = nil, |
| 34 | - reloader: ConfigReloader? = nil | |
| 34 | + reloader: ConfigReloader? = nil, system: @escaping SystemReporter = SystemMonitor.measure | |
| 35 | 35 | ) -> Router<ServerContext> { |
| 36 | 36 | let router = Router(context: ServerContext.self) |
| 37 | 37 | router.middlewares.add(RequestLogMiddleware(history: history)) |
| @@ -50,7 +50,7 @@ public enum RazorbillServer { | ||
| 50 | 50 | EmbeddingsRoute(models: models).add(to: router) |
| 51 | 51 | AdminRoutes( |
| 52 | 52 | models: models, history: history, settings: settings, memory: memory, |
| 53 | - reloader: reloader, startedAt: .now | |
| 53 | + system: system, reloader: reloader, startedAt: .now | |
| 54 | 54 | ).add(to: router) |
| 55 | 55 | return router |
| 56 | 56 | } |
| @@ -31,7 +31,7 @@ public enum RazorbillServer { | |||
| 31 | public static func makeRouter( | 31 | public static func makeRouter( |
| 32 | _ settings: ServerSettings, models: ModelManager, streamKeepAlive: Duration = .seconds(5), | 32 | _ settings: ServerSettings, models: ModelManager, streamKeepAlive: Duration = .seconds(5), |
| 33 | history: RequestHistory = RequestHistory(), memory: MemoryReporter? = nil, | 33 | history: RequestHistory = RequestHistory(), memory: MemoryReporter? = nil, |
| 34 | - reloader: ConfigReloader? = nil | 34 | + reloader: ConfigReloader? = nil, system: @escaping SystemReporter = SystemMonitor.measure |
| 35 | ) -> Router<ServerContext> { | 35 | ) -> Router<ServerContext> { |
| 36 | let router = Router(context: ServerContext.self) | 36 | let router = Router(context: ServerContext.self) |
| 37 | router.middlewares.add(RequestLogMiddleware(history: history)) | 37 | router.middlewares.add(RequestLogMiddleware(history: history)) |
| @@ -50,7 +50,7 @@ public enum RazorbillServer { | |||
| 50 | EmbeddingsRoute(models: models).add(to: router) | 50 | EmbeddingsRoute(models: models).add(to: router) |
| 51 | AdminRoutes( | 51 | AdminRoutes( |
| 52 | models: models, history: history, settings: settings, memory: memory, | 52 | models: models, history: history, settings: settings, memory: memory, |
| 53 | - reloader: reloader, startedAt: .now | 53 | + system: system, reloader: reloader, startedAt: .now |
| 54 | ).add(to: router) | 54 | ).add(to: router) |
| 55 | return router | 55 | return router |
| 56 | } | 56 | } |
modified
Sources/RazorbillTUI/AppRenderer.swift +14 -1 | @@ -67,7 +67,10 @@ public struct AppRenderer: Sendable { | ||
| 67 | 67 | let used = Self.gigabytes(memory.used) |
| 68 | 68 | parts.append("memory \(used) / \(Self.gigabytes(memory.limit))") |
| 69 | 69 | } |
| 70 | - return (style.green("●"), parts.joined(separator: " · ")) | |
| 70 | + if let gpu = state.gpuUtilization { parts.append("gpu \(gpu)%") } | |
| 71 | + var text = parts.joined(separator: " · ") | |
| 72 | + if let pressure = state.pressure { text += " · " + self.pressure(pressure) } | |
| 73 | + return (style.green("●"), text) | |
| 71 | 74 | case .unreachable: |
| 72 | 75 | return (style.red("○"), "no server at \(url) — start one with: rzb serve") |
| 73 | 76 | case .unauthorized: |
| @@ -78,6 +81,16 @@ public struct AppRenderer: Sendable { | ||
| 78 | 81 | } |
| 79 | 82 | } |
| 80 | 83 | |
| 84 | + /// `pressure normal` in green, `warning` in yellow, `critical` in red. | |
| 85 | + func pressure(_ level: String) -> String { | |
| 86 | + let text = "pressure \(level)" | |
| 87 | + switch level { | |
| 88 | + case "normal": return style.green(text) | |
| 89 | + case "warning": return style.yellow(text) | |
| 90 | + default: return style.red(text) | |
| 91 | + } | |
| 92 | + } | |
| 93 | + | |
| 81 | 94 | /// `12.3 GB`, one decimal, 1 GB = 2³⁰ bytes like the server's own messages. |
| 82 | 95 | static func gigabytes(_ bytes: Int64) -> String { |
| 83 | 96 | String(format: "%.1f GB", Double(bytes) / 1_073_741_824) |
| @@ -67,7 +67,10 @@ public struct AppRenderer: Sendable { | |||
| 67 | let used = Self.gigabytes(memory.used) | 67 | let used = Self.gigabytes(memory.used) |
| 68 | parts.append("memory \(used) / \(Self.gigabytes(memory.limit))") | 68 | parts.append("memory \(used) / \(Self.gigabytes(memory.limit))") |
| 69 | } | 69 | } |
| 70 | - return (style.green("●"), parts.joined(separator: " · ")) | 70 | + if let gpu = state.gpuUtilization { parts.append("gpu \(gpu)%") } |
| 71 | + var text = parts.joined(separator: " · ") | ||
| 72 | + if let pressure = state.pressure { text += " · " + self.pressure(pressure) } | ||
| 73 | + return (style.green("●"), text) | ||
| 71 | case .unreachable: | 74 | case .unreachable: |
| 72 | return (style.red("○"), "no server at \(url) — start one with: rzb serve") | 75 | return (style.red("○"), "no server at \(url) — start one with: rzb serve") |
| 73 | case .unauthorized: | 76 | case .unauthorized: |
| @@ -78,6 +81,16 @@ public struct AppRenderer: Sendable { | |||
| 78 | } | 81 | } |
| 79 | } | 82 | } |
| 80 | 83 | ||
| 84 | + /// `pressure normal` in green, `warning` in yellow, `critical` in red. | ||
| 85 | + func pressure(_ level: String) -> String { | ||
| 86 | + let text = "pressure \(level)" | ||
| 87 | + switch level { | ||
| 88 | + case "normal": return style.green(text) | ||
| 89 | + case "warning": return style.yellow(text) | ||
| 90 | + default: return style.red(text) | ||
| 91 | + } | ||
| 92 | + } | ||
| 93 | + | ||
| 81 | /// `12.3 GB`, one decimal, 1 GB = 2³⁰ bytes like the server's own messages. | 94 | /// `12.3 GB`, one decimal, 1 GB = 2³⁰ bytes like the server's own messages. |
| 82 | static func gigabytes(_ bytes: Int64) -> String { | 95 | static func gigabytes(_ bytes: Int64) -> String { |
| 83 | String(format: "%.1f GB", Double(bytes) / 1_073_741_824) | 96 | String(format: "%.1f GB", Double(bytes) / 1_073_741_824) |
modified
Sources/RazorbillTUI/AppState.swift +3 -0 | @@ -61,6 +61,9 @@ public struct AppState: Sendable, Equatable { | ||
| 61 | 61 | public var model: String? |
| 62 | 62 | /// The engine's memory, when the server reports it. |
| 63 | 63 | public var memory: MemoryUse? |
| 64 | + /// The machine's GPU load in percent and memory pressure, when the server measures them. | |
| 65 | + public var gpuUtilization: Int? | |
| 66 | + public var pressure: String? | |
| 64 | 67 | |
| 65 | 68 | /// Starts on the Dashboard, the screen that has content before the chat exists (#55). |
| 66 | 69 | public init(serverURL: String, screen: AppScreen = .dashboard) { |
| @@ -61,6 +61,9 @@ public struct AppState: Sendable, Equatable { | |||
| 61 | public var model: String? | 61 | public var model: String? |
| 62 | /// The engine's memory, when the server reports it. | 62 | /// The engine's memory, when the server reports it. |
| 63 | public var memory: MemoryUse? | 63 | public var memory: MemoryUse? |
| 64 | + /// The machine's GPU load in percent and memory pressure, when the server measures them. | ||
| 65 | + public var gpuUtilization: Int? | ||
| 66 | + public var pressure: String? | ||
| 64 | 67 | ||
| 65 | /// Starts on the Dashboard, the screen that has content before the chat exists (#55). | 68 | /// Starts on the Dashboard, the screen that has content before the chat exists (#55). |
| 66 | public init(serverURL: String, screen: AppScreen = .dashboard) { | 69 | public init(serverURL: String, screen: AppScreen = .dashboard) { |
modified
Sources/RazorbillTUI/DashboardScreen.swift +26 -0 | @@ -43,6 +43,7 @@ public struct DashboardScreen: Sendable, Equatable { | ||
| 43 | 43 | " Server rzb \(snapshot.version) · up \(Self.duration(snapshot.uptimeSeconds))" |
| 44 | 44 | + " · \(snapshot.host):\(snapshot.port)", |
| 45 | 45 | " Memory " + Self.memory(snapshot.memory), |
| 46 | + " Machine " + Self.machine(snapshot.system, style: style), | |
| 46 | 47 | "", |
| 47 | 48 | style.bold(" Models") + style.dim(" ↑↓ select · u unload"), |
| 48 | 49 | style.dim(Self.modelHeader), |
| @@ -115,6 +116,31 @@ public struct DashboardScreen: Sendable, Equatable { | ||
| 115 | 116 | + " · peak \(AppRenderer.gigabytes(memory.peakBytes))" |
| 116 | 117 | } |
| 117 | 118 | |
| 119 | + /// `pressure normal · 18.2 GB available of 32.0 GB · compressed 1.1 GB · swap 0.0 GB · | |
| 120 | + /// rzb 4.1 GB · gpu 87%`, each part only when measured. | |
| 121 | + static func machine(_ system: MachineState?, style: Style) -> String { | |
| 122 | + guard let system else { return "not reported by this server" } | |
| 123 | + var parts: [String] = [] | |
| 124 | + if let pressure = system.pressure { | |
| 125 | + parts.append(AppRenderer(style: style).pressure(pressure)) | |
| 126 | + } | |
| 127 | + let total = AppRenderer.gigabytes(system.physicalBytes) | |
| 128 | + if let available = system.availableBytes { | |
| 129 | + parts.append("\(AppRenderer.gigabytes(available)) available of \(total)") | |
| 130 | + } else { | |
| 131 | + parts.append("\(total) installed") | |
| 132 | + } | |
| 133 | + if let compressed = system.compressedBytes { | |
| 134 | + parts.append("compressed \(AppRenderer.gigabytes(compressed))") | |
| 135 | + } | |
| 136 | + if let swap = system.swapUsedBytes { parts.append("swap \(AppRenderer.gigabytes(swap))") } | |
| 137 | + if let process = system.processBytes { | |
| 138 | + parts.append("rzb \(AppRenderer.gigabytes(process))") | |
| 139 | + } | |
| 140 | + if let gpu = system.gpuUtilization { parts.append("gpu \(gpu)%") } | |
| 141 | + return parts.joined(separator: " · ") | |
| 142 | + } | |
| 143 | + | |
| 118 | 144 | /// `[████░░░░░░░░░░░░░░░░]`, 20 cells. |
| 119 | 145 | static func gauge(_ value: Int64, of limit: Int64, cells: Int = 20) -> String { |
| 120 | 146 | let ratio = limit > 0 ? min(1, max(0, Double(value) / Double(limit))) : 0 |
| @@ -43,6 +43,7 @@ public struct DashboardScreen: Sendable, Equatable { | |||
| 43 | " Server rzb \(snapshot.version) · up \(Self.duration(snapshot.uptimeSeconds))" | 43 | " Server rzb \(snapshot.version) · up \(Self.duration(snapshot.uptimeSeconds))" |
| 44 | + " · \(snapshot.host):\(snapshot.port)", | 44 | + " · \(snapshot.host):\(snapshot.port)", |
| 45 | " Memory " + Self.memory(snapshot.memory), | 45 | " Memory " + Self.memory(snapshot.memory), |
| 46 | + " Machine " + Self.machine(snapshot.system, style: style), | ||
| 46 | "", | 47 | "", |
| 47 | style.bold(" Models") + style.dim(" ↑↓ select · u unload"), | 48 | style.bold(" Models") + style.dim(" ↑↓ select · u unload"), |
| 48 | style.dim(Self.modelHeader), | 49 | style.dim(Self.modelHeader), |
| @@ -115,6 +116,31 @@ public struct DashboardScreen: Sendable, Equatable { | |||
| 115 | + " · peak \(AppRenderer.gigabytes(memory.peakBytes))" | 116 | + " · peak \(AppRenderer.gigabytes(memory.peakBytes))" |
| 116 | } | 117 | } |
| 117 | 118 | ||
| 119 | + /// `pressure normal · 18.2 GB available of 32.0 GB · compressed 1.1 GB · swap 0.0 GB · | ||
| 120 | + /// rzb 4.1 GB · gpu 87%`, each part only when measured. | ||
| 121 | + static func machine(_ system: MachineState?, style: Style) -> String { | ||
| 122 | + guard let system else { return "not reported by this server" } | ||
| 123 | + var parts: [String] = [] | ||
| 124 | + if let pressure = system.pressure { | ||
| 125 | + parts.append(AppRenderer(style: style).pressure(pressure)) | ||
| 126 | + } | ||
| 127 | + let total = AppRenderer.gigabytes(system.physicalBytes) | ||
| 128 | + if let available = system.availableBytes { | ||
| 129 | + parts.append("\(AppRenderer.gigabytes(available)) available of \(total)") | ||
| 130 | + } else { | ||
| 131 | + parts.append("\(total) installed") | ||
| 132 | + } | ||
| 133 | + if let compressed = system.compressedBytes { | ||
| 134 | + parts.append("compressed \(AppRenderer.gigabytes(compressed))") | ||
| 135 | + } | ||
| 136 | + if let swap = system.swapUsedBytes { parts.append("swap \(AppRenderer.gigabytes(swap))") } | ||
| 137 | + if let process = system.processBytes { | ||
| 138 | + parts.append("rzb \(AppRenderer.gigabytes(process))") | ||
| 139 | + } | ||
| 140 | + if let gpu = system.gpuUtilization { parts.append("gpu \(gpu)%") } | ||
| 141 | + return parts.joined(separator: " · ") | ||
| 142 | + } | ||
| 143 | + | ||
| 118 | /// `[████░░░░░░░░░░░░░░░░]`, 20 cells. | 144 | /// `[████░░░░░░░░░░░░░░░░]`, 20 cells. |
| 119 | static func gauge(_ value: Int64, of limit: Int64, cells: Int = 20) -> String { | 145 | static func gauge(_ value: Int64, of limit: Int64, cells: Int = 20) -> String { |
| 120 | let ratio = limit > 0 ? min(1, max(0, Double(value) / Double(limit))) : 0 | 146 | let ratio = limit > 0 ? min(1, max(0, Double(value) / Double(limit))) : 0 |
modified
Sources/RazorbillTUI/ServerAPI.swift +29 -0 | @@ -13,6 +13,35 @@ public struct StatusSnapshot: Sendable, Equatable, Decodable { | ||
| 13 | 13 | public var recentRequests: [RecentRequest] |
| 14 | 14 | /// `nil` when the server's engine cannot measure it (Linux). |
| 15 | 15 | public var memory: EngineMemory? |
| 16 | + /// The machine; `nil` before razorbill 0.3. | |
| 17 | + public var system: MachineState? | |
| 18 | +} | |
| 19 | + | |
| 20 | +/// ``StatusSnapshot/system``: the machine's memory and GPU, each `nil` when not measured. | |
| 21 | +public struct MachineState: Sendable, Equatable, Decodable { | |
| 22 | + public var physicalBytes: Int64 | |
| 23 | + /// `normal`, `warning` or `critical`. | |
| 24 | + public var pressure: String? | |
| 25 | + public var availableBytes: Int64? | |
| 26 | + public var compressedBytes: Int64? | |
| 27 | + public var swapUsedBytes: Int64? | |
| 28 | + public var processBytes: Int64? | |
| 29 | + /// Percent. | |
| 30 | + public var gpuUtilization: Int? | |
| 31 | + | |
| 32 | + public init( | |
| 33 | + physicalBytes: Int64, pressure: String? = nil, availableBytes: Int64? = nil, | |
| 34 | + compressedBytes: Int64? = nil, swapUsedBytes: Int64? = nil, processBytes: Int64? = nil, | |
| 35 | + gpuUtilization: Int? = nil | |
| 36 | + ) { | |
| 37 | + self.physicalBytes = physicalBytes | |
| 38 | + self.pressure = pressure | |
| 39 | + self.availableBytes = availableBytes | |
| 40 | + self.compressedBytes = compressedBytes | |
| 41 | + self.swapUsedBytes = swapUsedBytes | |
| 42 | + self.processBytes = processBytes | |
| 43 | + self.gpuUtilization = gpuUtilization | |
| 44 | + } | |
| 16 | 45 | } |
| 17 | 46 | |
| 18 | 47 | /// One entry of ``StatusSnapshot/models``. |
| @@ -13,6 +13,35 @@ public struct StatusSnapshot: Sendable, Equatable, Decodable { | |||
| 13 | public var recentRequests: [RecentRequest] | 13 | public var recentRequests: [RecentRequest] |
| 14 | /// `nil` when the server's engine cannot measure it (Linux). | 14 | /// `nil` when the server's engine cannot measure it (Linux). |
| 15 | public var memory: EngineMemory? | 15 | public var memory: EngineMemory? |
| 16 | + /// The machine; `nil` before razorbill 0.3. | ||
| 17 | + public var system: MachineState? | ||
| 18 | +} | ||
| 19 | + | ||
| 20 | +/// ``StatusSnapshot/system``: the machine's memory and GPU, each `nil` when not measured. | ||
| 21 | +public struct MachineState: Sendable, Equatable, Decodable { | ||
| 22 | + public var physicalBytes: Int64 | ||
| 23 | + /// `normal`, `warning` or `critical`. | ||
| 24 | + public var pressure: String? | ||
| 25 | + public var availableBytes: Int64? | ||
| 26 | + public var compressedBytes: Int64? | ||
| 27 | + public var swapUsedBytes: Int64? | ||
| 28 | + public var processBytes: Int64? | ||
| 29 | + /// Percent. | ||
| 30 | + public var gpuUtilization: Int? | ||
| 31 | + | ||
| 32 | + public init( | ||
| 33 | + physicalBytes: Int64, pressure: String? = nil, availableBytes: Int64? = nil, | ||
| 34 | + compressedBytes: Int64? = nil, swapUsedBytes: Int64? = nil, processBytes: Int64? = nil, | ||
| 35 | + gpuUtilization: Int? = nil | ||
| 36 | + ) { | ||
| 37 | + self.physicalBytes = physicalBytes | ||
| 38 | + self.pressure = pressure | ||
| 39 | + self.availableBytes = availableBytes | ||
| 40 | + self.compressedBytes = compressedBytes | ||
| 41 | + self.swapUsedBytes = swapUsedBytes | ||
| 42 | + self.processBytes = processBytes | ||
| 43 | + self.gpuUtilization = gpuUtilization | ||
| 44 | + } | ||
| 16 | } | 45 | } |
| 17 | 46 | ||
| 18 | /// One entry of ``StatusSnapshot/models``. | 47 | /// One entry of ``StatusSnapshot/models``. |
modified
Sources/RazorbillTUI/TUIApp.swift +4 -0 | @@ -226,6 +226,8 @@ public actor TUIApp { | ||
| 226 | 226 | state.connection = .connected(version: status.version) |
| 227 | 227 | state.model = status.models.first?.name |
| 228 | 228 | state.memory = status.memory.map { MemoryUse(used: $0.activeBytes, limit: $0.limitBytes) } |
| 229 | + state.gpuUtilization = status.system?.gpuUtilization | |
| 230 | + state.pressure = status.system?.pressure | |
| 229 | 231 | if !wasConnected && state.screen == .chat && chat.models.isEmpty { loadModels() } |
| 230 | 232 | if state.screen == .models { refreshModels() } |
| 231 | 233 | } |
| @@ -235,6 +237,8 @@ public actor TUIApp { | ||
| 235 | 237 | state.connection = connection |
| 236 | 238 | state.model = nil |
| 237 | 239 | state.memory = nil |
| 240 | + state.gpuUtilization = nil | |
| 241 | + state.pressure = nil | |
| 238 | 242 | } |
| 239 | 243 | |
| 240 | 244 | // MARK: Drawing |
| @@ -226,6 +226,8 @@ public actor TUIApp { | |||
| 226 | state.connection = .connected(version: status.version) | 226 | state.connection = .connected(version: status.version) |
| 227 | state.model = status.models.first?.name | 227 | state.model = status.models.first?.name |
| 228 | state.memory = status.memory.map { MemoryUse(used: $0.activeBytes, limit: $0.limitBytes) } | 228 | state.memory = status.memory.map { MemoryUse(used: $0.activeBytes, limit: $0.limitBytes) } |
| 229 | + state.gpuUtilization = status.system?.gpuUtilization | ||
| 230 | + state.pressure = status.system?.pressure | ||
| 229 | if !wasConnected && state.screen == .chat && chat.models.isEmpty { loadModels() } | 231 | if !wasConnected && state.screen == .chat && chat.models.isEmpty { loadModels() } |
| 230 | if state.screen == .models { refreshModels() } | 232 | if state.screen == .models { refreshModels() } |
| 231 | } | 233 | } |
| @@ -235,6 +237,8 @@ public actor TUIApp { | |||
| 235 | state.connection = connection | 237 | state.connection = connection |
| 236 | state.model = nil | 238 | state.model = nil |
| 237 | state.memory = nil | 239 | state.memory = nil |
| 240 | + state.gpuUtilization = nil | ||
| 241 | + state.pressure = nil | ||
| 238 | } | 242 | } |
| 239 | 243 | ||
| 240 | // MARK: Drawing | 244 | // MARK: Drawing |
added
Tests/RazorbillCoreTests/SystemMonitorTests.swift +33 -0 | new file mode 100644 | ||
| @@ -0,0 +1,33 @@ | ||
| 1 | +import Foundation | |
| 2 | +import RazorbillCore | |
| 3 | +import Testing | |
| 4 | + | |
| 5 | +@Suite struct SystemMonitorTests { | |
| 6 | + @Test func meminfoLinesBecomeBytes() { | |
| 7 | + let fields = SystemMonitor.parseMeminfo( | |
| 8 | + """ | |
| 9 | + MemTotal: 16384 kB | |
| 10 | + MemAvailable: 8192 kB | |
| 11 | + HugePages_Total: 0 | |
| 12 | + VmRSS:\t 2048 kB | |
| 13 | + bad line | |
| 14 | + """) | |
| 15 | + #expect(fields["MemTotal"] == 16_777_216 && fields["MemAvailable"] == 8_388_608) | |
| 16 | + #expect(fields["HugePages_Total"] == 0 && fields["bad"] == nil) | |
| 17 | + #expect(fields["VmRSS"] == 2_097_152) | |
| 18 | + } | |
| 19 | + | |
| 20 | + @Test func measuresThisMachine() { | |
| 21 | + let snapshot = SystemMonitor.measure() | |
| 22 | + #expect(snapshot.physicalBytes > 0) | |
| 23 | + #expect((snapshot.availableBytes ?? 0) > 0) | |
| 24 | + #expect((snapshot.processBytes ?? 0) > 0) | |
| 25 | + #if canImport(Darwin) | |
| 26 | + #expect(["normal", "warning", "critical"].contains(snapshot.pressure ?? "")) | |
| 27 | + #expect(snapshot.compressedBytes != nil && snapshot.swapUsedBytes != nil) | |
| 28 | + if let gpu = snapshot.gpuUtilization { #expect((0 ... 100).contains(gpu)) } | |
| 29 | + #else | |
| 30 | + #expect(snapshot.pressure == nil && snapshot.gpuUtilization == nil) | |
| 31 | + #endif | |
| 32 | + } | |
| 33 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,33 @@ | |||
| 1 | +import Foundation | ||
| 2 | +import RazorbillCore | ||
| 3 | +import Testing | ||
| 4 | + | ||
| 5 | +@Suite struct SystemMonitorTests { | ||
| 6 | + @Test func meminfoLinesBecomeBytes() { | ||
| 7 | + let fields = SystemMonitor.parseMeminfo( | ||
| 8 | + """ | ||
| 9 | + MemTotal: 16384 kB | ||
| 10 | + MemAvailable: 8192 kB | ||
| 11 | + HugePages_Total: 0 | ||
| 12 | + VmRSS:\t 2048 kB | ||
| 13 | + bad line | ||
| 14 | + """) | ||
| 15 | + #expect(fields["MemTotal"] == 16_777_216 && fields["MemAvailable"] == 8_388_608) | ||
| 16 | + #expect(fields["HugePages_Total"] == 0 && fields["bad"] == nil) | ||
| 17 | + #expect(fields["VmRSS"] == 2_097_152) | ||
| 18 | + } | ||
| 19 | + | ||
| 20 | + @Test func measuresThisMachine() { | ||
| 21 | + let snapshot = SystemMonitor.measure() | ||
| 22 | + #expect(snapshot.physicalBytes > 0) | ||
| 23 | + #expect((snapshot.availableBytes ?? 0) > 0) | ||
| 24 | + #expect((snapshot.processBytes ?? 0) > 0) | ||
| 25 | + #if canImport(Darwin) | ||
| 26 | + #expect(["normal", "warning", "critical"].contains(snapshot.pressure ?? "")) | ||
| 27 | + #expect(snapshot.compressedBytes != nil && snapshot.swapUsedBytes != nil) | ||
| 28 | + if let gpu = snapshot.gpuUtilization { #expect((0 ... 100).contains(gpu)) } | ||
| 29 | + #else | ||
| 30 | + #expect(snapshot.pressure == nil && snapshot.gpuUtilization == nil) | ||
| 31 | + #endif | ||
| 32 | + } | ||
| 33 | +} | ||
modified
Tests/RazorbillServerTests/LocalRoutesTests.swift +22 -0 | @@ -186,6 +186,28 @@ func record(_ path: String) -> RequestRecord { | ||
| 186 | 186 | } |
| 187 | 187 | } |
| 188 | 188 | |
| 189 | + @Test func reportsTheMachine() async throws { | |
| 190 | + let models = testModels() | |
| 191 | + let router = RazorbillServer.makeRouter( | |
| 192 | + testSettings, models: models, | |
| 193 | + system: { | |
| 194 | + SystemSnapshot( | |
| 195 | + physicalBytes: 32, pressure: "warning", availableBytes: 8, gpuUtilization: 87) | |
| 196 | + }) | |
| 197 | + try await withLiveServer(router: router) { client in | |
| 198 | + let system = try #require(try await fetchStatus(client)["system"] as? [String: Any]) | |
| 199 | + #expect(system["physical_bytes"] as? Int == 32) | |
| 200 | + #expect(system["pressure"] as? String == "warning") | |
| 201 | + #expect(system["available_bytes"] as? Int == 8) | |
| 202 | + #expect(system["gpu_utilization"] as? Int == 87) | |
| 203 | + #expect(system["swap_used_bytes"] is NSNull && system["compressed_bytes"] is NSNull) | |
| 204 | + } | |
| 205 | + try await withLiveServer { client in | |
| 206 | + let system = try #require(try await fetchStatus(client)["system"] as? [String: Any]) | |
| 207 | + #expect((system["physical_bytes"] as? Int ?? 0) > 0) | |
| 208 | + } | |
| 209 | + } | |
| 210 | + | |
| 189 | 211 | @Test func reportsTheEngineMemory() async throws { |
| 190 | 212 | let models = testModels() |
| 191 | 213 | let router = RazorbillServer.makeRouter(testSettings, models: models) { |
| @@ -186,6 +186,28 @@ func record(_ path: String) -> RequestRecord { | |||
| 186 | } | 186 | } |
| 187 | } | 187 | } |
| 188 | 188 | ||
| 189 | + @Test func reportsTheMachine() async throws { | ||
| 190 | + let models = testModels() | ||
| 191 | + let router = RazorbillServer.makeRouter( | ||
| 192 | + testSettings, models: models, | ||
| 193 | + system: { | ||
| 194 | + SystemSnapshot( | ||
| 195 | + physicalBytes: 32, pressure: "warning", availableBytes: 8, gpuUtilization: 87) | ||
| 196 | + }) | ||
| 197 | + try await withLiveServer(router: router) { client in | ||
| 198 | + let system = try #require(try await fetchStatus(client)["system"] as? [String: Any]) | ||
| 199 | + #expect(system["physical_bytes"] as? Int == 32) | ||
| 200 | + #expect(system["pressure"] as? String == "warning") | ||
| 201 | + #expect(system["available_bytes"] as? Int == 8) | ||
| 202 | + #expect(system["gpu_utilization"] as? Int == 87) | ||
| 203 | + #expect(system["swap_used_bytes"] is NSNull && system["compressed_bytes"] is NSNull) | ||
| 204 | + } | ||
| 205 | + try await withLiveServer { client in | ||
| 206 | + let system = try #require(try await fetchStatus(client)["system"] as? [String: Any]) | ||
| 207 | + #expect((system["physical_bytes"] as? Int ?? 0) > 0) | ||
| 208 | + } | ||
| 209 | + } | ||
| 210 | + | ||
| 189 | @Test func reportsTheEngineMemory() async throws { | 211 | @Test func reportsTheEngineMemory() async throws { |
| 190 | let models = testModels() | 212 | let models = testModels() |
| 191 | let router = RazorbillServer.makeRouter(testSettings, models: models) { | 213 | let router = RazorbillServer.makeRouter(testSettings, models: models) { |
modified
Tests/RazorbillTUITests/DashboardAndChatTests.swift +22 -0 | @@ -32,6 +32,28 @@ let plain = Style(colors: false) | ||
| 32 | 32 | } |
| 33 | 33 | } |
| 34 | 34 | |
| 35 | + @Test func machineLineAndStatusBar() { | |
| 36 | + var status = snapshot() | |
| 37 | + status.system = MachineState( | |
| 38 | + physicalBytes: 32 << 30, pressure: "warning", availableBytes: 8 << 30, | |
| 39 | + compressedBytes: 1 << 30, swapUsedBytes: 0, processBytes: 4 << 30, gpuUtilization: 87) | |
| 40 | + var dashboard = DashboardScreen() | |
| 41 | + #expect( | |
| 42 | + render(&dashboard, status)[2] | |
| 43 | + == " Machine pressure warning · 8.0 GB available of 32.0 GB · compressed 1.0 GB" | |
| 44 | + + " · swap 0.0 GB · rzb 4.0 GB · gpu 87%") | |
| 45 | + #expect(DashboardScreen.machine(nil, style: plain) == "not reported by this server") | |
| 46 | + let linux = MachineState(physicalBytes: 16 << 30) | |
| 47 | + #expect(DashboardScreen.machine(linux, style: plain) == "16.0 GB installed") | |
| 48 | + var state = AppState(serverURL: "u") | |
| 49 | + state.connection = .connected(version: "0.3.0") | |
| 50 | + state.gpuUtilization = 87 | |
| 51 | + state.pressure = "critical" | |
| 52 | + let colored = AppRenderer(style: Style(colors: true)).render( | |
| 53 | + state, body: [], rows: 4, columns: 120) | |
| 54 | + #expect(colored.lines[3].contains("gpu 87% · \u{1B}[31mpressure critical\u{1B}[0m")) | |
| 55 | + } | |
| 56 | + | |
| 35 | 57 | @Test func arrowsSelectAndUUnloadsTheSelectedModel() { |
| 36 | 58 | var second = qwen |
| 37 | 59 | second.name = "embed" |
| @@ -32,6 +32,28 @@ let plain = Style(colors: false) | |||
| 32 | } | 32 | } |
| 33 | } | 33 | } |
| 34 | 34 | ||
| 35 | + @Test func machineLineAndStatusBar() { | ||
| 36 | + var status = snapshot() | ||
| 37 | + status.system = MachineState( | ||
| 38 | + physicalBytes: 32 << 30, pressure: "warning", availableBytes: 8 << 30, | ||
| 39 | + compressedBytes: 1 << 30, swapUsedBytes: 0, processBytes: 4 << 30, gpuUtilization: 87) | ||
| 40 | + var dashboard = DashboardScreen() | ||
| 41 | + #expect( | ||
| 42 | + render(&dashboard, status)[2] | ||
| 43 | + == " Machine pressure warning · 8.0 GB available of 32.0 GB · compressed 1.0 GB" | ||
| 44 | + + " · swap 0.0 GB · rzb 4.0 GB · gpu 87%") | ||
| 45 | + #expect(DashboardScreen.machine(nil, style: plain) == "not reported by this server") | ||
| 46 | + let linux = MachineState(physicalBytes: 16 << 30) | ||
| 47 | + #expect(DashboardScreen.machine(linux, style: plain) == "16.0 GB installed") | ||
| 48 | + var state = AppState(serverURL: "u") | ||
| 49 | + state.connection = .connected(version: "0.3.0") | ||
| 50 | + state.gpuUtilization = 87 | ||
| 51 | + state.pressure = "critical" | ||
| 52 | + let colored = AppRenderer(style: Style(colors: true)).render( | ||
| 53 | + state, body: [], rows: 4, columns: 120) | ||
| 54 | + #expect(colored.lines[3].contains("gpu 87% · \u{1B}[31mpressure critical\u{1B}[0m")) | ||
| 55 | + } | ||
| 56 | + | ||
| 35 | @Test func arrowsSelectAndUUnloadsTheSelectedModel() { | 57 | @Test func arrowsSelectAndUUnloadsTheSelectedModel() { |
| 36 | var second = qwen | 58 | var second = qwen |
| 37 | second.name = "embed" | 59 | second.name = "embed" |