-
Notifications
You must be signed in to change notification settings - Fork 0
/
hardware.go
189 lines (165 loc) · 4.44 KB
/
hardware.go
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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
package main
import (
"bufio"
"encoding/json"
"fmt"
"net/http"
"os"
"strconv"
"strings"
"syscall"
"time"
)
type ServerStats struct {
CPUUsage string `json:"cpu_usage"`
CPUClockSpeed float64 `json:"cpuClockSpeed"`
RAMUsage string `json:"ram_usage"`
TotalStorage float64 `json:"totalStorage"`
UsedStorage float64 `json:"usedStorage"`
}
type CpuStat struct {
total uint64
idle uint64
}
func HandleHardwareInfo(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "Only GET requests are allowed", http.StatusMethodNotAllowed)
return
}
cpuUsage, err := getCPUUsage()
if err != nil {
http.Error(w, fmt.Sprintf("Error getting CPU usage: %s", err), http.StatusInternalServerError)
return
}
cpuClockSpeed, err := getCPUClockSpeed()
if err != nil {
http.Error(w, fmt.Sprintf("Error getting CPU clock speed: %s", err), http.StatusInternalServerError)
return
}
ramUsage, err := getRAMUsage()
if err != nil {
http.Error(w, fmt.Sprintf("Error getting RAM usage: %s", err), http.StatusInternalServerError)
return
}
totalStorage, usedStorage, err := getTotalAndUsedStorage()
if err != nil {
http.Error(w, fmt.Sprintf("Error getting total storage: %s", err), http.StatusInternalServerError)
return
}
stats := ServerStats{
CPUUsage: cpuUsage,
CPUClockSpeed: cpuClockSpeed,
RAMUsage: ramUsage,
TotalStorage: totalStorage,
UsedStorage: usedStorage,
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(stats)
}
func getCPUUsage() (string, error) {
firstMeasure, err := readCPUStat()
if err != nil {
return "", err
}
time.Sleep(500 * time.Millisecond)
secondMeasure, err := readCPUStat()
if err != nil {
return "", err
}
totalDelta := secondMeasure.total - firstMeasure.total
idleDelta := secondMeasure.idle - firstMeasure.idle
cpuUsage := 100.0 * (float64(totalDelta) - float64(idleDelta)) / float64(totalDelta)
return fmt.Sprintf("%.2f%%", cpuUsage), nil
}
func readCPUStat() (CpuStat, error) {
data, err := os.ReadFile("/proc/stat")
if err != nil {
return CpuStat{}, err
}
lines := strings.Split(string(data), "\n")
for _, line := range lines {
fields := strings.Fields(line)
if fields[0] == "cpu" {
numFields := len(fields)
var total uint64
var idle uint64
for i := 1; i < numFields; i++ {
val, err := strconv.ParseUint(fields[i], 10, 64)
if err != nil {
return CpuStat{}, err
}
total += val
if i == 4 {
idle = val
}
}
return CpuStat{total: total, idle: idle}, nil
}
}
return CpuStat{}, fmt.Errorf("cpu info not found")
}
func getCPUClockSpeed() (float64, error) {
file, err := os.Open("/proc/cpuinfo")
if err != nil {
return 0, err
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
if strings.HasPrefix(line, "cpu MHz") {
parts := strings.Split(line, ":")
if len(parts) == 2 {
speedStr := strings.TrimSpace(parts[1])
speed, err := strconv.ParseFloat(speedStr, 64)
if err != nil {
return 0, err
}
return speed, nil
}
}
}
if err := scanner.Err(); err != nil {
return 0, err
}
return 0, fmt.Errorf("CPU clock speed not found")
}
func getRAMUsage() (string, error) {
out, err := os.ReadFile("/proc/meminfo")
if err != nil {
return "", err
}
lines := strings.Split(string(out), "\n")
var memTotal, memAvailable uint64
for _, line := range lines {
fields := strings.Fields(line)
if len(fields) < 3 {
continue
}
switch fields[0] {
case "MemTotal:":
memTotal, err = strconv.ParseUint(fields[1], 10, 64)
if err != nil {
return "", err
}
case "MemAvailable:":
memAvailable, err = strconv.ParseUint(fields[1], 10, 64)
if err != nil {
return "", err
}
}
}
memUsed := memTotal - memAvailable
ramUsage := fmt.Sprintf("%d/%dMB (%.2f%%)", memUsed/1024, memTotal/1024, 100.0*float64(memUsed)/float64(memTotal))
return ramUsage, nil
}
func getTotalAndUsedStorage() (float64, float64, error) {
var stat syscall.Statfs_t
err := syscall.Statfs("/", &stat)
if err != nil {
return 0, 0, err
}
totalStorage := float64(stat.Blocks) * float64(stat.Bsize)
usedStorage := float64(stat.Blocks - stat.Bfree) * float64(stat.Bsize)
return totalStorage, usedStorage, nil
}