Coverage Report

Created: 2025-05-11 16:41

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