-
Notifications
You must be signed in to change notification settings - Fork 439
/
sys_metric_stat.go
273 lines (237 loc) · 6.21 KB
/
sys_metric_stat.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
// Copyright 1999-2020 Alibaba Group Holding Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package system_metric
import (
"os"
"sync"
"sync/atomic"
"time"
metric_exporter "github.com/alibaba/sentinel-golang/exporter/metric"
"github.com/alibaba/sentinel-golang/logging"
"github.com/alibaba/sentinel-golang/util"
"github.com/shirou/gopsutil/v3/load"
"github.com/shirou/gopsutil/v3/mem"
"github.com/shirou/gopsutil/v3/process"
)
const (
NotRetrievedLoadValue float64 = -1.0
NotRetrievedCpuUsageValue float64 = -1.0
NotRetrievedMemoryValue int64 = -1
)
var (
currentLoad atomic.Value
currentCpuUsage atomic.Value
currentMemoryUsage atomic.Value
loadStatCollectorOnce sync.Once
memoryStatCollectorOnce sync.Once
cpuStatCollectorOnce sync.Once
CurrentPID = os.Getpid()
currentProcess atomic.Value
currentProcessOnce sync.Once
TotalMemorySize = getTotalMemorySize()
ssStopChan = make(chan struct{})
cpuRatioGauge = metric_exporter.NewGauge(
"cpu_ratio",
"Process cpu ratio",
[]string{})
processMemoryGauge = metric_exporter.NewGauge(
"process_memory_bytes",
"Process memory in bytes",
[]string{})
)
func init() {
currentLoad.Store(NotRetrievedLoadValue)
currentCpuUsage.Store(NotRetrievedCpuUsageValue)
currentMemoryUsage.Store(NotRetrievedMemoryValue)
p, err := process.NewProcess(int32(CurrentPID))
if err != nil {
logging.Error(err, "Fail to new process when initializing system metric", "pid", CurrentPID)
return
}
currentProcessOnce.Do(func() {
currentProcess.Store(p)
})
metric_exporter.Register(cpuRatioGauge)
metric_exporter.Register(processMemoryGauge)
}
// getMemoryStat returns the current machine's memory statistic
func getTotalMemorySize() (total uint64) {
stat, err := mem.VirtualMemory()
if err != nil {
logging.Error(err, "Fail to read Virtual Memory")
return 0
}
return stat.Total
}
func InitMemoryCollector(intervalMs uint32) {
if intervalMs == 0 {
return
}
memoryStatCollectorOnce.Do(func() {
// Initial memory retrieval.
retrieveAndUpdateMemoryStat()
ticker := util.NewTicker(time.Duration(intervalMs) * time.Millisecond)
go util.RunWithRecover(func() {
for {
select {
case <-ticker.C():
retrieveAndUpdateMemoryStat()
case <-ssStopChan:
ticker.Stop()
return
}
}
})
})
}
func retrieveAndUpdateMemoryStat() {
memoryUsedBytes, err := GetProcessMemoryStat()
if err != nil {
logging.Error(err, "Fail to retrieve and update memory statistic")
return
}
processMemoryGauge.Set(float64(memoryUsedBytes))
currentMemoryUsage.Store(memoryUsedBytes)
}
// GetProcessMemoryStat gets current process's memory usage in Bytes
func GetProcessMemoryStat() (int64, error) {
curProcess := currentProcess.Load()
if curProcess == nil {
p, err := process.NewProcess(int32(CurrentPID))
if err != nil {
return 0, err
}
currentProcessOnce.Do(func() {
currentProcess.Store(p)
})
curProcess = currentProcess.Load()
}
p := curProcess.(*process.Process)
memInfo, err := p.MemoryInfo()
var rss int64
if memInfo != nil {
rss = int64(memInfo.RSS)
}
return rss, err
}
func InitCpuCollector(intervalMs uint32) {
if intervalMs == 0 {
return
}
cpuStatCollectorOnce.Do(func() {
// Initial memory retrieval.
retrieveAndUpdateCpuStat()
ticker := util.NewTicker(time.Duration(intervalMs) * time.Millisecond)
go util.RunWithRecover(func() {
for {
select {
case <-ticker.C():
retrieveAndUpdateCpuStat()
case <-ssStopChan:
ticker.Stop()
return
}
}
})
})
}
func retrieveAndUpdateCpuStat() {
cpuPercent, err := getProcessCpuStat()
if err != nil {
logging.Error(err, "Fail to retrieve and update cpu statistic")
return
}
cpuRatioGauge.Set(cpuPercent)
currentCpuUsage.Store(cpuPercent)
}
// getProcessCpuStat gets current process's cpu usage in percentage
func getProcessCpuStat() (float64, error) {
curProcess := currentProcess.Load()
if curProcess == nil {
p, err := process.NewProcess(int32(CurrentPID))
if err != nil {
return 0, err
}
currentProcessOnce.Do(func() {
currentProcess.Store(p)
})
curProcess = currentProcess.Load()
}
p := curProcess.(*process.Process)
return p.Percent(0)
}
func InitLoadCollector(intervalMs uint32) {
if intervalMs == 0 {
return
}
loadStatCollectorOnce.Do(func() {
// Initial retrieval.
retrieveAndUpdateLoadStat()
ticker := util.NewTicker(time.Duration(intervalMs) * time.Millisecond)
go util.RunWithRecover(func() {
for {
select {
case <-ticker.C():
retrieveAndUpdateLoadStat()
case <-ssStopChan:
ticker.Stop()
return
}
}
})
})
}
func retrieveAndUpdateLoadStat() {
loadStat, err := load.Avg()
if err != nil {
logging.Error(err, "[retrieveAndUpdateSystemStat] Failed to retrieve current system load")
return
}
if loadStat != nil {
currentLoad.Store(loadStat.Load1)
}
}
func CurrentLoad() float64 {
r, ok := currentLoad.Load().(float64)
if !ok {
return NotRetrievedLoadValue
}
return r
}
// Note: SetSystemLoad is used for unit test, the user shouldn't call this function.
func SetSystemLoad(load float64) {
currentLoad.Store(load)
}
func CurrentCpuUsage() float64 {
r, ok := currentCpuUsage.Load().(float64)
if !ok {
return NotRetrievedCpuUsageValue
}
return r
}
// Note: SetSystemCpuUsage is used for unit test, the user shouldn't call this function.
func SetSystemCpuUsage(cpuUsage float64) {
currentCpuUsage.Store(cpuUsage)
}
func CurrentMemoryUsage() int64 {
bytes, ok := currentMemoryUsage.Load().(int64)
if !ok {
return NotRetrievedMemoryValue
}
return bytes
}
// Note: SetSystemCpuUsage is used for unit test, the user shouldn't call this function.
func SetSystemMemoryUsage(memoryUsage int64) {
currentMemoryUsage.Store(memoryUsage)
}