miaopanel
1package system
2
3import (
4 "bufio"
5 "os"
6 "runtime"
7 "strconv"
8 "strings"
9 "sync"
10 "time"
11)
12
13// Memory reports memory usage in bytes.
14type Memory struct {
15 Total uint64 `json:"total"`
16 Used uint64 `json:"used"`
17 Available uint64 `json:"available"`
18 SwapTotal uint64 `json:"swap_total"`
19 SwapUsed uint64 `json:"swap_used"`
20}
21
22// Disk reports filesystem usage in bytes.
23type Disk struct {
24 Path string `json:"path"`
25 Total uint64 `json:"total"`
26 Used uint64 `json:"used"`
27 Free uint64 `json:"free"`
28}
29
30// Snapshot is the dashboard payload.
31type Snapshot struct {
32 Hostname string `json:"hostname"`
33 Distro Distro `json:"distro"`
34 Uptime int64 `json:"uptime"`
35 Load1 float64 `json:"load1"`
36 Load5 float64 `json:"load5"`
37 Load15 float64 `json:"load15"`
38 CPUCores int `json:"cpu_cores"`
39 CPUUsage float64 `json:"cpu_usage"`
40 Memory Memory `json:"memory"`
41 Disk Disk `json:"disk"`
42 NetRX uint64 `json:"net_rx"`
43 NetTX uint64 `json:"net_tx"`
44 Time int64 `json:"time"`
45}
46
47// Collect gathers the current host metrics.
48func Collect(diskPath string) Snapshot {
49 host, _ := os.Hostname()
50 if diskPath == "" {
51 diskPath = "/"
52 }
53 s := Snapshot{
54 Hostname: host,
55 Distro: Detect(),
56 CPUCores: runtime.NumCPU(),
57 CPUUsage: cpuUsage(),
58 Memory: readMemory(),
59 Disk: diskUsage(diskPath),
60 Time: time.Now().Unix(),
61 }
62 s.Uptime = readUptime()
63 s.Load1, s.Load5, s.Load15 = readLoad()
64 s.NetRX, s.NetTX = readNet()
65 return s
66}
67
68func readUptime() int64 {
69 b, err := os.ReadFile("/proc/uptime")
70 if err != nil {
71 return 0
72 }
73 fields := strings.Fields(string(b))
74 if len(fields) == 0 {
75 return 0
76 }
77 f, _ := strconv.ParseFloat(fields[0], 64)
78 return int64(f)
79}
80
81func readLoad() (float64, float64, float64) {
82 b, err := os.ReadFile("/proc/loadavg")
83 if err != nil {
84 return 0, 0, 0
85 }
86 fields := strings.Fields(string(b))
87 if len(fields) < 3 {
88 return 0, 0, 0
89 }
90 a, _ := strconv.ParseFloat(fields[0], 64)
91 c, _ := strconv.ParseFloat(fields[1], 64)
92 d, _ := strconv.ParseFloat(fields[2], 64)
93 return a, c, d
94}
95
96func readMemory() Memory {
97 b, err := os.ReadFile("/proc/meminfo")
98 if err != nil {
99 return Memory{}
100 }
101 vals := map[string]uint64{}
102 sc := bufio.NewScanner(strings.NewReader(string(b)))
103 for sc.Scan() {
104 key, rest, ok := strings.Cut(sc.Text(), ":")
105 if !ok {
106 continue
107 }
108 fields := strings.Fields(rest)
109 if len(fields) == 0 {
110 continue
111 }
112 v, _ := strconv.ParseUint(fields[0], 10, 64)
113 vals[key] = v * 1024
114 }
115 var m Memory
116 m.Total = vals["MemTotal"]
117 m.Available = vals["MemAvailable"]
118 if m.Available == 0 {
119 m.Available = vals["MemFree"] + vals["Buffers"] + vals["Cached"]
120 }
121 if m.Total > m.Available {
122 m.Used = m.Total - m.Available
123 }
124 m.SwapTotal = vals["SwapTotal"]
125 if m.SwapTotal > vals["SwapFree"] {
126 m.SwapUsed = m.SwapTotal - vals["SwapFree"]
127 }
128 return m
129}
130
131func readNet() (uint64, uint64) {
132 b, err := os.ReadFile("/proc/net/dev")
133 if err != nil {
134 return 0, 0
135 }
136 var rx, tx uint64
137 sc := bufio.NewScanner(strings.NewReader(string(b)))
138 for sc.Scan() {
139 line := sc.Text()
140 idx := strings.IndexByte(line, ':')
141 if idx < 0 {
142 continue
143 }
144 name := strings.TrimSpace(line[:idx])
145 if name == "lo" {
146 continue
147 }
148 fields := strings.Fields(line[idx+1:])
149 if len(fields) < 9 {
150 continue
151 }
152 r, _ := strconv.ParseUint(fields[0], 10, 64)
153 t, _ := strconv.ParseUint(fields[8], 10, 64)
154 rx += r
155 tx += t
156 }
157 return rx, tx
158}
159
160var cpuSample struct {
161 sync.Mutex
162 lastTotal uint64
163 lastIdle uint64
164 lastAt time.Time
165 lastValue float64
166}
167
168// cpuUsage returns the busy percentage since the previous sample. The very
169// first call measures a short 200ms window so the dashboard never flashes 0%.
170func cpuUsage() float64 {
171 data, err := os.ReadFile("/proc/stat")
172 if err != nil {
173 return 0
174 }
175 total, idle := parseCPUStat(string(data))
176 if total == 0 {
177 return 0
178 }
179
180 cpuSample.Lock()
181 defer cpuSample.Unlock()
182 if cpuSample.lastAt.IsZero() {
183 time.Sleep(200 * time.Millisecond)
184 second, err := os.ReadFile("/proc/stat")
185 if err != nil {
186 cpuSample.lastTotal, cpuSample.lastIdle, cpuSample.lastAt = total, idle, time.Now()
187 return 0
188 }
189 t2, i2 := parseCPUStat(string(second))
190 cpuSample.lastTotal, cpuSample.lastIdle, cpuSample.lastAt = t2, i2, time.Now()
191 dTotal := float64(t2) - float64(total)
192 dIdle := float64(i2) - float64(idle)
193 if dTotal > 0 {
194 cpuSample.lastValue = clampPercent((dTotal - dIdle) / dTotal * 100)
195 }
196 return cpuSample.lastValue
197 }
198
199 dTotal := float64(total) - float64(cpuSample.lastTotal)
200 dIdle := float64(idle) - float64(cpuSample.lastIdle)
201 cpuSample.lastTotal, cpuSample.lastIdle, cpuSample.lastAt = total, idle, time.Now()
202 if dTotal <= 0 {
203 return cpuSample.lastValue
204 }
205 cpuSample.lastValue = clampPercent((dTotal - dIdle) / dTotal * 100)
206 return cpuSample.lastValue
207}
208
209func parseCPUStat(data string) (total, idle uint64) {
210 line := strings.SplitN(data, "\n", 2)[0]
211 fields := strings.Fields(line)
212 if len(fields) < 5 {
213 return 0, 0
214 }
215 for i, f := range fields[1:] {
216 v, _ := strconv.ParseUint(f, 10, 64)
217 total += v
218 if i == 3 || i == 4 { // idle + iowait
219 idle += v
220 }
221 }
222 return total, idle
223}
224
225func clampPercent(v float64) float64 {
226 if v < 0 {
227 return 0
228 }
229 if v > 100 {
230 return 100
231 }
232 return v
233}