Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5b06749094 | ||
|
|
0bc6c0a483 | ||
|
|
0aaa9d0110 | ||
|
|
54b6e6a7f8 | ||
|
|
f59ee440af | ||
|
|
7046777fa9 |
@@ -21,5 +21,8 @@
|
||||
#import "MMPowerTelemetryProvider.h"
|
||||
#import "MMKernelTelemetryProvider.h"
|
||||
#import "MMLoadAverageProvider.h"
|
||||
#import "MMDiskIOProvider.h"
|
||||
#import "MMNetworkBandwidthProvider.h"
|
||||
#import "MMNetworkSocketsProvider.h"
|
||||
|
||||
#endif /* MacMonitor_Bridging_Header_h */
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
#ifndef MMNetworkBandwidthProvider_h
|
||||
#define MMNetworkBandwidthProvider_h
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "MMTelemetryProvider.h"
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
/**
|
||||
* MMNetworkBandwidthProvider
|
||||
* Samples real-time network download and upload throughput, packets/sec, and error counts
|
||||
* across physical (Wi-Fi, Ethernet) and virtual (VPN, bridge) network interfaces.
|
||||
*/
|
||||
@interface MMNetworkBandwidthProvider : NSObject <MMTelemetryProvider>
|
||||
|
||||
- (instancetype)init;
|
||||
|
||||
/**
|
||||
* Pure calculator method for deterministic unit testing.
|
||||
*/
|
||||
+ (NSDictionary<NSString *, id> *)calculateBandwidthMetricsWithCurrentSnapshots:(NSDictionary<NSString *, NSDictionary<NSString *, NSNumber *> *> *)current
|
||||
previousSnapshots:(nullable NSDictionary<NSString *, NSDictionary<NSString *, NSNumber *> *> *)previous
|
||||
timeDelta:(NSTimeInterval)timeDelta
|
||||
ipAddresses:(nullable NSDictionary<NSString *, NSString *> *)ipAddresses;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
|
||||
#endif /* MMNetworkBandwidthProvider_h */
|
||||
@@ -0,0 +1,211 @@
|
||||
#import "MMNetworkBandwidthProvider.h"
|
||||
#import <sys/sysctl.h>
|
||||
#import <net/if.h>
|
||||
#import <net/if_dl.h>
|
||||
#import <net/route.h>
|
||||
#import <ifaddrs.h>
|
||||
#import <arpa/inet.h>
|
||||
#import <mach/mach_time.h>
|
||||
#import <os/lock.h>
|
||||
|
||||
@interface MMNetworkBandwidthProvider () {
|
||||
os_unfair_lock _lock;
|
||||
NSDictionary<NSString *, NSDictionary<NSString *, NSNumber *> *> *_previousSnapshots;
|
||||
uint64_t _previousTimestamp;
|
||||
mach_timebase_info_data_t _timebase;
|
||||
}
|
||||
@end
|
||||
|
||||
@implementation MMNetworkBandwidthProvider
|
||||
|
||||
- (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 MMTelemetryDomainNetwork;
|
||||
}
|
||||
|
||||
- (NSString *)providerIdentifier {
|
||||
return @"com.i3omb.macmonitor.telemetry.network.bandwidth";
|
||||
}
|
||||
|
||||
- (BOOL)isAvailable {
|
||||
return YES;
|
||||
}
|
||||
|
||||
+ (NSDictionary<NSString *, id> *)calculateBandwidthMetricsWithCurrentSnapshots:(NSDictionary<NSString *, NSDictionary<NSString *, NSNumber *> *> *)current
|
||||
previousSnapshots:(nullable NSDictionary<NSString *, NSDictionary<NSString *, NSNumber *> *> *)previous
|
||||
timeDelta:(NSTimeInterval)timeDelta
|
||||
ipAddresses:(nullable NSDictionary<NSString *, NSString *> *)ipAddresses {
|
||||
double totalDownBps = 0.0;
|
||||
double totalUpBps = 0.0;
|
||||
double totalDownPps = 0.0;
|
||||
double totalUpPps = 0.0;
|
||||
|
||||
NSMutableArray<NSDictionary<NSString *, id> *> *interfaces = [NSMutableArray arrayWithCapacity:current.count];
|
||||
NSArray<NSString *> *sortedNames = [current.allKeys sortedArrayUsingSelector:@selector(compare:)];
|
||||
|
||||
NSString *primaryInterface = @"";
|
||||
double maxActivity = -1.0;
|
||||
|
||||
for (NSString *name in sortedNames) {
|
||||
// Skip loopback for aggregate statistics
|
||||
BOOL isLoopback = [name hasPrefix:@"lo"];
|
||||
|
||||
NSDictionary<NSString *, NSNumber *> *curr = current[name];
|
||||
NSDictionary<NSString *, NSNumber *> *prev = previous ? previous[name] : nil;
|
||||
|
||||
uint64_t currInBytes = [curr[@"inBytes"] unsignedLongLongValue];
|
||||
uint64_t currOutBytes = [curr[@"outBytes"] unsignedLongLongValue];
|
||||
uint64_t currInPackets = [curr[@"inPackets"] unsignedLongLongValue];
|
||||
uint64_t currOutPackets = [curr[@"outPackets"] unsignedLongLongValue];
|
||||
uint64_t inErrors = [curr[@"inErrors"] unsignedLongLongValue];
|
||||
uint64_t outErrors = [curr[@"outErrors"] unsignedLongLongValue];
|
||||
|
||||
uint64_t prevInBytes = prev ? [prev[@"inBytes"] unsignedLongLongValue] : currInBytes;
|
||||
uint64_t prevOutBytes = prev ? [prev[@"outBytes"] unsignedLongLongValue] : currOutBytes;
|
||||
uint64_t prevInPackets = prev ? [prev[@"inPackets"] unsignedLongLongValue] : currInPackets;
|
||||
uint64_t prevOutPackets = prev ? [prev[@"outPackets"] unsignedLongLongValue] : currOutPackets;
|
||||
|
||||
double deltaInBytes = (currInBytes >= prevInBytes) ? (double)(currInBytes - prevInBytes) : 0.0;
|
||||
double deltaOutBytes = (currOutBytes >= prevOutBytes) ? (double)(currOutBytes - prevOutBytes) : 0.0;
|
||||
double deltaInPackets = (currInPackets >= prevInPackets) ? (double)(currInPackets - prevInPackets) : 0.0;
|
||||
double deltaOutPackets = (currOutPackets >= prevOutPackets) ? (double)(currOutPackets - prevOutPackets) : 0.0;
|
||||
|
||||
double downBps = (timeDelta > 0.0001) ? (deltaInBytes / timeDelta) : 0.0;
|
||||
double upBps = (timeDelta > 0.0001) ? (deltaOutBytes / timeDelta) : 0.0;
|
||||
double downPps = (timeDelta > 0.0001) ? (deltaInPackets / timeDelta) : 0.0;
|
||||
double upPps = (timeDelta > 0.0001) ? (deltaOutPackets / timeDelta) : 0.0;
|
||||
|
||||
if (!isLoopback) {
|
||||
totalDownBps += downBps;
|
||||
totalUpBps += upBps;
|
||||
totalDownPps += downPps;
|
||||
totalUpPps += upPps;
|
||||
|
||||
double activity = downBps + upBps;
|
||||
if (activity > maxActivity) {
|
||||
maxActivity = activity;
|
||||
primaryInterface = name;
|
||||
}
|
||||
}
|
||||
|
||||
NSString *ip = ipAddresses[name] ?: @"";
|
||||
|
||||
[interfaces addObject:@{
|
||||
@"name": name,
|
||||
@"downloadBytesPerSec": @(downBps),
|
||||
@"uploadBytesPerSec": @(upBps),
|
||||
@"downloadPacketsPerSec": @(downPps),
|
||||
@"uploadPacketsPerSec": @(upPps),
|
||||
@"cumulativeInBytes": @(currInBytes),
|
||||
@"cumulativeOutBytes": @(currOutBytes),
|
||||
@"cumulativeInPackets": @(currInPackets),
|
||||
@"cumulativeOutPackets": @(currOutPackets),
|
||||
@"inErrors": @(inErrors),
|
||||
@"outErrors": @(outErrors),
|
||||
@"ipv4Address": ip,
|
||||
@"isLoopback": @(isLoopback)
|
||||
}];
|
||||
}
|
||||
|
||||
if (primaryInterface.length == 0 && current[@"en0"]) {
|
||||
primaryInterface = @"en0";
|
||||
}
|
||||
|
||||
return @{
|
||||
@"interfaces": interfaces,
|
||||
@"totalDownloadBytesPerSec": @(totalDownBps),
|
||||
@"totalUploadBytesPerSec": @(totalUpBps),
|
||||
@"totalDownloadPacketsPerSec": @(totalDownPps),
|
||||
@"totalUploadPacketsPerSec": @(totalUpPps),
|
||||
@"primaryInterface": primaryInterface,
|
||||
@"timeDelta": @(timeDelta)
|
||||
};
|
||||
}
|
||||
|
||||
- (nullable NSDictionary<NSString *, id> *)sampleTelemetryWithError:(NSError **)error {
|
||||
uint64_t now = mach_absolute_time();
|
||||
|
||||
// 1. Read 64-bit interface stats via NET_RT_IFLIST2
|
||||
NSMutableDictionary<NSString *, NSDictionary<NSString *, NSNumber *> *> *currentSnapshots = [NSMutableDictionary dictionary];
|
||||
|
||||
int mib[] = { CTL_NET, PF_ROUTE, 0, 0, NET_RT_IFLIST2, 0 };
|
||||
size_t len = 0;
|
||||
if (sysctl(mib, 6, NULL, &len, NULL, 0) == 0 && len > 0) {
|
||||
char *buf = malloc(len);
|
||||
if (buf && sysctl(mib, 6, buf, &len, NULL, 0) == 0) {
|
||||
char *next = buf;
|
||||
char *lim = buf + len;
|
||||
while (next < lim) {
|
||||
struct if_msghdr *ifm = (struct if_msghdr *)next;
|
||||
next += ifm->ifm_msglen;
|
||||
if (ifm->ifm_type == RTM_IFINFO2) {
|
||||
struct if_msghdr2 *if2m = (struct if_msghdr2 *)ifm;
|
||||
struct sockaddr_dl *sdl = (struct sockaddr_dl *)(if2m + 1);
|
||||
if (sdl->sdl_nlen > 0 && sdl->sdl_nlen < 32) {
|
||||
char nameBuf[33] = {0};
|
||||
memcpy(nameBuf, sdl->sdl_data, sdl->sdl_nlen);
|
||||
NSString *name = [NSString stringWithUTF8String:nameBuf];
|
||||
|
||||
currentSnapshots[name] = @{
|
||||
@"inBytes": @(if2m->ifm_data.ifi_ibytes),
|
||||
@"outBytes": @(if2m->ifm_data.ifi_obytes),
|
||||
@"inPackets": @(if2m->ifm_data.ifi_ipackets),
|
||||
@"outPackets": @(if2m->ifm_data.ifi_opackets),
|
||||
@"inErrors": @(if2m->ifm_data.ifi_ierrors),
|
||||
@"outErrors": @(if2m->ifm_data.ifi_oerrors)
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (buf) free(buf);
|
||||
}
|
||||
|
||||
// 2. Query IPv4 addresses via getifaddrs
|
||||
NSMutableDictionary<NSString *, NSString *> *ipDict = [NSMutableDictionary dictionary];
|
||||
struct ifaddrs *ifap = NULL;
|
||||
if (getifaddrs(&ifap) == 0) {
|
||||
for (struct ifaddrs *ifa = ifap; ifa != NULL; ifa = ifa->ifa_next) {
|
||||
if (ifa->ifa_addr && ifa->ifa_addr->sa_family == AF_INET) {
|
||||
char ipBuf[INET_ADDRSTRLEN] = {0};
|
||||
struct sockaddr_in *sin = (struct sockaddr_in *)ifa->ifa_addr;
|
||||
if (inet_ntop(AF_INET, &sin->sin_addr, ipBuf, sizeof(ipBuf))) {
|
||||
NSString *name = [NSString stringWithUTF8String:ifa->ifa_name];
|
||||
ipDict[name] = [NSString stringWithUTF8String:ipBuf];
|
||||
}
|
||||
}
|
||||
}
|
||||
freeifaddrs(ifap);
|
||||
}
|
||||
|
||||
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 [MMNetworkBandwidthProvider calculateBandwidthMetricsWithCurrentSnapshots:currentSnapshots
|
||||
previousSnapshots:prev
|
||||
timeDelta:timeDelta
|
||||
ipAddresses:ipDict];
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -0,0 +1,27 @@
|
||||
#ifndef MMNetworkSocketsProvider_h
|
||||
#define MMNetworkSocketsProvider_h
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "MMTelemetryProvider.h"
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
/**
|
||||
* MMNetworkSocketsProvider
|
||||
* Inspects system-wide open TCP and UDP sockets, local/remote endpoints, connection states,
|
||||
* and owning processes.
|
||||
*/
|
||||
@interface MMNetworkSocketsProvider : NSObject <MMTelemetryProvider>
|
||||
|
||||
- (instancetype)init;
|
||||
|
||||
/**
|
||||
* Pure calculator / summarizer method for deterministic unit testing.
|
||||
*/
|
||||
+ (NSDictionary<NSString *, id> *)calculateSocketSummaryWithSocketList:(NSArray<NSDictionary<NSString *, id> *> *)sockets;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
|
||||
#endif /* MMNetworkSocketsProvider_h */
|
||||
@@ -0,0 +1,152 @@
|
||||
#import "MMNetworkSocketsProvider.h"
|
||||
#import <libproc.h>
|
||||
#import <sys/proc_info.h>
|
||||
#import <arpa/inet.h>
|
||||
|
||||
@implementation MMNetworkSocketsProvider
|
||||
|
||||
- (instancetype)init {
|
||||
self = [super init];
|
||||
return self;
|
||||
}
|
||||
|
||||
- (MMTelemetryDomain)domain {
|
||||
return MMTelemetryDomainNetwork;
|
||||
}
|
||||
|
||||
- (NSString *)providerIdentifier {
|
||||
return @"com.i3omb.macmonitor.telemetry.network.sockets";
|
||||
}
|
||||
|
||||
- (BOOL)isAvailable {
|
||||
return YES;
|
||||
}
|
||||
|
||||
static NSString *tcpStateString(int state) {
|
||||
switch (state) {
|
||||
case 0: return @"CLOSED";
|
||||
case 1: return @"LISTEN";
|
||||
case 2: return @"SYN_SENT";
|
||||
case 3: return @"SYN_RCVD";
|
||||
case 4: return @"ESTABLISHED";
|
||||
case 5: return @"CLOSE_WAIT";
|
||||
case 6: return @"FIN_WAIT_1";
|
||||
case 7: return @"CLOSING";
|
||||
case 8: return @"LAST_ACK";
|
||||
case 9: return @"FIN_WAIT_2";
|
||||
case 10: return @"TIME_WAIT";
|
||||
default: return @"UNKNOWN";
|
||||
}
|
||||
}
|
||||
|
||||
+ (NSDictionary<NSString *, id> *)calculateSocketSummaryWithSocketList:(NSArray<NSDictionary<NSString *, id> *> *)sockets {
|
||||
NSUInteger tcpCount = 0;
|
||||
NSUInteger udpCount = 0;
|
||||
NSUInteger listenCount = 0;
|
||||
NSUInteger establishedCount = 0;
|
||||
|
||||
for (NSDictionary<NSString *, id> *sock in sockets) {
|
||||
NSString *proto = sock[@"protocol"];
|
||||
NSString *state = sock[@"state"];
|
||||
|
||||
if ([proto isEqualToString:@"TCP"]) {
|
||||
tcpCount++;
|
||||
if ([state isEqualToString:@"LISTEN"]) {
|
||||
listenCount++;
|
||||
} else if ([state isEqualToString:@"ESTABLISHED"]) {
|
||||
establishedCount++;
|
||||
}
|
||||
} else if ([proto isEqualToString:@"UDP"]) {
|
||||
udpCount++;
|
||||
}
|
||||
}
|
||||
|
||||
return @{
|
||||
@"socketCount": @(sockets.count),
|
||||
@"tcpCount": @(tcpCount),
|
||||
@"udpCount": @(udpCount),
|
||||
@"listenCount": @(listenCount),
|
||||
@"establishedCount": @(establishedCount),
|
||||
@"sockets": sockets
|
||||
};
|
||||
}
|
||||
|
||||
- (nullable NSDictionary<NSString *, id> *)sampleTelemetryWithError:(NSError **)error {
|
||||
int pids[2048];
|
||||
int bytes = proc_listpids(PROC_ALL_PIDS, 0, pids, sizeof(pids));
|
||||
int pidCount = bytes / sizeof(int);
|
||||
|
||||
NSMutableArray<NSDictionary<NSString *, id> *> *sockets = [NSMutableArray array];
|
||||
|
||||
for (int i = 0; i < pidCount; i++) {
|
||||
pid_t pid = pids[i];
|
||||
if (pid <= 0) continue;
|
||||
|
||||
int sz = proc_pidinfo(pid, PROC_PIDLISTFDS, 0, NULL, 0);
|
||||
if (sz <= 0) continue;
|
||||
|
||||
struct proc_fdinfo *fds = malloc(sz);
|
||||
if (!fds) continue;
|
||||
|
||||
int actual = proc_pidinfo(pid, PROC_PIDLISTFDS, 0, fds, sz);
|
||||
int fdCount = actual / sizeof(struct proc_fdinfo);
|
||||
|
||||
char procNameBuf[256] = {0};
|
||||
BOOL procNameFetched = NO;
|
||||
|
||||
for (int j = 0; j < fdCount; j++) {
|
||||
if (fds[j].proc_fdtype == PROX_FDTYPE_SOCKET) {
|
||||
struct socket_fdinfo si;
|
||||
if (proc_pidfdinfo(pid, fds[j].proc_fd, PROC_PIDFDSOCKETINFO, &si, sizeof(si)) == sizeof(si)) {
|
||||
int family = si.psi.soi_family;
|
||||
if (family == AF_INET || family == AF_INET6) {
|
||||
if (!procNameFetched) {
|
||||
proc_name(pid, procNameBuf, sizeof(procNameBuf));
|
||||
procNameFetched = YES;
|
||||
}
|
||||
|
||||
char localIP[INET6_ADDRSTRLEN] = {0};
|
||||
char remoteIP[INET6_ADDRSTRLEN] = {0};
|
||||
int lport = 0, rport = 0;
|
||||
NSString *familyStr = (family == AF_INET) ? @"IPv4" : @"IPv6";
|
||||
NSString *proto = (si.psi.soi_type == SOCK_STREAM) ? @"TCP" : @"UDP";
|
||||
NSString *state = @"NONE";
|
||||
|
||||
if (family == AF_INET) {
|
||||
inet_ntop(AF_INET, &si.psi.soi_proto.pri_in.insi_laddr.ina_46.i46a_addr4, localIP, sizeof(localIP));
|
||||
inet_ntop(AF_INET, &si.psi.soi_proto.pri_in.insi_faddr.ina_46.i46a_addr4, remoteIP, sizeof(remoteIP));
|
||||
lport = ntohs(si.psi.soi_proto.pri_in.insi_lport);
|
||||
rport = ntohs(si.psi.soi_proto.pri_in.insi_fport);
|
||||
} else {
|
||||
inet_ntop(AF_INET6, &si.psi.soi_proto.pri_in.insi_laddr.ina_6, localIP, sizeof(localIP));
|
||||
inet_ntop(AF_INET6, &si.psi.soi_proto.pri_in.insi_faddr.ina_6, remoteIP, sizeof(remoteIP));
|
||||
lport = ntohs(si.psi.soi_proto.pri_in.insi_lport);
|
||||
rport = ntohs(si.psi.soi_proto.pri_in.insi_fport);
|
||||
}
|
||||
|
||||
if (si.psi.soi_type == SOCK_STREAM) {
|
||||
state = tcpStateString(si.psi.soi_proto.pri_tcp.tcpsi_state);
|
||||
}
|
||||
|
||||
[sockets addObject:@{
|
||||
@"pid": @(pid),
|
||||
@"processName": [NSString stringWithUTF8String:procNameBuf],
|
||||
@"protocol": proto,
|
||||
@"family": familyStr,
|
||||
@"localAddress": [NSString stringWithUTF8String:localIP],
|
||||
@"localPort": @(lport),
|
||||
@"remoteAddress": [NSString stringWithUTF8String:remoteIP],
|
||||
@"remotePort": @(rport),
|
||||
@"state": state
|
||||
}];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
free(fds);
|
||||
}
|
||||
|
||||
return [MMNetworkSocketsProvider calculateSocketSummaryWithSocketList:sockets];
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -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,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"])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import XCTest
|
||||
@testable import MacMonitor
|
||||
|
||||
final class MMNetworkBandwidthTests: XCTestCase {
|
||||
|
||||
func testNetworkBandwidthCalculation() {
|
||||
let prev: [String: [String: NSNumber]] = [
|
||||
"en0": [
|
||||
"inBytes": NSNumber(value: 50_000_000),
|
||||
"outBytes": NSNumber(value: 10_000_000),
|
||||
"inPackets": NSNumber(value: 40_000),
|
||||
"outPackets": NSNumber(value: 20_000),
|
||||
"inErrors": NSNumber(value: 0),
|
||||
"outErrors": NSNumber(value: 0)
|
||||
],
|
||||
"lo0": [
|
||||
"inBytes": NSNumber(value: 5_000_000),
|
||||
"outBytes": NSNumber(value: 5_000_000),
|
||||
"inPackets": NSNumber(value: 5_000),
|
||||
"outPackets": NSNumber(value: 5_000),
|
||||
"inErrors": NSNumber(value: 0),
|
||||
"outErrors": NSNumber(value: 0)
|
||||
]
|
||||
]
|
||||
|
||||
let curr: [String: [String: NSNumber]] = [
|
||||
"en0": [
|
||||
"inBytes": NSNumber(value: 60_000_000), // delta in = 10,000,000 bytes
|
||||
"outBytes": NSNumber(value: 12_000_000), // delta out = 2,000,000 bytes
|
||||
"inPackets": NSNumber(value: 48_000), // delta in = 8,000 pkts
|
||||
"outPackets": NSNumber(value: 24_000), // delta out = 4,000 pkts
|
||||
"inErrors": NSNumber(value: 0),
|
||||
"outErrors": NSNumber(value: 0)
|
||||
],
|
||||
"lo0": [
|
||||
"inBytes": NSNumber(value: 7_000_000),
|
||||
"outBytes": NSNumber(value: 7_000_000),
|
||||
"inPackets": NSNumber(value: 7_000),
|
||||
"outPackets": NSNumber(value: 7_000),
|
||||
"inErrors": NSNumber(value: 0),
|
||||
"outErrors": NSNumber(value: 0)
|
||||
]
|
||||
]
|
||||
|
||||
let timeDelta: TimeInterval = 2.0 // 2 seconds
|
||||
let ipDict: [String: String] = ["en0": "192.168.1.100", "lo0": "127.0.0.1"]
|
||||
|
||||
let metrics = MMNetworkBandwidthProvider.calculateBandwidthMetrics(
|
||||
withCurrentSnapshots: curr,
|
||||
previousSnapshots: prev,
|
||||
timeDelta: timeDelta,
|
||||
ipAddresses: ipDict
|
||||
)
|
||||
|
||||
let totalDownBps = metrics["totalDownloadBytesPerSec"] as? Double ?? 0
|
||||
let totalUpBps = metrics["totalUploadBytesPerSec"] as? Double ?? 0
|
||||
let totalDownPps = metrics["totalDownloadPacketsPerSec"] as? Double ?? 0
|
||||
let totalUpPps = metrics["totalUploadPacketsPerSec"] as? Double ?? 0
|
||||
let primary = metrics["primaryInterface"] as? String ?? ""
|
||||
let interfaces = metrics["interfaces"] as? [[String: Any]] ?? []
|
||||
|
||||
// en0 delta in = 10MB / 2s = 5,000,000 B/s (lo0 is excluded from total)
|
||||
XCTAssertEqual(totalDownBps, 5_000_000.0, accuracy: 1.0)
|
||||
// en0 delta out = 2MB / 2s = 1,000,000 B/s
|
||||
XCTAssertEqual(totalUpBps, 1_000_000.0, accuracy: 1.0)
|
||||
// en0 delta in pkts = 8,000 / 2s = 4,000 pps
|
||||
XCTAssertEqual(totalDownPps, 4000.0, accuracy: 0.1)
|
||||
// en0 delta out pkts = 4,000 / 2s = 2,000 pps
|
||||
XCTAssertEqual(totalUpPps, 2000.0, accuracy: 0.1)
|
||||
XCTAssertEqual(primary, "en0")
|
||||
XCTAssertEqual(interfaces.count, 2)
|
||||
}
|
||||
|
||||
func testLiveNetworkBandwidthProvider() throws {
|
||||
let provider = MMNetworkBandwidthProvider()
|
||||
XCTAssertEqual(provider.domain, .network)
|
||||
XCTAssertEqual(provider.providerIdentifier, "com.i3omb.macmonitor.telemetry.network.bandwidth")
|
||||
|
||||
let sample = try provider.sampleTelemetry()
|
||||
XCTAssertNotNil(sample)
|
||||
XCTAssertNotNil(sample["totalDownloadBytesPerSec"])
|
||||
XCTAssertNotNil(sample["totalUploadBytesPerSec"])
|
||||
XCTAssertNotNil(sample["interfaces"])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import XCTest
|
||||
@testable import MacMonitor
|
||||
|
||||
final class MMNetworkSocketsTests: XCTestCase {
|
||||
|
||||
func testSocketSummaryCalculation() {
|
||||
let testSockets: [[String: Any]] = [
|
||||
[
|
||||
"pid": 100,
|
||||
"processName": "web_server",
|
||||
"protocol": "TCP",
|
||||
"family": "IPv4",
|
||||
"localAddress": "0.0.0.0",
|
||||
"localPort": 8080,
|
||||
"remoteAddress": "0.0.0.0",
|
||||
"remotePort": 0,
|
||||
"state": "LISTEN"
|
||||
],
|
||||
[
|
||||
"pid": 200,
|
||||
"processName": "browser",
|
||||
"protocol": "TCP",
|
||||
"family": "IPv4",
|
||||
"localAddress": "192.168.1.50",
|
||||
"localPort": 54321,
|
||||
"remoteAddress": "142.250.190.46",
|
||||
"remotePort": 443,
|
||||
"state": "ESTABLISHED"
|
||||
],
|
||||
[
|
||||
"pid": 300,
|
||||
"processName": "dns_daemon",
|
||||
"protocol": "UDP",
|
||||
"family": "IPv4",
|
||||
"localAddress": "0.0.0.0",
|
||||
"localPort": 53,
|
||||
"remoteAddress": "0.0.0.0",
|
||||
"remotePort": 0,
|
||||
"state": "NONE"
|
||||
]
|
||||
]
|
||||
|
||||
let summary = MMNetworkSocketsProvider.calculateSocketSummary(withSocketList: testSockets)
|
||||
|
||||
let total = summary["socketCount"] as? Int ?? 0
|
||||
let tcp = summary["tcpCount"] as? Int ?? 0
|
||||
let udp = summary["udpCount"] as? Int ?? 0
|
||||
let listen = summary["listenCount"] as? Int ?? 0
|
||||
let established = summary["establishedCount"] as? Int ?? 0
|
||||
|
||||
XCTAssertEqual(total, 3)
|
||||
XCTAssertEqual(tcp, 2)
|
||||
XCTAssertEqual(udp, 1)
|
||||
XCTAssertEqual(listen, 1)
|
||||
XCTAssertEqual(established, 1)
|
||||
}
|
||||
|
||||
func testLiveNetworkSocketsProvider() throws {
|
||||
let provider = MMNetworkSocketsProvider()
|
||||
XCTAssertEqual(provider.domain, .network)
|
||||
XCTAssertEqual(provider.providerIdentifier, "com.i3omb.macmonitor.telemetry.network.sockets")
|
||||
|
||||
let sample = try provider.sampleTelemetry()
|
||||
XCTAssertNotNil(sample)
|
||||
XCTAssertNotNil(sample["socketCount"])
|
||||
XCTAssertNotNil(sample["sockets"])
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user