-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsysstats.go
More file actions
130 lines (112 loc) · 2.5 KB
/
Copy pathsysstats.go
File metadata and controls
130 lines (112 loc) · 2.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
package main
import (
"bufio"
"context"
"fmt"
"os"
"strconv"
"strings"
"sync"
"time"
)
type SystemStats struct {
CPULoad float64 `json:"cpu_load"` // 0 to 100 percentage
RAMUsedMB float64 `json:"ram_used_mb"`
RAMTotalMB float64 `json:"ram_total_mb"`
}
type SysStatsMonitor struct {
mu sync.RWMutex
stats SystemStats
lastIdleTime uint64
lastTotalTime uint64
}
func NewSysStatsMonitor() *SysStatsMonitor {
m := &SysStatsMonitor{}
// Initialize CPU counters to get immediate first read
m.readCPU()
return m
}
func (m *SysStatsMonitor) GetStats() SystemStats {
m.mu.RLock()
defer m.mu.RUnlock()
return m.stats
}
func (m *SysStatsMonitor) Start(ctx context.Context) {
ticker := time.NewTicker(2 * time.Second)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
cpu := m.readCPU()
used, total := m.readRAM()
m.mu.Lock()
m.stats.CPULoad = cpu
m.stats.RAMUsedMB = used
m.stats.RAMTotalMB = total
m.mu.Unlock()
}
}
}
func (m *SysStatsMonitor) readCPU() float64 {
file, err := os.Open("/proc/stat")
if err != nil {
return 0
}
defer file.Close()
scanner := bufio.NewScanner(file)
if scanner.Scan() {
fields := strings.Fields(scanner.Text())
if len(fields) >= 5 && fields[0] == "cpu" {
var user, nice, system, idle uint64
fmt.Sscanf(fields[1], "%d", &user)
fmt.Sscanf(fields[2], "%d", &nice)
fmt.Sscanf(fields[3], "%d", &system)
fmt.Sscanf(fields[4], "%d", &idle)
total := user + nice + system + idle
var cpuLoad float64
if m.lastTotalTime > 0 {
totalDiff := float64(total - m.lastTotalTime)
idleDiff := float64(idle - m.lastIdleTime)
if totalDiff > 0 {
cpuLoad = (totalDiff - idleDiff) / totalDiff * 100.0
}
}
m.lastIdleTime = idle
m.lastTotalTime = total
return cpuLoad
}
}
return 0
}
func (m *SysStatsMonitor) readRAM() (usedMB, totalMB float64) {
file, err := os.Open("/proc/meminfo")
if err != nil {
return 0, 0
}
defer file.Close()
var total, free, buffers, cached uint64
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
parts := strings.Fields(line)
if len(parts) < 2 {
continue
}
val, _ := strconv.ParseUint(parts[1], 10, 64)
switch parts[0] {
case "MemTotal:":
total = val
case "MemFree:":
free = val
case "Buffers:":
buffers = val
case "Cached:":
cached = val
}
}
totalMB = float64(total) / 1024.0
usedMB = float64(total-free-buffers-cached) / 1024.0
return usedMB, totalMB
}