17
17
package statsutil
18
18
19
19
import (
20
+ "bufio"
21
+ "os"
22
+ "strconv"
23
+ "strings"
20
24
"time"
21
25
22
26
"github.com/vishvananda/netlink"
@@ -35,11 +39,10 @@ func calculateMemPercent(limit float64, usedNo float64) float64 {
35
39
}
36
40
37
41
func SetCgroupStatsFields (previousStats * ContainerStats , data * v1.Metrics , links []netlink.Link ) (StatsEntry , error ) {
38
-
39
42
cpuPercent := calculateCgroupCPUPercent (previousStats , data )
40
43
blkRead , blkWrite := calculateCgroupBlockIO (data )
41
44
mem := calculateCgroupMemUsage (data )
42
- memLimit := float64 (data .Memory .Usage .Limit )
45
+ memLimit := getCgroupMemLimit ( float64 (data .Memory .Usage .Limit ) )
43
46
memPercent := calculateMemPercent (memLimit , mem )
44
47
pidsStatsCurrent := data .Pids .Current
45
48
netRx , netTx := calculateCgroupNetwork (links )
@@ -59,11 +62,10 @@ func SetCgroupStatsFields(previousStats *ContainerStats, data *v1.Metrics, links
59
62
}
60
63
61
64
func SetCgroup2StatsFields (previousStats * ContainerStats , metrics * v2.Metrics , links []netlink.Link ) (StatsEntry , error ) {
62
-
63
65
cpuPercent := calculateCgroup2CPUPercent (previousStats , metrics )
64
66
blkRead , blkWrite := calculateCgroup2IO (metrics )
65
67
mem := calculateCgroup2MemUsage (metrics )
66
- memLimit := float64 (metrics .Memory .UsageLimit )
68
+ memLimit := getCgroupMemLimit ( float64 (metrics .Memory .UsageLimit ) )
67
69
memPercent := calculateMemPercent (memLimit , mem )
68
70
pidsStatsCurrent := metrics .Pids .Current
69
71
netRx , netTx := calculateCgroupNetwork (links )
@@ -82,6 +84,36 @@ func SetCgroup2StatsFields(previousStats *ContainerStats, metrics *v2.Metrics, l
82
84
83
85
}
84
86
87
+ func getCgroupMemLimit (memLimit float64 ) float64 {
88
+ if memLimit == float64 (^ uint64 (0 )) {
89
+ return getHostMemLimit ()
90
+ }
91
+ return memLimit
92
+ }
93
+
94
+ func getHostMemLimit () float64 {
95
+ file , err := os .Open ("/proc/meminfo" )
96
+ if err != nil {
97
+ return float64 (^ uint64 (0 ))
98
+ }
99
+ defer file .Close ()
100
+
101
+ scanner := bufio .NewScanner (file )
102
+ for scanner .Scan () {
103
+ if strings .HasPrefix (scanner .Text (), "MemTotal:" ) {
104
+ fields := strings .Fields (scanner .Text ())
105
+ if len (fields ) >= 2 {
106
+ memKb , err := strconv .ParseUint (fields [1 ], 10 , 64 )
107
+ if err == nil {
108
+ return float64 (memKb * 1024 ) // kB to bytes
109
+ }
110
+ }
111
+ break
112
+ }
113
+ }
114
+ return float64 (^ uint64 (0 ))
115
+ }
116
+
85
117
func calculateCgroupCPUPercent (previousStats * ContainerStats , metrics * v1.Metrics ) float64 {
86
118
var (
87
119
cpuPercent = 0.0
0 commit comments