forked from couchbase/indexing
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cpu.go
94 lines (71 loc) · 1.92 KB
/
cpu.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
package indexer
import (
"github.com/couchbase/indexing/secondary/logging"
"github.com/couchbase/indexing/secondary/system"
"math"
"sync/atomic"
"time"
)
//////////////////////////////////////////////////////////////
// Global Variable
//////////////////////////////////////////////////////////////
var cpuPercent uint64
//////////////////////////////////////////////////////////////
// Concrete Type/Struct
//////////////////////////////////////////////////////////////
type cpuCollector struct {
stats *system.SystemStats
}
//////////////////////////////////////////////////////////////
// Cpu Collector
//////////////////////////////////////////////////////////////
//
// Start Cpu collection
//
func StartCpuCollector() error {
collector := &cpuCollector{}
// open sigar for stats
stats, err := system.NewSystemStats()
if err != nil {
logging.Errorf("Fail to start cpu stat collector. Err=%v", err)
return err
}
collector.stats = stats
// skip the first one
collector.stats.ProcessCpuPercent()
// start stats collection
go collector.runCollectCpu()
return nil
}
//
// Gather Cpu
//
func (c *cpuCollector) runCollectCpu() {
//ticker := time.NewTicker(time.Second * 60)
ticker := time.NewTicker(time.Second * 1)
defer ticker.Stop()
count := 0
for range ticker.C {
pid, percent, err := c.stats.ProcessCpuPercent()
if err != nil {
logging.Debugf("Fail to get cpu percentage. Err=%v", err)
continue
}
count++
if count > 10 {
logging.Infof("cpuCollector: cpu percent %v for pid %v", percent, pid)
count = 0
}
updateCpuPercent(percent)
}
}
//////////////////////////////////////////////////////////////
// Global Function
//////////////////////////////////////////////////////////////
func updateCpuPercent(percent float64) {
atomic.StoreUint64(&cpuPercent, math.Float64bits(percent))
}
func getCpuPercent() float64 {
bits := atomic.LoadUint64(&cpuPercent)
return math.Float64frombits(bits)
}