-
Notifications
You must be signed in to change notification settings - Fork 0
/
server_stats.go
69 lines (64 loc) · 1.82 KB
/
server_stats.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
package server
import (
"runtime"
velox "github.com/jpillora/velox/go"
"github.com/shirou/gopsutil/cpu"
"github.com/shirou/gopsutil/disk"
"github.com/shirou/gopsutil/mem"
)
type stats struct {
Set bool `json:"set"`
CPU float64 `json:"cpu"`
DiskUsed int64 `json:"diskUsed"`
DiskTotal int64 `json:"diskTotal"`
MemoryUsed int64 `json:"memoryUsed"`
MemoryTotal int64 `json:"memoryTotal"`
GoMemory int64 `json:"goMemory"`
GoRoutines int `json:"goRoutines"`
//internal
lastCPUStat *cpu.CPUTimesStat
pusher velox.Pusher
}
func (s *stats) loadStats(diskDir string) {
//count cpu cycles between last count
if stats, err := cpu.CPUTimes(false); err == nil {
stat := stats[0]
total := totalCPUTime(stat)
last := s.lastCPUStat
if last != nil {
lastTotal := totalCPUTime(*last)
if lastTotal != 0 {
totalDelta := total - lastTotal
if totalDelta > 0 {
idleDelta := (stat.Iowait + stat.Idle) - (last.Iowait + last.Idle)
usedDelta := (totalDelta - idleDelta)
s.CPU = 100 * usedDelta / totalDelta
}
}
}
s.lastCPUStat = &stat
}
//count disk usage
if stat, err := disk.DiskUsage(diskDir); err == nil {
s.DiskUsed = int64(stat.Used)
s.DiskTotal = int64(stat.Total)
}
//count memory usage
if stat, err := mem.VirtualMemory(); err == nil {
s.MemoryUsed = int64(stat.Used)
s.MemoryTotal = int64(stat.Total)
}
//count total bytes allocated by the go runtime
memStats := runtime.MemStats{}
runtime.ReadMemStats(&memStats)
s.GoMemory = int64(memStats.Alloc)
//count current number of goroutines
s.GoRoutines = runtime.NumGoroutine()
//done
s.Set = true
s.pusher.Push()
}
func totalCPUTime(t cpu.CPUTimesStat) float64 {
total := t.User + t.System + t.Nice + t.Iowait + t.Irq + t.Softirq + t.Steal + t.Guest + t.GuestNice + t.Idle
return total
}