Coverage Report

Created: 2026-06-12 10:27

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/util/mem_info.cpp
Line
Count
Source
1
// Licensed to the Apache Software Foundation (ASF) under one
2
// or more contributor license agreements.  See the NOTICE file
3
// distributed with this work for additional information
4
// regarding copyright ownership.  The ASF licenses this file
5
// to you under the Apache License, Version 2.0 (the
6
// "License"); you may not use this file except in compliance
7
// with the License.  You may obtain a copy of the License at
8
//
9
//   http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied.  See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
// This file is copied from
18
// https://github.com/apache/impala/blob/branch-2.9.0/be/src/util/mem-info.cc
19
// and modified by Doris
20
21
#include "util/mem_info.h"
22
23
#include "runtime/memory/cache_manager.h"
24
25
#ifdef __APPLE__
26
#include <sys/sysctl.h>
27
#endif
28
29
#include <absl/strings/str_split.h>
30
#include <bvar/bvar.h>
31
#include <fmt/format.h>
32
#include <gen_cpp/Metrics_types.h>
33
#include <gen_cpp/segment_v2.pb.h>
34
#include <jemalloc/jemalloc.h>
35
36
#include <algorithm>
37
#include <boost/algorithm/string/trim.hpp>
38
#include <fstream>
39
#include <unordered_map>
40
41
#include "common/cgroup_memory_ctl.h"
42
#include "common/config.h"
43
#include "common/status.h"
44
#include "runtime/memory/global_memory_arbitrator.h"
45
#include "util/cgroup_util.h"
46
#include "util/parse_util.h"
47
#include "util/pretty_printer.h"
48
#include "util/string_parser.hpp"
49
50
namespace doris {
51
52
bool MemInfo::_s_initialized = false;
53
std::atomic<int64_t> MemInfo::_s_physical_mem = std::numeric_limits<int64_t>::max();
54
std::atomic<int64_t> MemInfo::_s_mem_limit = std::numeric_limits<int64_t>::max();
55
std::atomic<int64_t> MemInfo::_s_soft_mem_limit = std::numeric_limits<int64_t>::max();
56
57
std::atomic<int64_t> MemInfo::_s_cgroup_mem_limit = std::numeric_limits<int64_t>::max();
58
std::atomic<int64_t> MemInfo::_s_cgroup_mem_usage = std::numeric_limits<int64_t>::min();
59
std::atomic<bool> MemInfo::_s_cgroup_mem_refresh_state = false;
60
int64_t MemInfo::_s_cgroup_mem_refresh_wait_times = 0;
61
62
static std::unordered_map<std::string, int64_t> _mem_info_bytes;
63
std::atomic<int64_t> MemInfo::_s_sys_mem_available = -1;
64
int64_t MemInfo::_s_sys_mem_available_low_water_mark = std::numeric_limits<int64_t>::min();
65
int64_t MemInfo::_s_sys_mem_available_warning_water_mark = std::numeric_limits<int64_t>::min();
66
std::atomic<int64_t> MemInfo::_s_process_minor_gc_size = -1;
67
std::atomic<int64_t> MemInfo::_s_process_full_gc_size = -1;
68
69
#ifndef __APPLE__
70
235k
void MemInfo::refresh_proc_meminfo() {
71
235k
    std::ifstream meminfo("/proc/meminfo", std::ios::in);
72
235k
    std::string line;
73
74
12.9M
    while (meminfo.good() && !meminfo.eof()) {
75
12.7M
        getline(meminfo, line);
76
12.7M
        std::vector<std::string> fields = absl::StrSplit(line, " ", absl::SkipWhitespace());
77
12.7M
        if (fields.size() < 2) {
78
235k
            continue;
79
235k
        }
80
12.4M
        std::string key = fields[0].substr(0, fields[0].size() - 1);
81
82
12.4M
        StringParser::ParseResult result;
83
12.4M
        auto mem_value =
84
12.4M
                StringParser::string_to_int<int64_t>(fields[1].data(), fields[1].size(), &result);
85
86
12.4M
        if (result == StringParser::PARSE_SUCCESS) {
87
12.4M
            if (fields.size() == 2) {
88
942k
                _mem_info_bytes[key] = mem_value;
89
11.5M
            } else if (fields[2] == "kB") {
90
11.5M
                _mem_info_bytes[key] = mem_value * 1024L;
91
11.5M
            }
92
12.4M
        }
93
12.4M
    }
94
235k
    if (meminfo.is_open()) {
95
235k
        meminfo.close();
96
235k
    }
97
235k
    _s_cgroup_mem_refresh_state = false;
98
    // refresh cgroup memory
99
235k
    if (config::enable_use_cgroup_memory_info) {
100
235k
        if (_s_cgroup_mem_refresh_wait_times >= 0) {
101
2.33k
            int64_t cgroup_mem_limit;
102
2.33k
            auto status = CGroupMemoryCtl::find_cgroup_mem_limit(&cgroup_mem_limit);
103
2.33k
            if (!status.ok()) {
104
0
                _s_cgroup_mem_limit = std::numeric_limits<int64_t>::max();
105
                // find cgroup limit failed, wait 300s, 1000 * 100ms.
106
0
                _s_cgroup_mem_refresh_wait_times = -3000;
107
0
                LOG(WARNING)
108
0
                        << "Refresh cgroup memory limit failed, refresh again after 300s, cgroup "
109
0
                           "mem limit: "
110
0
                        << _s_cgroup_mem_limit << ", " << status;
111
2.33k
            } else {
112
2.33k
                _s_cgroup_mem_limit = cgroup_mem_limit;
113
                // wait 10s, 100 * 100ms, avoid too frequently.
114
2.33k
                _s_cgroup_mem_refresh_wait_times = -100;
115
2.33k
            }
116
233k
        } else {
117
233k
            _s_cgroup_mem_refresh_wait_times++;
118
233k
        }
119
120
        // cgroup mem limit is refreshed every 10 seconds,
121
        // cgroup mem usage is refreshed together with memInfo every time, which is very frequent.
122
        // If _s_cgroup_mem_limit == max, it means get cgroup mem limit failed OR the cgroup has no memory limit for example
123
        // there is just "max" in memory.max file.
124
235k
        if (_s_cgroup_mem_limit != std::numeric_limits<int64_t>::max()) {
125
235k
            int64_t cgroup_mem_usage;
126
235k
            auto status = CGroupMemoryCtl::find_cgroup_mem_usage(&cgroup_mem_usage);
127
235k
            if (!status.ok()) {
128
0
                _s_cgroup_mem_usage = std::numeric_limits<int64_t>::min();
129
0
                LOG_EVERY_N(WARNING, 500)
130
0
                        << "Refresh cgroup memory usage failed, cgroup mem limit: "
131
0
                        << _s_cgroup_mem_limit << ", " << status;
132
235k
            } else {
133
235k
                _s_cgroup_mem_usage = cgroup_mem_usage;
134
235k
                _s_cgroup_mem_refresh_state = true;
135
235k
            }
136
235k
        }
137
235k
    }
138
139
    // 1. calculate physical_mem
140
235k
    int64_t physical_mem = -1;
141
235k
    if (_mem_info_bytes.find("MemTotal") != _mem_info_bytes.end()) {
142
235k
        physical_mem = _mem_info_bytes["MemTotal"];
143
235k
    }
144
235k
    if (_s_cgroup_mem_refresh_state) {
145
        // In theory, always cgroup_mem_limit < physical_mem
146
235k
        if (physical_mem < 0) {
147
0
            physical_mem = _s_cgroup_mem_limit;
148
235k
        } else {
149
235k
            physical_mem =
150
235k
                    std::min(physical_mem, _s_cgroup_mem_limit.load(std::memory_order_relaxed));
151
235k
        }
152
235k
    }
153
154
235k
    if (physical_mem <= 0) {
155
0
        LOG(WARNING)
156
0
                << "Could not determine amount of physical memory on this machine, physical_mem: "
157
0
                << physical_mem;
158
0
    }
159
160
    // 2. if physical_mem changed, refresh mem limit and gc size.
161
235k
    if (physical_mem > 0 && _s_physical_mem.load(std::memory_order_relaxed) != physical_mem) {
162
8
        if (_s_physical_mem != std::numeric_limits<int64_t>::max()) {
163
            // After MemInfo is initialized, if physical memory changed, reset initial capacity of all caches.
164
0
            CacheManager::instance()->for_each_cache_reset_initial_capacity(
165
0
                    physical_mem / (_s_physical_mem * 1.0));
166
0
        }
167
168
8
        _s_physical_mem.store(physical_mem);
169
170
8
        bool is_percent = true;
171
8
        _s_mem_limit.store(
172
8
                ParseUtil::parse_mem_spec(config::mem_limit, -1, _s_physical_mem, &is_percent));
173
8
        if (_s_mem_limit <= 0) {
174
0
            LOG(WARNING) << "Failed to parse mem limit from '" + config::mem_limit + "'.";
175
0
        }
176
8
        if (_s_mem_limit > _s_physical_mem) {
177
0
            LOG(WARNING) << "Memory limit " << PrettyPrinter::print(_s_mem_limit, TUnit::BYTES)
178
0
                         << " exceeds physical memory of "
179
0
                         << PrettyPrinter::print(_s_physical_mem, TUnit::BYTES)
180
0
                         << ". Using physical memory instead";
181
0
            _s_mem_limit.store(_s_physical_mem);
182
0
        }
183
8
        _s_soft_mem_limit.store(int64_t(_s_mem_limit * config::soft_mem_limit_frac));
184
185
8
        _s_process_minor_gc_size.store(ParseUtil::parse_mem_spec(config::process_minor_gc_size, -1,
186
8
                                                                 _s_mem_limit, &is_percent));
187
8
        _s_process_full_gc_size.store(ParseUtil::parse_mem_spec(config::process_full_gc_size, -1,
188
8
                                                                _s_mem_limit, &is_percent));
189
8
    }
190
191
    // 3. refresh process available memory
192
235k
    int64_t mem_available = -1;
193
235k
    if (_mem_info_bytes.find("MemAvailable") != _mem_info_bytes.end()) {
194
235k
        mem_available = _mem_info_bytes["MemAvailable"];
195
235k
    }
196
235k
    if (_s_cgroup_mem_refresh_state) {
197
        // Note, CgroupV2 MemAvailable is usually a little smaller than Process MemAvailable.
198
        // Process `MemAvailable = MemFree - LowWaterMark + (PageCache - min(PageCache / 2, LowWaterMark))`,
199
        // from `MemAvailable` in `/proc/meminfo`, calculated by OS.
200
        // CgroupV2 `MemAvailable = cgroup_mem_limit - cgroup_mem_usage`,
201
        // `cgroup_mem_usage = memory.current - inactive_file - active_file - slab_reclaimable`, in fact,
202
        // there seems to be some memory that can be reused in `cgroup_mem_usage`.
203
235k
        if (mem_available < 0) {
204
0
            mem_available = _s_cgroup_mem_limit - _s_cgroup_mem_usage;
205
235k
        } else {
206
235k
            mem_available = std::min(mem_available, _s_cgroup_mem_limit - _s_cgroup_mem_usage);
207
235k
        }
208
235k
    }
209
235k
    if (mem_available < 0) {
210
0
        LOG(WARNING) << "Failed to get available memory, set MAX_INT.";
211
0
        mem_available = std::numeric_limits<int64_t>::max();
212
0
    }
213
235k
    if (_s_sys_mem_available.load(std::memory_order_relaxed) != mem_available) {
214
224k
        _s_sys_mem_available.store(mem_available);
215
224k
    }
216
235k
}
217
218
8
void MemInfo::init() {
219
8
    refresh_proc_meminfo();
220
221
8
    std::string line;
222
8
    int64_t _s_vm_min_free_kbytes = 0;
223
8
    std::ifstream vminfo("/proc/sys/vm/min_free_kbytes", std::ios::in);
224
8
    if (vminfo.good() && !vminfo.eof()) {
225
8
        getline(vminfo, line);
226
8
        boost::algorithm::trim(line);
227
8
        StringParser::ParseResult result;
228
8
        auto mem_value = StringParser::string_to_int<int64_t>(line.data(), line.size(), &result);
229
230
8
        if (result == StringParser::PARSE_SUCCESS) {
231
8
            _s_vm_min_free_kbytes = mem_value * 1024L;
232
8
        }
233
8
    }
234
8
    if (vminfo.is_open()) {
235
8
        vminfo.close();
236
8
    }
237
238
    // Redhat 4.x OS, `/proc/meminfo` has no `MemAvailable`.
239
8
    if (_mem_info_bytes.find("MemAvailable") != _mem_info_bytes.end()) {
240
        // MemAvailable = MemFree - LowWaterMark + (PageCache - min(PageCache / 2, LowWaterMark))
241
        // LowWaterMark = /proc/sys/vm/min_free_kbytes
242
        // Ref:
243
        // https://serverfault.com/questions/940196/why-is-memavailable-a-lot-less-than-memfreebufferscached
244
        // https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=34e431b0ae398fc54ea69ff85ec700722c9da773
245
        //
246
        // smaller sys_mem_available_low_water_mark can avoid wasting too much memory.
247
8
        _s_sys_mem_available_low_water_mark =
248
8
                config::max_sys_mem_available_low_water_mark_bytes != -1
249
8
                        ? config::max_sys_mem_available_low_water_mark_bytes
250
8
                        : std::min<int64_t>(_s_physical_mem - _s_mem_limit,
251
2
                                            int64_t(_s_physical_mem * 0.05));
252
8
        _s_sys_mem_available_warning_water_mark = _s_sys_mem_available_low_water_mark * 2;
253
8
    }
254
255
8
    std::ifstream sys_transparent_hugepage("/sys/kernel/mm/transparent_hugepage/enabled",
256
8
                                           std::ios::in);
257
8
    std::string hugepage_enable;
258
    // If file not exist, getline returns an empty string.
259
8
    getline(sys_transparent_hugepage, hugepage_enable);
260
8
    if (sys_transparent_hugepage.is_open()) {
261
8
        sys_transparent_hugepage.close();
262
8
    }
263
8
    if (hugepage_enable == "[always] madvise never") {
264
0
        std::cout << "[WARNING!] /sys/kernel/mm/transparent_hugepage/enabled: " << hugepage_enable
265
0
                  << ", Doris not recommend turning on THP, which may cause the BE process to use "
266
0
                     "more memory and cannot be freed in time. Turn off THP: `echo madvise | sudo "
267
0
                     "tee /sys/kernel/mm/transparent_hugepage/enabled`"
268
0
                  << std::endl;
269
0
    }
270
271
    // Expect vm overcommit memory value to be 1, system will no longer throw bad_alloc, memory alloc are always accepted,
272
    // memory limit check is handed over to Doris Allocator, make sure throw exception position is controllable,
273
    // otherwise bad_alloc can be thrown anywhere and it will be difficult to achieve exception safety.
274
8
    std::ifstream sys_vm("/proc/sys/vm/overcommit_memory", std::ios::in);
275
8
    std::string vm_overcommit;
276
8
    getline(sys_vm, vm_overcommit);
277
8
    if (sys_vm.is_open()) {
278
8
        sys_vm.close();
279
8
    }
280
8
    if (!vm_overcommit.empty() && std::stoi(vm_overcommit) == 2) {
281
0
        std::cout << "[WARNING!] /proc/sys/vm/overcommit_memory: " << vm_overcommit
282
0
                  << ", expect is 1, memory limit check is handed over to Doris Allocator, "
283
0
                     "otherwise BE may crash even with remaining memory"
284
0
                  << std::endl;
285
0
    }
286
287
8
    LOG(INFO) << "Physical Memory: " << _mem_info_bytes["MemTotal"]
288
8
              << ", BE Available Physical Memory(consider cgroup): "
289
8
              << PrettyPrinter::print(_s_physical_mem, TUnit::BYTES) << ", Mem Limit: "
290
8
              << PrettyPrinter::print(_s_mem_limit.load(std::memory_order_relaxed), TUnit::BYTES)
291
8
              << ", origin config value: " << config::mem_limit
292
8
              << ", System Mem Available Min Reserve: "
293
8
              << PrettyPrinter::print(_s_sys_mem_available_low_water_mark, TUnit::BYTES)
294
8
              << ", Vm Min Free KBytes: "
295
8
              << PrettyPrinter::print(_s_vm_min_free_kbytes, TUnit::BYTES)
296
8
              << ", Vm Overcommit Memory: " << vm_overcommit;
297
8
    _s_initialized = true;
298
8
}
299
#else
300
void MemInfo::refresh_proc_meminfo() {}
301
302
void MemInfo::init() {
303
    size_t size = sizeof(_s_physical_mem);
304
    if (sysctlbyname("hw.memsize", &_s_physical_mem, &size, nullptr, 0) != 0) {
305
        LOG(WARNING) << "Could not determine amount of physical memory on this machine.";
306
        _s_physical_mem = -1;
307
    }
308
309
    bool is_percent = true;
310
    _s_mem_limit = ParseUtil::parse_mem_spec(config::mem_limit, -1, _s_physical_mem, &is_percent);
311
    _s_soft_mem_limit = static_cast<int64_t>(_s_mem_limit * config::soft_mem_limit_frac);
312
313
    LOG(INFO) << "Physical Memory: " << PrettyPrinter::print(_s_physical_mem, TUnit::BYTES);
314
    _s_initialized = true;
315
}
316
#endif
317
318
7
std::string MemInfo::debug_string() {
319
    DCHECK(_s_initialized);
320
7
    std::stringstream stream;
321
7
    stream << "Physical Memory: " << PrettyPrinter::print(_s_physical_mem, TUnit::BYTES)
322
7
           << std::endl;
323
7
    stream << "Memory Limt: " << PrettyPrinter::print(_s_mem_limit, TUnit::BYTES) << std::endl;
324
7
    stream << "CGroup Info: " << doris::CGroupMemoryCtl::debug_string() << std::endl;
325
7
    return stream.str();
326
7
}
327
328
} // namespace doris