-
Notifications
You must be signed in to change notification settings - Fork 92
Expand file tree
/
Copy pathSystemMonitorStore.swift
More file actions
1085 lines (973 loc) · 37.1 KB
/
Copy pathSystemMonitorStore.swift
File metadata and controls
1085 lines (973 loc) · 37.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import AppKit
import CoreGraphics
import Darwin
import Foundation
import IOKit
import Metal
import Observation
import QuartzCore
struct SystemHistorySample: Identifiable, Equatable, Sendable {
let recordedAt: Date
let value: Double
var id: Date { recordedAt }
}
struct SystemCPUMetrics: Equatable, Sendable {
var totalUsage: Double = 0
var userUsage: Double = 0
var systemUsage: Double = 0
var idleUsage: Double = 1
var coreUsage: [Double] = []
var loadAverages: [Double] = [0, 0, 0]
}
struct SystemGPUMetrics: Equatable, Sendable {
var deviceUsage: Double?
var aneUsage: Double?
var framesPerSecond: Double?
var allocatedMemoryBytes: UInt64?
}
struct SystemMemoryMetrics: Equatable, Sendable {
var totalBytes: UInt64 = 0
var usedBytes: UInt64 = 0
var activeBytes: UInt64 = 0
var wiredBytes: UInt64 = 0
var compressedBytes: UInt64 = 0
var cachedBytes: UInt64 = 0
var freeBytes: UInt64 = 0
var swapUsedBytes: UInt64 = 0
var swapTotalBytes: UInt64 = 0
var usage: Double {
guard totalBytes > 0 else { return 0 }
return min(max(Double(usedBytes) / Double(totalBytes), 0), 1)
}
var pressureLabel: String {
switch usage {
case ..<0.70:
"Normal"
case ..<0.90:
"Elevated"
default:
"Critical"
}
}
}
struct SystemDiskMetrics: Equatable, Sendable {
var totalBytes: UInt64?
var availableBytes: UInt64?
var readBytesPerSecond: Double = 0
var writeBytesPerSecond: Double = 0
var cumulativeReadBytes: UInt64 = 0
var cumulativeWriteBytes: UInt64 = 0
var usedBytes: UInt64? {
guard let totalBytes, let availableBytes, availableBytes <= totalBytes else {
return nil
}
return totalBytes - availableBytes
}
var usage: Double? {
guard let totalBytes, totalBytes > 0, let usedBytes else { return nil }
return Double(usedBytes) / Double(totalBytes)
}
/// Resolves the capacities used by macOS storage UI.
///
/// Important-usage capacity includes space the system can reclaim, such as
/// purgeable APFS data. Raw available capacity is retained as a fallback for
/// file systems that do not expose the preferred value. Inconsistent values
/// are rejected so a failed capacity read is not presented as an empty disk.
static func resolvedCapacity(
total: Int?,
availableForImportantUsage: Int64?,
available: Int?
) -> (total: UInt64, available: UInt64)? {
guard let total = validatedBytes(total), total > 0 else { return nil }
if let important = validatedBytes(
availableForImportantUsage,
notExceeding: total
) {
return (total, important)
}
guard let fallback = validatedBytes(available, notExceeding: total) else {
return nil
}
return (total, fallback)
}
private static func validatedBytes<Value: BinaryInteger>(
_ value: Value?,
notExceeding upperBound: UInt64 = .max
) -> UInt64? {
guard let value,
let bytes = UInt64(exactly: value),
bytes <= upperBound else {
return nil
}
return bytes
}
}
struct SystemDiskIdentity: Equatable, Sendable {
var volumeName = "Macintosh HD"
var fileSystem = "APFS"
var mountPoint = "/"
var deviceIdentifier = NativFormatting.missingValue
var model = "Internal storage"
var connection = "Internal"
var isEncrypted: Bool?
var isWritable: Bool?
var smartStatus: String?
var healthPercent: Int?
var temperatureCelsius: Int?
var powerCycles: UInt64?
var powerOnHours: UInt64?
var unsafeShutdowns: UInt64?
var mediaErrors: UInt64?
var availableSparePercent: Int?
var lifetimeReadBytes: UInt64?
var lifetimeWrittenBytes: UInt64?
}
struct SystemMonitorIdentity: Equatable, Sendable {
var computerName = Host.current().localizedName ?? "This Mac"
var modelIdentifier = NativFormatting.missingValue
var modelNumber: String?
var enclosureColorCode: String?
var productionYear: Int?
var serialNumber = NativFormatting.missingValue
var chipName = "Apple silicon"
var physicalCoreCount = ProcessInfo.processInfo.processorCount
var logicalCoreCount = ProcessInfo.processInfo.activeProcessorCount
var efficiencyCoreCount = 0
var performanceCoreCount = 0
var gpuName = "Apple GPU"
var gpuCoreCount: Int?
var aneCoreCount: Int?
var nominalCPUFrequencyHz: UInt64?
var operatingSystem = ProcessInfo.processInfo.operatingSystemVersionString
var displayName = "Built-in display"
var displayResolution = NativFormatting.missingValue
var displayRefreshRate: Double?
var disk = SystemDiskIdentity()
var deviceModelCode: String {
guard let enclosureColorCode,
!enclosureColorCode.isEmpty else {
return modelIdentifier
}
return "\(modelIdentifier)@ECOLOR=\(enclosureColorCode)"
}
var deviceModelCodeCandidates: [String] {
let colorSpecificCode = deviceModelCode
guard colorSpecificCode != modelIdentifier else {
return [modelIdentifier]
}
return [colorSpecificCode, modelIdentifier]
}
}
struct SystemMonitorSnapshot: Equatable, Sendable {
var recordedAt = Date()
var identity = SystemMonitorIdentity()
var cpu = SystemCPUMetrics()
var gpu = SystemGPUMetrics()
var memory = SystemMemoryMetrics()
var disk = SystemDiskMetrics()
var thermal = SystemThermalMetrics()
var power = SystemPowerMetrics()
var uptime: TimeInterval = ProcessInfo.processInfo.systemUptime
}
struct SystemMonitorObservationPolicy {
private var observerIDs: Set<UUID> = []
private(set) var isPaused = false
mutating func begin(_ observerID: UUID) -> Bool {
let inserted = observerIDs.insert(observerID).inserted
return inserted && observerIDs.count == 1 && !isPaused
}
mutating func end(_ observerID: UUID) -> Bool {
guard observerIDs.remove(observerID) != nil else { return false }
return observerIDs.isEmpty && !isPaused
}
mutating func pause() -> Bool {
guard !isPaused else { return false }
isPaused = true
return !observerIDs.isEmpty
}
mutating func resume() -> Bool {
guard isPaused else { return false }
isPaused = false
return !observerIDs.isEmpty
}
}
@MainActor
@Observable
final class SystemMonitorStore {
private(set) var snapshot = SystemMonitorSnapshot()
private(set) var cpuHistory: [SystemHistorySample] = []
private(set) var gpuHistory: [SystemHistorySample] = []
private(set) var aneHistory: [SystemHistorySample] = []
private(set) var fpsHistory: [SystemHistorySample] = []
private(set) var memoryHistory: [SystemHistorySample] = []
private(set) var swapHistory: [SystemHistorySample] = []
private(set) var diskReadHistory: [SystemHistorySample] = []
private(set) var diskWriteHistory: [SystemHistorySample] = []
private(set) var temperatureHistory: [SystemHistorySample] = []
private(set) var powerHistory: [SystemHistorySample] = []
private(set) var isSampling = false
private let collector = SystemMetricsCollector()
private let displayFPSSampler = SystemDisplayFPSSampler()
private let aneSampler = SystemANEUtilizationSampler()
private var samplingTask: Task<Void, Never>?
private var observationPolicy = SystemMonitorObservationPolicy()
private let historyLimit = 300
isolated deinit {
samplingTask?.cancel()
}
func beginObservation(_ observerID: UUID) {
guard observationPolicy.begin(observerID) else { return }
startSampling()
}
func endObservation(_ observerID: UUID) {
guard observationPolicy.end(observerID) else { return }
stopSampling()
}
func pause() {
guard observationPolicy.pause() else { return }
stopSampling()
}
func resume() {
guard observationPolicy.resume() else { return }
startSampling()
}
private func startSampling() {
guard samplingTask == nil else { return }
isSampling = true
displayFPSSampler.start()
aneSampler.start()
samplingTask = Task { [weak self] in
while !Task.isCancelled {
guard let self else { return }
var nextSnapshot = await collector.collect()
nextSnapshot.gpu.framesPerSecond = displayFPSSampler.takeFramesPerSecond()
nextSnapshot.gpu.aneUsage = aneSampler.takeUtilization()
apply(nextSnapshot)
do {
try await Task.sleep(nanoseconds: 1_000_000_000)
} catch {
return
}
}
}
}
private func stopSampling() {
samplingTask?.cancel()
samplingTask = nil
displayFPSSampler.stop()
aneSampler.stop()
isSampling = false
}
func refresh() {
Task { [weak self] in
guard let self else { return }
apply(await collector.collect())
}
}
func collectSnapshot() async -> SystemMonitorSnapshot {
await collector.collect()
}
private func apply(_ nextSnapshot: SystemMonitorSnapshot) {
snapshot = nextSnapshot
append(nextSnapshot.cpu.totalUsage, at: nextSnapshot.recordedAt, to: &cpuHistory)
append(nextSnapshot.memory.usage, at: nextSnapshot.recordedAt, to: &memoryHistory)
if let value = nextSnapshot.gpu.deviceUsage {
append(value, at: nextSnapshot.recordedAt, to: &gpuHistory)
}
if let value = nextSnapshot.gpu.aneUsage {
append(value, at: nextSnapshot.recordedAt, to: &aneHistory)
}
if let value = nextSnapshot.gpu.framesPerSecond {
append(value, at: nextSnapshot.recordedAt, to: &fpsHistory)
}
let swapUsage: Double
if nextSnapshot.memory.swapTotalBytes > 0 {
swapUsage = Double(nextSnapshot.memory.swapUsedBytes)
/ Double(nextSnapshot.memory.swapTotalBytes)
} else {
swapUsage = 0
}
append(swapUsage, at: nextSnapshot.recordedAt, to: &swapHistory)
if let value = nextSnapshot.thermal.dieTemperatureCelsius {
append(value, at: nextSnapshot.recordedAt, to: &temperatureHistory)
}
if let value = nextSnapshot.power.headlineWatts {
append(value, at: nextSnapshot.recordedAt, to: &powerHistory)
}
append(
nextSnapshot.disk.readBytesPerSecond,
at: nextSnapshot.recordedAt,
to: &diskReadHistory
)
append(
nextSnapshot.disk.writeBytesPerSecond,
at: nextSnapshot.recordedAt,
to: &diskWriteHistory
)
}
private func append(
_ value: Double,
at date: Date,
to samples: inout [SystemHistorySample]
) {
samples.append(SystemHistorySample(recordedAt: date, value: value))
if samples.count > historyLimit {
samples.removeFirst(samples.count - historyLimit)
}
}
}
private struct SystemCPUTicks: Sendable {
let user: UInt64
let system: UInt64
let idle: UInt64
var total: UInt64 { user + system + idle }
}
private struct SystemDiskCounters: Sendable {
let readBytes: UInt64
let writeBytes: UInt64
}
@MainActor
private final class SystemDisplayFPSSampler: NSObject {
private var displayLink: CADisplayLink?
private var firstTimestamp: TimeInterval?
private var lastTimestamp: TimeInterval?
private var frameCount = 0
func start() {
guard displayLink == nil, let screen = NSScreen.main else { return }
let createdDisplayLink = screen.displayLink(
target: self,
selector: #selector(displayLinkDidFire(_:))
)
firstTimestamp = nil
lastTimestamp = nil
frameCount = 0
displayLink = createdDisplayLink
createdDisplayLink.add(to: .main, forMode: .common)
}
func stop() {
displayLink?.invalidate()
displayLink = nil
firstTimestamp = nil
lastTimestamp = nil
frameCount = 0
}
@objc private func displayLinkDidFire(_ sender: CADisplayLink) {
if firstTimestamp == nil {
firstTimestamp = sender.timestamp
}
lastTimestamp = sender.timestamp
frameCount += 1
}
func takeFramesPerSecond() -> Double? {
guard let firstTimestamp,
let lastTimestamp,
lastTimestamp > firstTimestamp,
frameCount > 1
else {
return nil
}
let elapsed = lastTimestamp - firstTimestamp
guard elapsed > 0 else { return nil }
let fps = Double(frameCount - 1) / elapsed
self.firstTimestamp = lastTimestamp
self.lastTimestamp = lastTimestamp
frameCount = 1
return fps
}
}
private final class SystemANEUtilizationSampler: @unchecked Sendable {
private let queue = DispatchQueue(
label: "dev.local.Nativ.system-monitor.ane",
qos: .utility
)
private var services: [io_service_t] = []
private var timer: DispatchSourceTimer?
private var sampleCount = 0
private var busySampleCount = 0
func start() {
queue.sync {
guard timer == nil else { return }
let serviceClasses = [
"H1xANELoadBalancer",
"H11ANEIn",
"AppleT6031ANEHAL",
]
services = serviceClasses.compactMap { className in
guard let matching = IOServiceMatching(className) else { return nil }
let service = IOServiceGetMatchingService(kIOMainPortDefault, matching)
return service == IO_OBJECT_NULL ? nil : service
}
guard !services.isEmpty else { return }
sampleCount = 0
busySampleCount = 0
let source = DispatchSource.makeTimerSource(queue: queue)
source.schedule(
deadline: .now(),
repeating: .milliseconds(10),
leeway: .milliseconds(2)
)
source.setEventHandler { [weak self] in
self?.sampleBusyState()
}
timer = source
source.resume()
}
}
func stop() {
queue.sync {
timer?.setEventHandler {}
timer?.cancel()
timer = nil
services.forEach { IOObjectRelease($0) }
services = []
sampleCount = 0
busySampleCount = 0
}
}
func takeUtilization() -> Double? {
queue.sync {
guard !services.isEmpty, sampleCount > 0 else { return nil }
let utilization = Double(busySampleCount) / Double(sampleCount)
sampleCount = 0
busySampleCount = 0
return min(max(utilization, 0), 1)
}
}
private func sampleBusyState() {
sampleCount += 1
for service in services {
var busyState: UInt32 = 0
if IOServiceGetBusyState(service, &busyState) == KERN_SUCCESS,
busyState > 0 {
busySampleCount += 1
return
}
}
}
}
private actor SystemMetricsCollector {
private var identity: SystemMonitorIdentity?
private var previousCPUTicks: [SystemCPUTicks] = []
private var previousDiskCounters: SystemDiskCounters?
private var previousDiskSampleDate: Date?
/// Holds the IOReport subscription and SMC connection open across samples.
private let sensors = SystemSensorSampler()
func collect() -> SystemMonitorSnapshot {
let now = Date()
let resolvedIdentity: SystemMonitorIdentity
if let identity {
resolvedIdentity = identity
} else {
let capturedIdentity = Self.captureIdentity()
identity = capturedIdentity
resolvedIdentity = capturedIdentity
}
let ticks = Self.cpuTicks()
let cpu = Self.cpuMetrics(current: ticks, previous: previousCPUTicks)
previousCPUTicks = ticks
let counters = Self.diskCounters()
let disk = Self.diskMetrics(
current: counters,
previous: previousDiskCounters,
elapsed: previousDiskSampleDate.map { now.timeIntervalSince($0) }
)
previousDiskCounters = counters
previousDiskSampleDate = now
return SystemMonitorSnapshot(
recordedAt: now,
identity: resolvedIdentity,
cpu: cpu,
gpu: Self.gpuMetrics(),
memory: Self.memoryMetrics(),
disk: disk,
thermal: sensors.thermalMetrics(),
power: sensors.powerMetrics(),
uptime: ProcessInfo.processInfo.systemUptime
)
}
private static func captureIdentity() -> SystemMonitorIdentity {
var identity = SystemMonitorIdentity()
identity.modelIdentifier = sysctlString("hw.model") ?? identity.modelIdentifier
identity.chipName = sysctlString("machdep.cpu.brand_string") ?? identity.chipName
identity.physicalCoreCount = sysctlInteger("hw.physicalcpu")
?? identity.physicalCoreCount
identity.logicalCoreCount = sysctlInteger("hw.logicalcpu")
?? identity.logicalCoreCount
identity.performanceCoreCount = sysctlInteger("hw.perflevel0.physicalcpu") ?? 0
identity.efficiencyCoreCount = sysctlInteger("hw.perflevel1.physicalcpu") ?? 0
identity.nominalCPUFrequencyHz = sysctlInteger("hw.cpufrequency_max").map(UInt64.init)
identity.serialNumber = platformSerialNumber() ?? identity.serialNumber
identity.enclosureColorCode = mobileGestaltString(
for: "DeviceEnclosureColor"
)
if let profile = hardwareProfile() {
identity.computerName = profile["machine_name"] as? String
?? identity.computerName
identity.modelNumber = profile["model_number"] as? String
identity.serialNumber = profile["serial_number"] as? String
?? identity.serialNumber
}
identity.productionYear = productionYear(modelIdentifier: identity.modelIdentifier)
if let device = MTLCreateSystemDefaultDevice() {
identity.gpuName = device.name
}
if let gpuConfiguration = gpuProperty("GPUConfigurationVariable") as? NSDictionary {
identity.gpuCoreCount = number(gpuConfiguration["num_cores"]).map(Int.init)
}
if let aneProperties = registryProperty(
serviceClass: "H11ANEIn",
key: "DeviceProperties"
) as? NSDictionary {
identity.aneCoreCount = number(
aneProperties["ANEDevicePropertyNumANECores"]
).map(Int.init)
}
let version = ProcessInfo.processInfo.operatingSystemVersion
identity.operatingSystem = [
"\(version.majorVersion)",
"\(version.minorVersion)",
version.patchVersion > 0 ? "\(version.patchVersion)" : nil,
]
.compactMap { $0 }
.joined(separator: ".")
.withPrefix("macOS ")
if let screen = NSScreen.main {
identity.displayName = screen.localizedName
if let screenNumber = screen.deviceDescription[
NSDeviceDescriptionKey("NSScreenNumber")
] as? NSNumber,
let mode = CGDisplayCopyDisplayMode(CGDirectDisplayID(screenNumber.uint32Value)) {
identity.displayResolution = "\(mode.pixelWidth) × \(mode.pixelHeight)"
if mode.refreshRate > 0 {
identity.displayRefreshRate = mode.refreshRate
}
}
}
identity.disk = diskIdentity()
return identity
}
private static func cpuTicks() -> [SystemCPUTicks] {
var processorCount: natural_t = 0
var processorInfo: processor_info_array_t?
var processorInfoCount: mach_msg_type_number_t = 0
let result = host_processor_info(
mach_host_self(),
PROCESSOR_CPU_LOAD_INFO,
&processorCount,
&processorInfo,
&processorInfoCount
)
guard result == KERN_SUCCESS, let processorInfo else { return [] }
defer {
vm_deallocate(
mach_task_self_,
vm_address_t(UInt(bitPattern: processorInfo)),
vm_size_t(processorInfoCount) * vm_size_t(MemoryLayout<integer_t>.stride)
)
}
return (0..<Int(processorCount)).map { index in
let offset = index * Int(CPU_STATE_MAX)
return SystemCPUTicks(
user: UInt64(
processorInfo[offset + Int(CPU_STATE_USER)]
+ processorInfo[offset + Int(CPU_STATE_NICE)]
),
system: UInt64(processorInfo[offset + Int(CPU_STATE_SYSTEM)]),
idle: UInt64(processorInfo[offset + Int(CPU_STATE_IDLE)])
)
}
}
private static func cpuMetrics(
current: [SystemCPUTicks],
previous: [SystemCPUTicks]
) -> SystemCPUMetrics {
let deltas = current.enumerated().map { index, value in
guard previous.indices.contains(index) else { return value }
let prior = previous[index]
return SystemCPUTicks(
user: value.user >= prior.user ? value.user - prior.user : 0,
system: value.system >= prior.system ? value.system - prior.system : 0,
idle: value.idle >= prior.idle ? value.idle - prior.idle : 0
)
}
let aggregate = deltas.reduce(SystemCPUTicks(user: 0, system: 0, idle: 0)) {
SystemCPUTicks(
user: $0.user + $1.user,
system: $0.system + $1.system,
idle: $0.idle + $1.idle
)
}
let total = max(Double(aggregate.total), 1)
let loads = loadAverages()
return SystemCPUMetrics(
totalUsage: min(max(1 - (Double(aggregate.idle) / total), 0), 1),
userUsage: min(max(Double(aggregate.user) / total, 0), 1),
systemUsage: min(max(Double(aggregate.system) / total, 0), 1),
idleUsage: min(max(Double(aggregate.idle) / total, 0), 1),
coreUsage: deltas.map {
guard $0.total > 0 else { return 0 }
return min(max(1 - (Double($0.idle) / Double($0.total)), 0), 1)
},
loadAverages: loads
)
}
private static func loadAverages() -> [Double] {
var values = [Double](repeating: 0, count: 3)
let count = getloadavg(&values, Int32(values.count))
guard count > 0 else { return [0, 0, 0] }
return values
}
private static func memoryMetrics() -> SystemMemoryMetrics {
var statistics = vm_statistics64()
var count = mach_msg_type_number_t(
MemoryLayout<vm_statistics64_data_t>.stride / MemoryLayout<integer_t>.stride
)
let result = withUnsafeMutablePointer(to: &statistics) { pointer in
pointer.withMemoryRebound(to: integer_t.self, capacity: Int(count)) {
host_statistics64(mach_host_self(), HOST_VM_INFO64, $0, &count)
}
}
guard result == KERN_SUCCESS else {
return SystemMemoryMetrics(totalBytes: ProcessInfo.processInfo.physicalMemory)
}
var kernelPageSize: vm_size_t = 0
guard host_page_size(mach_host_self(), &kernelPageSize) == KERN_SUCCESS else {
return SystemMemoryMetrics(totalBytes: ProcessInfo.processInfo.physicalMemory)
}
let pageSize = UInt64(kernelPageSize)
let total = ProcessInfo.processInfo.physicalMemory
let active = UInt64(statistics.active_count) * pageSize
let wired = UInt64(statistics.wire_count) * pageSize
let compressed = UInt64(statistics.compressor_page_count) * pageSize
let cached = UInt64(statistics.inactive_count) * pageSize
let used = min(active + wired + compressed, total)
let swap = swapUsage()
return SystemMemoryMetrics(
totalBytes: total,
usedBytes: used,
activeBytes: active,
wiredBytes: wired,
compressedBytes: compressed,
cachedBytes: cached,
freeBytes: total > used ? total - used : 0,
swapUsedBytes: swap.used,
swapTotalBytes: swap.total
)
}
private static func swapUsage() -> (used: UInt64, total: UInt64) {
var usage = xsw_usage()
var size = MemoryLayout<xsw_usage>.stride
guard sysctlbyname("vm.swapusage", &usage, &size, nil, 0) == 0 else {
return (0, 0)
}
return (usage.xsu_used, usage.xsu_total)
}
private static func gpuMetrics() -> SystemGPUMetrics {
guard let statistics = gpuProperty("PerformanceStatistics") as? NSDictionary else {
return SystemGPUMetrics()
}
return SystemGPUMetrics(
deviceUsage: percentage(statistics["Device Utilization %"]),
allocatedMemoryBytes: number(statistics["Alloc system memory"])
)
}
private static func gpuProperty(_ key: String) -> Any? {
registryProperty(serviceClass: "AGXAccelerator", key: key)
}
private static func registryProperty(
serviceClass: String,
key: String
) -> Any? {
guard let matching = IOServiceMatching(serviceClass) else { return nil }
let service = IOServiceGetMatchingService(kIOMainPortDefault, matching)
guard service != IO_OBJECT_NULL else { return nil }
defer { IOObjectRelease(service) }
return IORegistryEntryCreateCFProperty(
service,
key as CFString,
kCFAllocatorDefault,
0
)?.takeRetainedValue()
}
private static func diskMetrics(
current: SystemDiskCounters,
previous: SystemDiskCounters?,
elapsed: TimeInterval?
) -> SystemDiskMetrics {
let rootURL = URL(fileURLWithPath: "/")
let values = try? rootURL.resourceValues(forKeys: [
.volumeTotalCapacityKey,
.volumeAvailableCapacityForImportantUsageKey,
.volumeAvailableCapacityKey,
])
let capacity = SystemDiskMetrics.resolvedCapacity(
total: values?.volumeTotalCapacity,
availableForImportantUsage: values?.volumeAvailableCapacityForImportantUsage,
available: values?.volumeAvailableCapacity
)
let interval = max(elapsed ?? 0, 0)
let readRate: Double
let writeRate: Double
if let previous, interval > 0 {
readRate = Double(
current.readBytes >= previous.readBytes
? current.readBytes - previous.readBytes
: 0
) / interval
writeRate = Double(
current.writeBytes >= previous.writeBytes
? current.writeBytes - previous.writeBytes
: 0
) / interval
} else {
readRate = 0
writeRate = 0
}
return SystemDiskMetrics(
totalBytes: capacity?.total,
availableBytes: capacity?.available,
readBytesPerSecond: readRate,
writeBytesPerSecond: writeRate,
cumulativeReadBytes: current.readBytes,
cumulativeWriteBytes: current.writeBytes
)
}
private static func diskCounters() -> SystemDiskCounters {
guard let matching = IOServiceMatching("IOBlockStorageDriver") else {
return SystemDiskCounters(readBytes: 0, writeBytes: 0)
}
var iterator: io_iterator_t = 0
guard IOServiceGetMatchingServices(
kIOMainPortDefault,
matching,
&iterator
) == KERN_SUCCESS else {
return SystemDiskCounters(readBytes: 0, writeBytes: 0)
}
defer { IOObjectRelease(iterator) }
var readBytes: UInt64 = 0
var writeBytes: UInt64 = 0
while case let service = IOIteratorNext(iterator), service != IO_OBJECT_NULL {
defer { IOObjectRelease(service) }
var properties: Unmanaged<CFMutableDictionary>?
guard IORegistryEntryCreateCFProperties(
service,
&properties,
kCFAllocatorDefault,
0
) == KERN_SUCCESS,
let dictionary = properties?.takeRetainedValue() as NSDictionary?,
let statistics = dictionary["Statistics"] as? NSDictionary
else {
continue
}
readBytes += number(statistics["Bytes (Read)"]) ?? 0
writeBytes += number(statistics["Bytes (Write)"]) ?? 0
}
return SystemDiskCounters(readBytes: readBytes, writeBytes: writeBytes)
}
private static func diskIdentity() -> SystemDiskIdentity {
guard let volume = diskutilInfo("/") else {
return SystemDiskIdentity()
}
let physicalStore = (volume["APFSPhysicalStores"] as? [[String: Any]])?
.first?["APFSPhysicalStore"] as? String
let physicalDisk = physicalStore.map(wholeDiskIdentifier)
let device = physicalDisk.flatMap(diskutilInfo)
let smart = (device?["SMARTDeviceSpecificKeysMayVaryNotGuaranteed"]
?? volume["SMARTDeviceSpecificKeysMayVaryNotGuaranteed"]) as? [String: Any]
let usedPercent = intValue(smart?["PERCENTAGE_USED"])
let temperatureKelvin = intValue(smart?["TEMPERATURE"])
let dataUnitBytes: UInt64 = 512_000
return SystemDiskIdentity(
volumeName: volume["VolumeName"] as? String ?? "Macintosh HD",
fileSystem: volume["FilesystemUserVisibleName"] as? String
?? volume["FilesystemType"] as? String
?? "APFS",
mountPoint: volume["MountPoint"] as? String ?? "/",
deviceIdentifier: volume["DeviceIdentifier"] as? String ?? NativFormatting.missingValue,
model: device?["MediaName"] as? String ?? "Internal storage",
connection: device?["BusProtocol"] as? String
?? volume["BusProtocol"] as? String
?? "Internal",
isEncrypted: volume["Encryption"] as? Bool,
isWritable: volume["WritableVolume"] as? Bool,
smartStatus: device?["SMARTStatus"] as? String
?? volume["SMARTStatus"] as? String,
healthPercent: usedPercent.map { max(0, 100 - $0) },
temperatureCelsius: temperatureKelvin.map { max(0, $0 - 273) },
powerCycles: uintValue(smart?["POWER_CYCLES_0"]),
powerOnHours: uintValue(smart?["POWER_ON_HOURS_0"]),
unsafeShutdowns: uintValue(smart?["UNSAFE_SHUTDOWNS_0"]),
mediaErrors: uintValue(smart?["MEDIA_ERRORS_0"]),
availableSparePercent: intValue(smart?["AVAILABLE_SPARE"]),
lifetimeReadBytes: uintValue(smart?["DATA_UNITS_READ_0"]).map {
$0.multipliedReportingOverflow(by: dataUnitBytes).partialValue
},
lifetimeWrittenBytes: uintValue(smart?["DATA_UNITS_WRITTEN_0"]).map {
$0.multipliedReportingOverflow(by: dataUnitBytes).partialValue
}
)
}
private static func diskutilInfo(_ target: String) -> [String: Any]? {
let process = Process()
let output = Pipe()
process.executableURL = URL(fileURLWithPath: "/usr/sbin/diskutil")
process.arguments = ["info", "-plist", target]
process.standardOutput = output
process.standardError = Pipe()
do {
try process.run()
process.waitUntilExit()
} catch {
return nil
}
guard process.terminationStatus == 0 else { return nil }
let data = output.fileHandleForReading.readDataToEndOfFile()
return (try? PropertyListSerialization.propertyList(
from: data,
options: [],
format: nil
)) as? [String: Any]
}
private static func hardwareProfile() -> [String: Any]? {
let process = Process()
let output = Pipe()
process.executableURL = URL(fileURLWithPath: "/usr/sbin/system_profiler")
process.arguments = ["SPHardwareDataType", "-json"]
process.standardOutput = output
process.standardError = Pipe()
do {
try process.run()
process.waitUntilExit()
} catch {
return nil
}
guard process.terminationStatus == 0 else { return nil }
let data = output.fileHandleForReading.readDataToEndOfFile()
guard let object = try? JSONSerialization.jsonObject(with: data),
let root = object as? [String: Any],
let entries = root["SPHardwareDataType"] as? [[String: Any]]
else {
return nil
}
return entries.first
}
private static func productionYear(modelIdentifier: String) -> Int? {
let exactModelYears: [String: Int] = [
"Mac15,3": 2023,
"Mac15,4": 2023,
"Mac15,5": 2023,
"Mac15,6": 2023,
"Mac15,7": 2023,
"Mac15,8": 2023,
"Mac15,9": 2023,
"Mac15,10": 2023,
"Mac15,11": 2023,
"Mac15,12": 2024,
"Mac15,13": 2024,
]
if let year = exactModelYears[modelIdentifier] {
return year
}
return nil
}
private static func wholeDiskIdentifier(_ identifier: String) -> String {
let partitionSuffix = identifier.dropFirst(identifier.hasPrefix("disk") ? 4 : 0)
guard let separator = partitionSuffix.firstIndex(of: "s") else {
return identifier
}
return String(identifier[..<separator])
}
private static func platformSerialNumber() -> String? {
guard let matching = IOServiceMatching("IOPlatformExpertDevice") else {
return nil
}
let service = IOServiceGetMatchingService(kIOMainPortDefault, matching)
guard service != IO_OBJECT_NULL else { return nil }
defer { IOObjectRelease(service) }
guard let value = IORegistryEntryCreateCFProperty(
service,
"IOPlatformSerialNumber" as CFString,
kCFAllocatorDefault,
0
)?.takeRetainedValue() as? String else {
return nil
}
return value
}
private static func mobileGestaltString(for key: String) -> String? {