Repository Public
1//go:build darwin23/**4 * =============================================================================5 * SP BOUCHER | INFRASTRUCTURE & AUTOMATION6 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING7 * =============================================================================8 *9 * Project : MacLustr Command Center (MCC)10 * File : services/internal/agent/collect/platform_darwin.go11 * Module : services12 * Repository : https://git.spboucher.ai/maclustr-command-center13 * Project Website : https://clustr.spboucher.ai14 * Created : 2026-11-1815 * Last Modified : 2026-11-1816 *17 * Author : Simon-Pierre Boucher18 * Position : Professor of Finance19 * Institution : Université du Québec en Outaouais (UQO)20 * Organization : SP Boucher21 * Website : https://spboucher.ai22 * Git : https://git.spboucher.ai23 *24 * Preferred Contact: admin@spboucher.ai25 * Technical Contact: dev@spboucher.ai26 * Security/Admin : admin@spboucher.ai27 *28 * Copyright (c) 202629 * Simon-Pierre Boucher30 * All rights reserved where applicable. This file is governed by the31 * applicable project license, copyright notices and relevant law.32 * Existing third-party rights and notices remain unaffected.33 *34 * License : None specified (no license file in this repository)35 *36 * Do not embed credentials, private keys, access tokens,37 * certificates or confidential personal information.38 *39 * =============================================================================40 * END OF SP BOUCHER SOURCE HEADER41 * =============================================================================42 */4344package collect4546import (47 "context"48 "errors"49 "fmt"50 "net"51 "os"52 "strings"53 "sync"54 "time"55 "unsafe"5657 "github.com/ebitengine/purego"58 "golang.org/x/sys/unix"5960 "clustr.spboucher.ai/mcc/internal/agent/runcmd"61 "clustr.spboucher.ai/mcc/internal/protocol"62)6364const osKind = "mac"6566// libSystem bindings, resolved once without cgo. If anything is missing the67// dependent metrics are reported unavailable; nothing is estimated.68var (69 libOnce sync.Once70 libErr error71 machHostSelf func() uint3272 hostStatistics64 func(host uint32, flavor int32, info unsafe.Pointer, count *uint32) int3273 notifyRegisterChk func(name string, token *int32) uint3274 notifyGetState func(token int32, state *uint64) uint3275 thermalToken int3276 thermalTokenOK bool77 thermalRegisterErr error78)7980func loadLib() error {81 libOnce.Do(func() {82 defer func() {83 if v := recover(); v != nil {84 libErr = fmt.Errorf("libSystem binding failed: %v", v)85 }86 }()87 h, err := purego.Dlopen("/usr/lib/libSystem.B.dylib", purego.RTLD_LAZY|purego.RTLD_GLOBAL)88 if err != nil {89 libErr = err90 return91 }92 purego.RegisterLibFunc(&machHostSelf, h, "mach_host_self")93 purego.RegisterLibFunc(&hostStatistics64, h, "host_statistics64")94 purego.RegisterLibFunc(¬ifyRegisterChk, h, "notify_register_check")95 purego.RegisterLibFunc(¬ifyGetState, h, "notify_get_state")96 if st := notifyRegisterChk("com.apple.system.thermalpressurelevel", &thermalToken); st == 0 {97 thermalTokenOK = true98 } else {99 thermalRegisterErr = fmt.Errorf("notify_register_check status %d", st)100 }101 })102 return libErr103}104105// vmStatistics64 mirrors struct vm_statistics64 (mach/vm_statistics.h).106type vmStatistics64 struct {107 FreeCount, ActiveCount, InactiveCount, WireCount uint32108 ZeroFill, Reactivations, Pageins, Pageouts, Faults, CowFaults uint64109 Lookups, Hits, Purges uint64110 PurgeableCount, SpeculativeCount uint32111 Decompressions, Compressions, Swapins, Swapouts uint64112 CompressorPageCount, ThrottledCount, ExternalPageCount, InternalCount uint32113 TotalUncompressedInCompressor uint64114}115116const hostVMInfo64 = 4117118func platformMemory() (memStats, error) {119 var m memStats120 if err := loadLib(); err != nil {121 return m, err122 }123 var vs vmStatistics64124 count := uint32(unsafe.Sizeof(vs) / 4)125 if kr := hostStatistics64(machHostSelf(), hostVMInfo64, unsafe.Pointer(&vs), &count); kr != 0 {126 return m, fmt.Errorf("host_statistics64: kern_return %d", kr)127 }128 page, err := unix.SysctlUint64("hw.pagesize")129 if err != nil {130 return m, err131 }132 total, err := unix.SysctlUint64("hw.memsize")133 if err != nil {134 return m, err135 }136 m.Total = total137 m.Wired, m.HasWired = uint64(vs.WireCount)*page, true138 m.Compressed, m.HasCompressed = uint64(vs.CompressorPageCount)*page, true139 m.Used = (uint64(vs.ActiveCount) + uint64(vs.WireCount) + uint64(vs.CompressorPageCount)) * page140 if lvl, err := unix.SysctlUint32("kern.memorystatus_vm_pressure_level"); err == nil {141 m.PressureLevel, m.HasPressure = float64(lvl), true142 }143 if lvl, err := unix.SysctlUint32("kern.memorystatus_level"); err == nil && lvl <= 100 {144 m.AvailablePct, m.HasAvailablePct = float64(lvl), true145 }146 return m, nil147}148149// xswUsage mirrors struct xsw_usage (sys/sysctl.h).150type xswUsage struct {151 Total, Avail, Used uint64152 PageSize uint32153 Encrypted uint32154}155156func platformSwap(ctx context.Context) (used, total uint64, err error) {157 if raw, rerr := unix.SysctlRaw("vm.swapusage"); rerr == nil && len(raw) >= int(unsafe.Sizeof(xswUsage{})) {158 x := *(*xswUsage)(unsafe.Pointer(&raw[0]))159 return x.Used, x.Total, nil160 }161 // Fallback: the text form (locale dependent: decimal comma under fr_*).162 out, err := runcmd.Output(ctx, 3*time.Second, "/usr/sbin/sysctl", "-n", "vm.swapusage")163 if err != nil {164 return 0, 0, err165 }166 total, used, err = ParseSwapUsage(string(out))167 return used, total, err168}169170func platformGPU(ctx context.Context) (GPUStats, error) {171 out, err := runcmd.Output(ctx, 4*time.Second, "/usr/sbin/ioreg", "-r", "-d", "1", "-w", "0", "-c", "IOAccelerator")172 if err != nil {173 return GPUStats{}, err174 }175 return ParseIORegGPU(string(out))176}177178// platformThermal reads the notify state com.apple.system.thermalpressurelevel179// (0 nominal … 4 sleeping) through libnotify, without cgo and without root.180func platformThermal() (float64, error) {181 if err := loadLib(); err != nil {182 return 0, err183 }184 if !thermalTokenOK {185 return 0, thermalRegisterErr186 }187 var state uint64188 if st := notifyGetState(thermalToken, &state); st != 0 {189 return 0, fmt.Errorf("notify_get_state status %d", st)190 }191 if state > 4 {192 return 0, fmt.Errorf("unexpected thermal pressure state %d", state)193 }194 return float64(state), nil195}196197func platformBattery(ctx context.Context) (pct float64, present bool, err error) {198 out, err := runcmd.Output(ctx, 3*time.Second, "/usr/bin/pmset", "-g", "batt")199 if err != nil {200 return 0, false, err201 }202 pct, present = ParsePmsetBatt(string(out))203 return pct, present, nil204}205206func platformGateway(ctx context.Context) (gateway, iface string, err error) {207 out, err := runcmd.Output(ctx, 3*time.Second, "/sbin/route", "-n", "get", "default")208 if err != nil {209 return "", "", err210 }211 gateway, iface = ParseRouteGet(string(out))212 if gateway == "" {213 return "", iface, errors.New("no default gateway")214 }215 return gateway, iface, nil216}217218func pingCommand(target string) []string {219 // 3 echoes 0.3 s apart, 1 s per-reply wait, 4 s overall.220 return []string{"/sbin/ping", "-n", "-q", "-c", "3", "-i", "0.3", "-W", "1000", "-t", "4", target}221}222223func cstr(b []byte) string {224 if i := strings.IndexByte(string(b), 0); i >= 0 {225 return string(b[:i])226 }227 return string(b)228}229230var networkFS = map[string]bool{"smbfs": true, "nfs": true, "afpfs": true, "webdav": true, "cifs": true}231232type diskInfo struct {233 smart string234 internal, known bool235 at time.Time236}237238var (239 diskInfoMu sync.Mutex240 diskInfoCache = map[string]diskInfo{}241)242243func diskutilInfo(ctx context.Context, mount string) diskInfo {244 diskInfoMu.Lock()245 if di, ok := diskInfoCache[mount]; ok && time.Since(di.at) < 6*time.Hour {246 diskInfoMu.Unlock()247 return di248 }249 diskInfoMu.Unlock()250 di := diskInfo{at: time.Now()}251 if out, err := runcmd.Output(ctx, 5*time.Second, "/usr/sbin/diskutil", "info", mount); err == nil {252 di.smart, di.internal, di.known = ParseDiskutilInfo(string(out))253 }254 diskInfoMu.Lock()255 diskInfoCache[mount] = di256 diskInfoMu.Unlock()257 return di258}259260// platformVolumes lists the volumes a person would recognise: the system261// container (as "/"), mounted disks under /Volumes and network shares.262// APFS helper volumes (/System/Volumes/*) share the container of "/" and are263// skipped. For "/", used = total - free of the container, which is the264// figure that matters for "is this disk full".265func platformVolumes(ctx context.Context) ([]protocol.Volume, error) {266 n, err := unix.Getfsstat(nil, unix.MNT_NOWAIT)267 if err != nil {268 return nil, err269 }270 buf := make([]unix.Statfs_t, n+4)271 n, err = unix.Getfsstat(buf, unix.MNT_NOWAIT)272 if err != nil {273 return nil, err274 }275 var vols []protocol.Volume276 for _, fs := range buf[:n] {277 mount := cstr(unsafe.Slice((*byte)(unsafe.Pointer(&fs.Mntonname[0])), len(fs.Mntonname)))278 from := cstr(unsafe.Slice((*byte)(unsafe.Pointer(&fs.Mntfromname[0])), len(fs.Mntfromname)))279 fstype := cstr(unsafe.Slice((*byte)(unsafe.Pointer(&fs.Fstypename[0])), len(fs.Fstypename)))280 network := networkFS[fstype] || fs.Flags&unix.MNT_LOCAL == 0 && strings.HasPrefix(from, "//")281 switch {282 case network:283 case mount == "/":284 case strings.HasPrefix(mount, "/Volumes/") && fs.Flags&unix.MNT_DONTBROWSE == 0 && fs.Flags&unix.MNT_LOCAL != 0:285 default:286 continue287 }288 if fs.Blocks == 0 {289 continue290 }291 total := int64(fs.Blocks) * int64(fs.Bsize)292 used := total - int64(fs.Bfree)*int64(fs.Bsize)293 v := protocol.Volume{Mount: mount, FS: fstype, Total: total, Used: used}294 if network {295 v.Kind = "network"296 v.Remote = StripRemoteCredentials(from)297 v.Device = v.Remote298 } else {299 v.Device = from300 di := diskutilInfo(ctx, mount)301 v.SMART = di.smart302 switch {303 case di.known && di.internal, !di.known && mount == "/":304 v.Kind = "internal"305 default:306 v.Kind = "external"307 }308 }309 vols = append(vols, v)310 }311 return vols, nil312}313314func sysctlString(name string) string {315 s, err := unix.Sysctl(name)316 if err != nil {317 return ""318 }319 return strings.TrimSpace(s)320}321322func platformInventory(ctx context.Context, inv *protocol.Inventory) {323 inv.Kind = "mac"324 inv.OSName = "macOS"325 if out, err := runcmd.Output(ctx, 5*time.Second, "/usr/sbin/ioreg", "-rd1", "-c", "IOPlatformExpertDevice"); err == nil {326 inv.HardwareUUID = ParseIOPlatformUUID(string(out))327 }328 inv.Model = sysctlString("hw.model")329 inv.Chip = sysctlString("machdep.cpu.brand_string")330 inv.OSVersion = sysctlString("kern.osproductversion")331 inv.OSBuild = sysctlString("kern.osversion")332 if rel := sysctlString("kern.osrelease"); rel != "" {333 inv.Kernel = "Darwin " + rel334 }335 if n, err := unix.SysctlUint32("hw.ncpu"); err == nil {336 inv.CPUCores = int(n)337 }338 if mem, err := unix.SysctlUint64("hw.memsize"); err == nil {339 inv.MemBytes = int64(mem)340 }341 // Every performance level, under the name the OS gives it. No P/E342 // assumption: M5/M6 machines name them differently and may have three.343 if n, err := unix.SysctlUint32("hw.nperflevels"); err == nil {344 for i := uint32(0); i < n && i < 8; i++ {345 name := sysctlString(fmt.Sprintf("hw.perflevel%d.name", i))346 cores, err := unix.SysctlUint32(fmt.Sprintf("hw.perflevel%d.physicalcpu", i))347 if err != nil {348 continue349 }350 if name == "" {351 name = fmt.Sprintf("level%d", i)352 }353 inv.CPULevels = append(inv.CPULevels, protocol.CPULevel{Name: name, Cores: int(cores)})354 }355 }356 if g, err := platformGPU(ctx); err == nil || g.Model != "" || g.Cores > 0 {357 inv.GPUModel, inv.GPUCores = g.Model, g.Cores358 }359 if tv, err := unix.SysctlTimeval("kern.boottime"); err == nil {360 inv.BootTime = time.Unix(tv.Sec, int64(tv.Usec)*1000).UTC()361 }362 if _, present, err := platformBattery(ctx); err == nil {363 inv.Laptop = present364 }365 inv.Managers = append(inv.Managers, "launchd")366}367368// platformInterfaceMeta returns, per interface, its hardware port name and369// media line.370func platformInterfaceMeta(ctx context.Context, names []string) (ports map[string]string, media map[string]string, wireless map[string]bool) {371 ports, media, wireless = map[string]string{}, map[string]string{}, map[string]bool{}372 if out, err := runcmd.Output(ctx, 5*time.Second, "/usr/sbin/networksetup", "-listallhardwareports"); err == nil {373 ports = ParseHardwarePorts(string(out))374 }375 for _, n := range names {376 if !strings.HasPrefix(n, "en") {377 continue378 }379 out, err := runcmd.Output(ctx, 3*time.Second, "/sbin/ifconfig", n)380 if err != nil {381 continue382 }383 for _, line := range strings.Split(string(out), "\n") {384 if v, ok := strings.CutPrefix(strings.TrimSpace(line), "media: "); ok {385 media[n] = strings.TrimSpace(v)386 }387 }388 }389 return390}391392func physicalDisk(name string) bool { return strings.HasPrefix(name, "disk") }393394func skipInterface(ifc net.Interface) bool {395 for _, p := range []string{"awdl", "llw", "bridge", "anpi", "gif", "stf", "ap", "pktap", "XHC"} {396 if strings.HasPrefix(ifc.Name, p) {397 return true398 }399 }400 return false401}402403func platformHostname() string {404 if out, err := unix.Sysctl("kern.hostname"); err == nil && out != "" {405 return out406 }407 h, _ := os.Hostname()408 return h409}410