-
Notifications
You must be signed in to change notification settings - Fork 17
/
cpu_utilisation_analyser.go
87 lines (72 loc) · 2.18 KB
/
cpu_utilisation_analyser.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
package cagent
import (
"os"
"os/signal"
"syscall"
"time"
log "github.com/sirupsen/logrus"
"github.com/cloudradar-monitoring/cagent/pkg/common"
"github.com/cloudradar-monitoring/cagent/pkg/monitoring/top"
)
type CPUUtilisationAnalyser struct {
NumberOfProcesses int
top *top.Top
topIsRunning bool
hasUnclaimedResults bool
}
func (ca *Cagent) CPUUtilisationAnalyser() *CPUUtilisationAnalyser {
if ca.cpuUtilisationAnalyser != nil {
return ca.cpuUtilisationAnalyser
}
cfg := ca.Config.CPUUtilisationAnalysis
if cfg.Threshold < 0 || cfg.Metric == "" || cfg.Function == "" || cfg.GatheringMode == "" || cfg.ReportProcesses == 0 {
return &CPUUtilisationAnalyser{}
}
sigc := make(chan os.Signal, 1)
signal.Notify(sigc,
syscall.SIGHUP,
syscall.SIGINT,
syscall.SIGTERM)
cuan := CPUUtilisationAnalyser{NumberOfProcesses: cfg.ReportProcesses}
ca.cpuUtilisationAnalyser = &cuan
cuan.top = top.New()
thresholdChan := make(chan float64)
err := ca.cpuWatcher.AddThresholdNotifier(cfg.Threshold, cfg.Metric, cfg.Function, cfg.GatheringMode, thresholdChan)
if err != nil {
log.Error("[CPU_ANALYSIS] addThresholdNotifier error", err.Error())
return ca.cpuUtilisationAnalyser
}
go func() {
for {
select {
case x := <-thresholdChan:
log.Debugf("[CPU_ANALYSIS] CPU threshold signal(%.2f) received from chan", x)
if !cuan.topIsRunning {
go cuan.top.Run()
cuan.topIsRunning = true
}
break
case <-time.After(time.Duration(cfg.TrailingProcessAnalysisMinutes) * time.Minute):
if cuan.topIsRunning {
log.Debugf("[CPU_ANALYSIS] TrailingRecoveryTime reached")
cuan.hasUnclaimedResults = true
cuan.topIsRunning = false
cuan.top.Stop()
}
break
case <-sigc:
log.Debugf("[CPU_ANALYSIS] got interrupt signal")
return
}
}
}()
return ca.cpuUtilisationAnalyser
}
func (cuan *CPUUtilisationAnalyser) Results() (common.MeasurementsMap, bool, error) {
if cuan.top == nil || !cuan.hasUnclaimedResults && !cuan.topIsRunning {
return nil, false, nil
}
cuan.hasUnclaimedResults = false
topProcs := cuan.top.HighestNLoad(cuan.NumberOfProcesses)
return common.MeasurementsMap{"top": topProcs}, true, nil
}