@@ -22,8 +22,10 @@ import (
22
22
"github.com/pingcap/sysutil"
23
23
"github.com/pingcap/tidb/parser/terror"
24
24
"github.com/pingcap/tidb/util/cgroup"
25
+ "github.com/pingcap/tidb/util/logutil"
25
26
"github.com/pingcap/tidb/util/mathutil"
26
27
"github.com/shirou/gopsutil/v3/mem"
28
+ "go.uber.org/zap"
27
29
)
28
30
29
31
// MemTotal returns the total amount of RAM on this system
@@ -51,6 +53,10 @@ func MemTotalNormal() (uint64, error) {
51
53
if time .Since (t ) < 60 * time .Second {
52
54
return total , nil
53
55
}
56
+ return memTotalNormal ()
57
+ }
58
+
59
+ func memTotalNormal () (uint64 , error ) {
54
60
v , err := mem .VirtualMemory ()
55
61
if err != nil {
56
62
return v .Total , err
@@ -140,6 +146,7 @@ func MemUsedCGroup() (uint64, error) {
140
146
return memo , nil
141
147
}
142
148
149
+ // it is for test and init.
143
150
func init () {
144
151
if cgroup .InContainer () {
145
152
MemTotal = MemTotalCGroup
@@ -164,6 +171,37 @@ func init() {
164
171
terror .MustNil (err )
165
172
}
166
173
174
+ // InitMemoryHook initializes the memory hook.
175
+ // It is to solve the problem that tidb cannot read cgroup in the systemd.
176
+ // so if we are not in the container, we compare the cgroup memory limit and the physical memory,
177
+ // the cgroup memory limit is smaller, we use the cgroup memory hook.
178
+ func InitMemoryHook () {
179
+ if cgroup .InContainer () {
180
+ logutil .BgLogger ().Info ("use cgroup memory hook because TiDB is in the container" )
181
+ return
182
+ }
183
+ cgroupValue , err := cgroup .GetMemoryLimit ()
184
+ if err != nil {
185
+ return
186
+ }
187
+ physicalValue , err := memTotalNormal ()
188
+ if err != nil {
189
+ return
190
+ }
191
+ if physicalValue > cgroupValue && cgroupValue != 0 {
192
+ MemTotal = MemTotalCGroup
193
+ MemUsed = MemUsedCGroup
194
+ sysutil .RegisterGetMemoryCapacity (MemTotalCGroup )
195
+ logutil .BgLogger ().Info ("use cgroup memory hook" , zap .Int64 ("cgroupMemorySize" , int64 (cgroupValue )), zap .Int64 ("physicalMemorySize" , int64 (physicalValue )))
196
+ } else {
197
+ logutil .BgLogger ().Info ("use physical memory hook" , zap .Int64 ("cgroupMemorySize" , int64 (cgroupValue )), zap .Int64 ("physicalMemorySize" , int64 (physicalValue )))
198
+ }
199
+ _ , err = MemTotal ()
200
+ terror .MustNil (err )
201
+ _ , err = MemUsed ()
202
+ terror .MustNil (err )
203
+ }
204
+
167
205
// InstanceMemUsed returns the memory usage of this TiDB server
168
206
func InstanceMemUsed () (uint64 , error ) {
169
207
used , t := serverMemUsage .get ()
0 commit comments