Compare commits

..
Author SHA1 Message Date
gronod f59ee440af feat(telemetry): implement real-time disk I/O throughput and IOPS provider (fixes #10)
MacMonitor CI/CD Pipeline / Build & Test (Intel x86_64) (push) Canceled after 0s
2026-09-08 12:34:25 +01:00
gronod 7046777fa9 Merge branch 'feat/7-system-load' into milestone/m3-advanced-telemetry
MacMonitor CI/CD Pipeline / Build & Test (Intel x86_64) (push) Canceled after 0s
2026-09-08 12:33:20 +01:00
gronod 66401bec28 feat(telemetry): implement load average and thread concurrency provider (fixes #7)
MacMonitor CI/CD Pipeline / Build & Test (Intel x86_64) (push) Canceled after 0s
2026-09-08 12:33:14 +01:00
gronod 76cb48be09 Merge branch 'feat/6-kernel-counters' into milestone/m3-advanced-telemetry
MacMonitor CI/CD Pipeline / Build & Test (Intel x86_64) (push) Canceled after 0s
2026-09-08 12:32:22 +01:00
7 changed files with 461 additions and 0 deletions
@@ -20,5 +20,7 @@
#import "MMComponentThermalProvider.h"
#import "MMPowerTelemetryProvider.h"
#import "MMKernelTelemetryProvider.h"
#import "MMLoadAverageProvider.h"
#import "MMDiskIOProvider.h"
#endif /* MacMonitor_Bridging_Header_h */
@@ -0,0 +1,29 @@
#ifndef MMDiskIOProvider_h
#define MMDiskIOProvider_h
#import <Foundation/Foundation.h>
#import "MMTelemetryProvider.h"
NS_ASSUME_NONNULL_BEGIN
/**
* MMDiskIOProvider
* Samples real-time storage disk transfer rates (read/write bytes per second)
* and transaction rates (read/write IOPS) across internal and external block storage devices.
*/
@interface MMDiskIOProvider : NSObject <MMTelemetryProvider>
- (instancetype)init;
/**
* Pure calculator method for deterministic unit testing.
*/
+ (NSDictionary<NSString *, id> *)calculateDiskIOMetricsWithCurrentSnapshots:(NSDictionary<NSString *, NSDictionary<NSString *, NSNumber *> *> *)current
previousSnapshots:(nullable NSDictionary<NSString *, NSDictionary<NSString *, NSNumber *> *> *)previous
timeDelta:(NSTimeInterval)timeDelta;
@end
NS_ASSUME_NONNULL_END
#endif /* MMDiskIOProvider_h */
@@ -0,0 +1,170 @@
#import "MMDiskIOProvider.h"
#import <IOKit/IOKitLib.h>
#import <IOKit/storage/IOBlockStorageDriver.h>
#import <mach/mach_time.h>
#import <os/lock.h>
@interface MMDiskIOProvider () {
os_unfair_lock _lock;
NSDictionary<NSString *, NSDictionary<NSString *, NSNumber *> *> *_previousSnapshots;
uint64_t _previousTimestamp;
mach_timebase_info_data_t _timebase;
}
@end
@implementation MMDiskIOProvider
- (instancetype)init {
self = [super init];
if (self) {
_lock = OS_UNFAIR_LOCK_INIT;
_previousSnapshots = nil;
_previousTimestamp = 0;
mach_timebase_info(&_timebase);
}
return self;
}
- (MMTelemetryDomain)domain {
return MMTelemetryDomainStorage;
}
- (NSString *)providerIdentifier {
return @"com.i3omb.macmonitor.telemetry.storage.io";
}
- (BOOL)isAvailable {
return YES;
}
+ (NSDictionary<NSString *, id> *)calculateDiskIOMetricsWithCurrentSnapshots:(NSDictionary<NSString *, NSDictionary<NSString *, NSNumber *> *> *)current
previousSnapshots:(nullable NSDictionary<NSString *, NSDictionary<NSString *, NSNumber *> *> *)previous
timeDelta:(NSTimeInterval)timeDelta {
double totalReadBps = 0.0;
double totalWriteBps = 0.0;
double totalReadIOPS = 0.0;
double totalWriteIOPS = 0.0;
NSMutableArray<NSDictionary<NSString *, id> *> *disks = [NSMutableArray arrayWithCapacity:current.count];
NSArray<NSString *> *sortedBsdNames = [current.allKeys sortedArrayUsingSelector:@selector(compare:)];
for (NSString *bsdName in sortedBsdNames) {
NSDictionary<NSString *, NSNumber *> *curr = current[bsdName];
NSDictionary<NSString *, NSNumber *> *prev = previous ? previous[bsdName] : nil;
uint64_t currReadBytes = [curr[@"readBytes"] unsignedLongLongValue];
uint64_t currWriteBytes = [curr[@"writeBytes"] unsignedLongLongValue];
uint64_t currReadOps = [curr[@"readOps"] unsignedLongLongValue];
uint64_t currWriteOps = [curr[@"writeOps"] unsignedLongLongValue];
uint64_t prevReadBytes = prev ? [prev[@"readBytes"] unsignedLongLongValue] : currReadBytes;
uint64_t prevWriteBytes = prev ? [prev[@"writeBytes"] unsignedLongLongValue] : currWriteBytes;
uint64_t prevReadOps = prev ? [prev[@"readOps"] unsignedLongLongValue] : currReadOps;
uint64_t prevWriteOps = prev ? [prev[@"writeOps"] unsignedLongLongValue] : currWriteOps;
double deltaReadBytes = (currReadBytes >= prevReadBytes) ? (double)(currReadBytes - prevReadBytes) : 0.0;
double deltaWriteBytes = (currWriteBytes >= prevWriteBytes) ? (double)(currWriteBytes - prevWriteBytes) : 0.0;
double deltaReadOps = (currReadOps >= prevReadOps) ? (double)(currReadOps - prevReadOps) : 0.0;
double deltaWriteOps = (currWriteOps >= prevWriteOps) ? (double)(currWriteOps - prevWriteOps) : 0.0;
double readBps = (timeDelta > 0.0001) ? (deltaReadBytes / timeDelta) : 0.0;
double writeBps = (timeDelta > 0.0001) ? (deltaWriteBytes / timeDelta) : 0.0;
double readIOPS = (timeDelta > 0.0001) ? (deltaReadOps / timeDelta) : 0.0;
double writeIOPS = (timeDelta > 0.0001) ? (deltaWriteOps / timeDelta) : 0.0;
totalReadBps += readBps;
totalWriteBps += writeBps;
totalReadIOPS += readIOPS;
totalWriteIOPS += writeIOPS;
[disks addObject:@{
@"bsdName": bsdName,
@"readBytesPerSec": @(readBps),
@"writeBytesPerSec": @(writeBps),
@"readIOPS": @(readIOPS),
@"writeIOPS": @(writeIOPS),
@"cumulativeReadBytes": @(currReadBytes),
@"cumulativeWriteBytes": @(currWriteBytes),
@"cumulativeReadOps": @(currReadOps),
@"cumulativeWriteOps": @(currWriteOps)
}];
}
return @{
@"disks": disks,
@"totalReadBytesPerSec": @(totalReadBps),
@"totalWriteBytesPerSec": @(totalWriteBps),
@"totalReadIOPS": @(totalReadIOPS),
@"totalWriteIOPS": @(totalWriteIOPS),
@"timeDelta": @(timeDelta)
};
}
- (nullable NSDictionary<NSString *, id> *)sampleTelemetryWithError:(NSError **)error {
uint64_t now = mach_absolute_time();
NSMutableDictionary<NSString *, NSDictionary<NSString *, NSNumber *> *> *currentSnapshots = [NSMutableDictionary dictionary];
CFMutableDictionaryRef matching = IOServiceMatching(kIOBlockStorageDriverClass);
io_iterator_t iterator = IO_OBJECT_NULL;
if (IOServiceGetMatchingServices(kIOMainPortDefault, matching, &iterator) == KERN_SUCCESS && iterator != IO_OBJECT_NULL) {
io_registry_entry_t entry;
while ((entry = IOIteratorNext(iterator)) != IO_OBJECT_NULL) {
NSString *bsdName = nil;
io_iterator_t childIterator;
if (IORegistryEntryGetChildIterator(entry, kIOServicePlane, &childIterator) == KERN_SUCCESS) {
io_registry_entry_t child;
while ((child = IOIteratorNext(childIterator)) != IO_OBJECT_NULL) {
CFTypeRef nameRef = IORegistryEntryCreateCFProperty(child, CFSTR("BSD Name"), kCFAllocatorDefault, 0);
if (nameRef) {
bsdName = CFBridgingRelease(nameRef);
IOObjectRelease(child);
break;
}
IOObjectRelease(child);
}
IOObjectRelease(childIterator);
}
if (bsdName) {
CFTypeRef statsRef = IORegistryEntryCreateCFProperty(entry, CFSTR("Statistics"), kCFAllocatorDefault, 0);
if (statsRef) {
NSDictionary *stats = CFBridgingRelease(statsRef);
NSNumber *readBytes = stats[@"Bytes (Read)"] ?: @0;
NSNumber *writeBytes = stats[@"Bytes (Write)"] ?: @0;
NSNumber *readOps = stats[@"Operations (Read)"] ?: @0;
NSNumber *writeOps = stats[@"Operations (Write)"] ?: @0;
currentSnapshots[bsdName] = @{
@"readBytes": readBytes,
@"writeBytes": writeBytes,
@"readOps": readOps,
@"writeOps": writeOps
};
}
}
IOObjectRelease(entry);
}
IOObjectRelease(iterator);
}
os_unfair_lock_lock(&_lock);
NSDictionary<NSString *, NSDictionary<NSString *, NSNumber *> *> *prev = _previousSnapshots;
uint64_t prevTime = _previousTimestamp;
_previousSnapshots = currentSnapshots;
_previousTimestamp = now;
os_unfair_lock_unlock(&_lock);
NSTimeInterval timeDelta = 1.0;
if (prevTime > 0) {
uint64_t elapsed = now - prevTime;
timeDelta = (double)elapsed * _timebase.numer / _timebase.denom / 1e9;
}
return [MMDiskIOProvider calculateDiskIOMetricsWithCurrentSnapshots:currentSnapshots
previousSnapshots:prev
timeDelta:timeDelta];
}
@end
@@ -0,0 +1,33 @@
#ifndef MMLoadAverageProvider_h
#define MMLoadAverageProvider_h
#import <Foundation/Foundation.h>
#import "MMTelemetryProvider.h"
NS_ASSUME_NONNULL_BEGIN
/**
* MMLoadAverageProvider
* Samples 1m, 5m, and 15m system load averages, Mach concurrency factors,
* and system-wide task and thread counts.
*/
@interface MMLoadAverageProvider : NSObject <MMTelemetryProvider>
- (instancetype)init;
/**
* Pure calculator method for deterministic unit testing.
*/
+ (NSDictionary<NSString *, id> *)calculateLoadMetricsWithLoad1:(double)load1
load5:(double)load5
load15:(double)load15
taskCount:(int)taskCount
threadCount:(int)threadCount
cpuCount:(int)cpuCount
machFactor:(double)machFactor;
@end
NS_ASSUME_NONNULL_END
#endif /* MMLoadAverageProvider_h */
@@ -0,0 +1,92 @@
#import "MMLoadAverageProvider.h"
#import <mach/mach.h>
#import <mach/processor_info.h>
#import <sys/sysctl.h>
#import <stdlib.h>
@implementation MMLoadAverageProvider
- (instancetype)init {
self = [super init];
return self;
}
- (MMTelemetryDomain)domain {
return MMTelemetryDomainSystem;
}
- (NSString *)providerIdentifier {
return @"com.i3omb.macmonitor.telemetry.system.load";
}
- (BOOL)isAvailable {
return YES;
}
+ (NSDictionary<NSString *, id> *)calculateLoadMetricsWithLoad1:(double)load1
load5:(double)load5
load15:(double)load15
taskCount:(int)taskCount
threadCount:(int)threadCount
cpuCount:(int)cpuCount
machFactor:(double)machFactor {
int safeCpus = cpuCount > 0 ? cpuCount : 1;
double norm1 = load1 / (double)safeCpus;
double norm5 = load5 / (double)safeCpus;
double norm15 = load15 / (double)safeCpus;
return @{
@"load1m": @(load1),
@"load5m": @(load5),
@"load15m": @(load15),
@"normalizedLoad1m": @(norm1),
@"normalizedLoad5m": @(norm5),
@"normalizedLoad15m": @(norm15),
@"taskCount": @(taskCount),
@"threadCount": @(threadCount),
@"logicalCpuCount": @(safeCpus),
@"machFactor": @(machFactor),
@"isOverloaded": @(norm1 > 1.0)
};
}
- (nullable NSDictionary<NSString *, id> *)sampleTelemetryWithError:(NSError **)error {
// 1. Get BSD load averages
double load[3] = {0.0, 0.0, 0.0};
int ret = getloadavg(load, 3);
if (ret <= 0) {
load[0] = 0.0;
load[1] = 0.0;
load[2] = 0.0;
}
// 2. Query Mach processor set for task & thread counts and mach factor
mach_port_t host = mach_host_self();
processor_set_name_port_t pset = MACH_PORT_NULL;
processor_set_load_info_data_t loadInfo = {0};
mach_msg_type_number_t count = PROCESSOR_SET_LOAD_INFO_COUNT;
kern_return_t kr = processor_set_default(host, &pset);
if (kr == KERN_SUCCESS && MACH_PORT_VALID(pset)) {
kr = processor_set_statistics(pset, PROCESSOR_SET_LOAD_INFO, (processor_set_info_t)&loadInfo, &count);
mach_port_deallocate(mach_task_self(), pset);
}
double machFactor = (double)loadInfo.mach_factor / (double)LOAD_SCALE;
// 3. Query logical CPU core count
int cpuCount = 1;
size_t size = sizeof(cpuCount);
sysctlbyname("hw.logicalcpu", &cpuCount, &size, NULL, 0);
if (cpuCount <= 0) cpuCount = 1;
return [MMLoadAverageProvider calculateLoadMetricsWithLoad1:load[0]
load5:load[1]
load15:load[2]
taskCount:loadInfo.task_count
threadCount:loadInfo.thread_count
cpuCount:cpuCount
machFactor:machFactor];
}
@end
+73
View File
@@ -0,0 +1,73 @@
import XCTest
@testable import MacMonitor
final class MMDiskIOTests: XCTestCase {
func testDiskIOMetricsCalculation() {
let prev: [String: [String: NSNumber]] = [
"disk0": [
"readBytes": NSNumber(value: 10_000_000),
"writeBytes": NSNumber(value: 5_000_000),
"readOps": NSNumber(value: 1_000),
"writeOps": NSNumber(value: 500)
],
"disk1": [
"readBytes": NSNumber(value: 2_000_000),
"writeBytes": NSNumber(value: 1_000_000),
"readOps": NSNumber(value: 200),
"writeOps": NSNumber(value: 100)
]
]
let curr: [String: [String: NSNumber]] = [
"disk0": [
"readBytes": NSNumber(value: 20_000_000), // delta = 10,000,000 bytes
"writeBytes": NSNumber(value: 7_000_000), // delta = 2,000,000 bytes
"readOps": NSNumber(value: 1_200), // delta = 200 ops
"writeOps": NSNumber(value: 600) // delta = 100 ops
],
"disk1": [
"readBytes": NSNumber(value: 4_000_000), // delta = 2,000,000 bytes
"writeBytes": NSNumber(value: 1_000_000), // delta = 0
"readOps": NSNumber(value: 250), // delta = 50 ops
"writeOps": NSNumber(value: 100) // delta = 0 ops
]
]
let timeDelta: TimeInterval = 2.0 // 2 seconds
let metrics = MMDiskIOProvider.calculateDiskIOMetrics(
withCurrentSnapshots: curr,
previousSnapshots: prev,
timeDelta: timeDelta
)
let totalReadBps = metrics["totalReadBytesPerSec"] as? Double ?? 0
let totalWriteBps = metrics["totalWriteBytesPerSec"] as? Double ?? 0
let totalReadIOPS = metrics["totalReadIOPS"] as? Double ?? 0
let totalWriteIOPS = metrics["totalWriteIOPS"] as? Double ?? 0
let disks = metrics["disks"] as? [[String: Any]] ?? []
// (10MB + 2MB) / 2s = 6,000,000 B/s
XCTAssertEqual(totalReadBps, 6_000_000.0, accuracy: 1.0)
// (2MB + 0) / 2s = 1,000,000 B/s
XCTAssertEqual(totalWriteBps, 1_000_000.0, accuracy: 1.0)
// (200 + 50) / 2s = 125 IOPS
XCTAssertEqual(totalReadIOPS, 125.0, accuracy: 0.1)
// (100 + 0) / 2s = 50 IOPS
XCTAssertEqual(totalWriteIOPS, 50.0, accuracy: 0.1)
XCTAssertEqual(disks.count, 2)
}
func testLiveDiskIOProvider() throws {
let provider = MMDiskIOProvider()
XCTAssertEqual(provider.domain, .storage)
XCTAssertEqual(provider.providerIdentifier, "com.i3omb.macmonitor.telemetry.storage.io")
let sample = try provider.sampleTelemetry()
XCTAssertNotNil(sample)
XCTAssertNotNil(sample["totalReadBytesPerSec"])
XCTAssertNotNil(sample["totalWriteBytesPerSec"])
XCTAssertNotNil(sample["disks"])
}
}
+62
View File
@@ -0,0 +1,62 @@
import XCTest
@testable import MacMonitor
final class MMLoadAverageTests: XCTestCase {
func testLoadMetricsCalculation() {
let metrics = MMLoadAverageProvider.calculateLoadMetrics(
withLoad1: 4.0,
load5: 3.5,
load15: 2.5,
taskCount: 500,
threadCount: 2200,
cpuCount: 8,
machFactor: 1.25
)
let load1 = metrics["load1m"] as? Double ?? 0
let norm1 = metrics["normalizedLoad1m"] as? Double ?? 0
let norm5 = metrics["normalizedLoad5m"] as? Double ?? 0
let taskCount = metrics["taskCount"] as? Int ?? 0
let threadCount = metrics["threadCount"] as? Int ?? 0
let isOverloaded = metrics["isOverloaded"] as? Bool ?? true
XCTAssertEqual(load1, 4.0, accuracy: 0.01)
XCTAssertEqual(norm1, 4.0 / 8.0, accuracy: 0.01)
XCTAssertEqual(norm5, 3.5 / 8.0, accuracy: 0.01)
XCTAssertEqual(taskCount, 500)
XCTAssertEqual(threadCount, 2200)
XCTAssertFalse(isOverloaded)
}
func testOverloadedStateDetection() {
let metrics = MMLoadAverageProvider.calculateLoadMetrics(
withLoad1: 12.0,
load5: 10.0,
load15: 8.0,
taskCount: 650,
threadCount: 3100,
cpuCount: 8,
machFactor: 0.4
)
let isOverloaded = metrics["isOverloaded"] as? Bool ?? false
let norm1 = metrics["normalizedLoad1m"] as? Double ?? 0
XCTAssertTrue(isOverloaded)
XCTAssertEqual(norm1, 1.5, accuracy: 0.01)
}
func testLiveLoadAverageProvider() throws {
let provider = MMLoadAverageProvider()
XCTAssertEqual(provider.domain, .system)
XCTAssertEqual(provider.providerIdentifier, "com.i3omb.macmonitor.telemetry.system.load")
let sample = try provider.sampleTelemetry()
XCTAssertNotNil(sample)
XCTAssertNotNil(sample["load1m"])
XCTAssertNotNil(sample["taskCount"])
XCTAssertNotNil(sample["threadCount"])
XCTAssertNotNil(sample["normalizedLoad1m"])
}
}