-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathheartbeat.go
More file actions
57 lines (49 loc) · 1.11 KB
/
Copy pathheartbeat.go
File metadata and controls
57 lines (49 loc) · 1.11 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
package main
import (
"math"
"time"
"github.com/shirou/gopsutil/v3/cpu"
"github.com/shirou/gopsutil/v3/disk"
"github.com/shirou/gopsutil/v3/mem"
)
func (s *Service) startHeartbeat(done <-chan struct{}) {
ticker := time.NewTicker(heartbeatInterval)
defer ticker.Stop()
for {
select {
case <-done:
return
case <-ticker.C:
s.sendHeartbeat()
}
}
}
func (s *Service) sendHeartbeat() {
cpuPct := 0.0
if pct, err := cpu.Percent(0, false); err == nil && len(pct) > 0 {
cpuPct = pct[0]
}
vm, _ := mem.VirtualMemory()
dk, _ := disk.Usage("/")
toGB := func(value uint64) int {
return int(math.Round(float64(value) / (1024 * 1024 * 1024)))
}
payload := map[string]interface{}{
"type": "heartbeat",
"usage": map[string]interface{}{
"cpu": math.Round(cpuPct),
"memory": map[string]interface{}{
"total": toGB(vm.Total),
"used": toGB(vm.Used),
"free": toGB(vm.Available),
},
"disk": map[string]interface{}{
"total": toGB(dk.Total),
"used": toGB(dk.Used),
"free": toGB(dk.Free),
},
},
"diagnostics": s.getDiagnosticsSnapshot(),
}
_ = s.sendJSON(payload)
}