Coverage Report

Created: 2025-04-11 14:35

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