/
memory.go
45 lines (34 loc) · 1.42 KB
/
memory.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
package nodelocal
import (
"fmt"
"time"
"github.com/shirou/gopsutil/mem"
"k8s.io/klog/v2"
"github.com/gocrane/crane/pkg/common"
"github.com/gocrane/crane/pkg/ensurance/collector/types"
)
const (
memoryCollectorName = "memory"
)
func init() {
registerCollector(memoryCollectorName, []types.MetricName{types.MetricNameMemoryTotalUsage, types.MetricNameMemoryTotalUtilization}, collectMemory)
}
func collectMemory(_ *nodeLocalContext) (map[string][]common.TimeSeries, error) {
var now = time.Now()
stat, err := mem.VirtualMemory()
if err != nil {
return nil, err
}
if stat == nil {
return nil, fmt.Errorf("memory stat is nil")
}
usage := stat.Total - stat.Available
usagePercent := float64(usage) / float64(stat.Total) * types.MaxPercentage
klog.V(6).Infof("MemoryCollector collected, total %d, Free %d, Available %d, usagePercent %.2f, usageCore %d",
stat.Total, stat.Free, stat.Available, usagePercent, usage)
var data = make(map[string][]common.TimeSeries, 2)
data[string(types.MetricNameMemoryTotalUsage)] = []common.TimeSeries{{Samples: []common.Sample{{Value: float64(usage), Timestamp: now.Unix()}}}}
data[string(types.MetricNameMemoryTotalUtilization)] = []common.TimeSeries{{Samples: []common.Sample{{Value: usagePercent, Timestamp: now.Unix()}}}}
data[string(types.MetricNameMemoryTotal)] = []common.TimeSeries{{Samples: []common.Sample{{Value: float64(stat.Total), Timestamp: now.Unix()}}}}
return data, nil
}