Repository Public
1//go:build linux23package collect45import (6 "bufio"7 "context"8 "errors"9 "net"10 "os"11 "path/filepath"12 "strconv"13 "strings"14 "syscall"15 "time"1617 "github.com/shirou/gopsutil/v4/mem"1819 "clustr.spboucher.ai/mcc/internal/agent/runcmd"20 "clustr.spboucher.ai/mcc/internal/protocol"21)2223const osKind = "linux"2425func platformMemory() (memStats, error) {26 var m memStats27 vm, err := mem.VirtualMemory()28 if err != nil {29 return m, err30 }31 if vm.Total == 0 {32 return m, errors.New("MemTotal is zero")33 }34 m.Total = vm.Total35 m.Used = vm.Total - vm.Available36 m.AvailablePct, m.HasAvailablePct = 100*float64(vm.Available)/float64(vm.Total), true37 // Wired, compressed and the kernel pressure level are macOS notions.38 return m, nil39}4041func platformSwap(context.Context) (used, total uint64, err error) {42 vm, err := mem.VirtualMemory()43 if err != nil {44 return 0, 0, err45 }46 return vm.SwapTotal - vm.SwapFree, vm.SwapTotal, nil47}4849func platformGPU(context.Context) (GPUStats, error) { return GPUStats{}, errUnsupported }5051// Linux exposes no equivalent of the macOS thermal pressure state.52func platformThermal() (float64, error) { return 0, errUnsupported }5354func platformBattery(context.Context) (pct float64, present bool, err error) {55 matches, _ := filepath.Glob("/sys/class/power_supply/BAT*/capacity")56 for _, m := range matches {57 b, err := os.ReadFile(m)58 if err != nil {59 continue60 }61 v, err := strconv.ParseFloat(strings.TrimSpace(string(b)), 64)62 if err == nil && v >= 0 && v <= 100 {63 return v, true, nil64 }65 }66 return 0, false, nil67}6869func platformGateway(context.Context) (gateway, iface string, err error) {70 b, err := os.ReadFile("/proc/net/route")71 if err != nil {72 return "", "", err73 }74 gateway, iface = ParseProcNetRoute(string(b))75 if gateway == "" {76 return "", "", errors.New("no default gateway")77 }78 return gateway, iface, nil79}8081func pingCommand(target string) []string {82 bin := runcmd.Find("ping", "/bin/ping", "/usr/bin/ping")83 if bin == "" {84 bin = "/bin/ping"85 }86 return []string{bin, "-n", "-q", "-c", "3", "-i", "0.3", "-W", "1", "-w", "4", target}87}8889var realFS = map[string]bool{90 "ext2": true, "ext3": true, "ext4": true, "xfs": true, "btrfs": true, "zfs": true, "f2fs": true,91 "vfat": true, "exfat": true, "ntfs": true, "ntfs3": true, "fuseblk": true,92}93var networkFS = map[string]bool{"nfs": true, "nfs4": true, "cifs": true, "smb3": true, "smbfs": true, "ceph": true, "glusterfs": true}9495func unescapeMount(s string) string {96 return strings.NewReplacer(`\040`, " ", `\011`, "\t", `\012`, "\n", `\134`, `\`).Replace(s)97}9899func platformVolumes(context.Context) ([]protocol.Volume, error) {100 f, err := os.Open("/proc/self/mounts")101 if err != nil {102 return nil, err103 }104 defer f.Close()105 var vols []protocol.Volume106 seenDev := map[string]bool{}107 sc := bufio.NewScanner(f)108 for sc.Scan() {109 p := strings.Fields(sc.Text())110 if len(p) < 3 {111 continue112 }113 dev, mount, fstype := unescapeMount(p[0]), unescapeMount(p[1]), p[2]114 network := networkFS[fstype]115 if !network && !realFS[fstype] {116 continue117 }118 if strings.HasPrefix(mount, "/boot") || strings.HasPrefix(mount, "/snap/") || strings.HasPrefix(mount, "/var/lib/docker/") {119 continue120 }121 if seenDev[dev] {122 continue // bind mounts and subvolumes of the same device123 }124 var st syscall.Statfs_t125 if err := syscall.Statfs(mount, &st); err != nil || st.Blocks == 0 {126 continue127 }128 seenDev[dev] = true129 total := int64(st.Blocks) * int64(st.Bsize)130 v := protocol.Volume{Mount: mount, FS: fstype, Total: total, Used: total - int64(st.Bfree)*int64(st.Bsize)}131 if network {132 v.Kind = "network"133 v.Remote = StripRemoteCredentials(dev)134 v.Device = v.Remote135 } else {136 v.Device = dev137 v.Kind = "internal"138 if removable(dev) {139 v.Kind = "external"140 }141 }142 vols = append(vols, v)143 }144 return vols, sc.Err()145}146147// removable reports whether the block device behind dev is flagged removable.148func removable(dev string) bool {149 name := filepath.Base(dev)150 for len(name) > 0 {151 if b, err := os.ReadFile("/sys/block/" + name + "/removable"); err == nil {152 return strings.TrimSpace(string(b)) == "1"153 }154 name = name[:len(name)-1] // sda1 -> sda, nvme0n1p2 -> nvme0n1155 }156 return false157}158159func readTrim(path string) string {160 b, err := os.ReadFile(path)161 if err != nil {162 return ""163 }164 return strings.TrimSpace(string(b))165}166167func platformInventory(_ context.Context, inv *protocol.Inventory) {168 inv.Kind = "linux"169 inv.HardwareUUID = readTrim("/etc/machine-id")170 if inv.HardwareUUID == "" {171 inv.HardwareUUID = readTrim("/var/lib/dbus/machine-id")172 }173 inv.Model = strings.TrimSpace(readTrim("/sys/class/dmi/id/sys_vendor") + " " + readTrim("/sys/class/dmi/id/product_name"))174 inv.Kernel = "Linux " + readTrim("/proc/sys/kernel/osrelease")175 inv.OSName = "Linux"176 if f, err := os.Open("/etc/os-release"); err == nil {177 sc := bufio.NewScanner(f)178 for sc.Scan() {179 k, v, ok := strings.Cut(sc.Text(), "=")180 if !ok {181 continue182 }183 v = strings.Trim(v, `"'`)184 switch k {185 case "NAME":186 inv.OSName = v187 case "VERSION_ID":188 inv.OSVersion = v189 case "BUILD_ID":190 inv.OSBuild = v191 }192 }193 f.Close()194 }195 logical := 0196 if f, err := os.Open("/proc/cpuinfo"); err == nil {197 sc := bufio.NewScanner(f)198 for sc.Scan() {199 k, v, ok := strings.Cut(sc.Text(), ":")200 if !ok {201 continue202 }203 switch strings.TrimSpace(k) {204 case "processor":205 logical++206 case "model name":207 if inv.Chip == "" {208 inv.Chip = strings.TrimSpace(v)209 }210 }211 }212 f.Close()213 }214 inv.CPUCores = logical215 if vm, err := mem.VirtualMemory(); err == nil {216 inv.MemBytes = int64(vm.Total)217 }218 if up := readTrim("/proc/uptime"); up != "" {219 if secs, err := strconv.ParseFloat(strings.Fields(up)[0], 64); err == nil {220 inv.BootTime = time.Now().Add(-time.Duration(secs * float64(time.Second))).UTC().Truncate(time.Second)221 }222 }223 if m, _ := filepath.Glob("/sys/class/power_supply/BAT*"); len(m) > 0 {224 inv.Laptop = true225 }226 if st, err := os.Stat("/run/systemd/system"); err == nil && st.IsDir() {227 inv.Managers = append(inv.Managers, "systemd")228 }229}230231func platformInterfaceMeta(_ context.Context, names []string) (ports map[string]string, media map[string]string, wireless map[string]bool) {232 ports, media, wireless = map[string]string{}, map[string]string{}, map[string]bool{}233 for _, n := range names {234 if _, err := os.Stat("/sys/class/net/" + n + "/wireless"); err == nil {235 wireless[n] = true236 }237 if sp := readTrim("/sys/class/net/" + n + "/speed"); sp != "" && sp != "-1" {238 media[n] = sp + "Mb/s"239 }240 }241 return242}243244// physicalDisk keeps whole physical devices: partitions, loop, RAM, md and245// device-mapper nodes would double count the same I/O.246func physicalDisk(name string) bool {247 if _, err := os.Stat("/sys/block/" + name + "/device"); err != nil {248 return false249 }250 return true251}252253func skipInterface(ifc net.Interface) bool {254 for _, p := range []string{"docker", "veth", "br-", "virbr", "cni", "flannel", "dummy"} {255 if strings.HasPrefix(ifc.Name, p) {256 return true257 }258 }259 return false260}261262func platformHostname() string {263 h, _ := os.Hostname()264 return h265}266