-
Notifications
You must be signed in to change notification settings - Fork 8
/
SystemMonitorDispatcher.go
87 lines (74 loc) · 2.47 KB
/
SystemMonitorDispatcher.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 main
import "net/http"
import "encoding/json"
import "time"
import "errors"
import "log"
type SystemStateRequest struct {
BasicRequest
}
type SystemMonitorResponse struct {
CPUUsage CPUAverage
MemSample MemSample
}
type SystemMonitorDispatcher struct {
lastCPUSample CPUSample
lastCPUAverage CPUAverage
measureJob BatchJob
lastRequestTime time.Time
}
func (serviceStateDispatcher *SystemMonitorDispatcher) getCPUUsage() CPUAverage {
lastCPUAverage := serviceStateDispatcher.lastCPUAverage
return lastCPUAverage
}
func (serviceStateDispatcher *SystemMonitorDispatcher) measureCPU() {
for {
serviceStateDispatcher.lastCPUAverage = GetCPUAverage(serviceStateDispatcher.lastCPUSample, GetCPUSample())
serviceStateDispatcher.lastCPUSample = GetCPUSample()
time.Sleep(500 * time.Millisecond)
secondLastRequest := time.Now().Sub(serviceStateDispatcher.lastRequestTime)
if secondLastRequest.Seconds() > 5 {
log.Println("info: sleep measure cpu job")
serviceStateDispatcher.measureJob.Stop()
}
}
}
func (serviceStateDispatcher *SystemMonitorDispatcher) StartMeasure() error {
serviceStateDispatcher.measureJob.Job = serviceStateDispatcher.measureCPU
serviceStateDispatcher.lastRequestTime = time.Now()
err := serviceStateDispatcher.measureJob.Start()
if err != nil {
stErr := "error: Can't start measure job"
log.Println(stErr)
return errors.New(stErr)
}
return nil
}
func (serviceStateDispatcher *SystemMonitorDispatcher) Stopmeasure() error {
err := serviceStateDispatcher.measureJob.Stop()
if err != nil {
stErr := "error: Can't start measure job"
log.Println(stErr)
return errors.New("error: Can't stop measure job\n")
}
return nil
}
func (serviceStateDispatcher *SystemMonitorDispatcher) Dispatch(request Request, responseWriter http.ResponseWriter, httpRequest *http.Request) error {
if !serviceStateDispatcher.measureJob.runJob {
log.Println("info: start measure cpu job")
serviceStateDispatcher.measureJob.Start()
}
systemInfo := SystemMonitorResponse{CPUUsage: serviceStateDispatcher.getCPUUsage(), MemSample: GetMemSample()}
js, err := json.Marshal(systemInfo)
if err != nil {
http.Error(responseWriter, err.Error(), http.StatusInternalServerError)
stErr := "error: Can't create system state response"
log.Println(stErr)
responseWriter.Write(js)
return errors.New(stErr)
}
responseWriter.Header().Set("Content-Type", "application/json")
responseWriter.Write(js)
serviceStateDispatcher.lastRequestTime = time.Now()
return nil
}