Coverage Report

Created: 2026-08-21 16:12

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/root/doris/be/src/common/daemon.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
18
#include "common/daemon.h"
19
20
// IWYU pragma: no_include <bthread/errno.h>
21
#include <errno.h> // IWYU pragma: keep
22
#include <gflags/gflags.h>
23
24
#include "runtime/memory/jemalloc_control.h"
25
#if !defined(__SANITIZE_ADDRESS__) && !defined(ADDRESS_SANITIZER) && !defined(LEAK_SANITIZER) && \
26
        !defined(THREAD_SANITIZER) && !defined(USE_JEMALLOC)
27
#include <gperftools/malloc_extension.h> // IWYU pragma: keep
28
#endif
29
// IWYU pragma: no_include <bits/std_abs.h>
30
#include <butil/iobuf.h>
31
#include <math.h>
32
#include <stdint.h>
33
#include <stdlib.h>
34
35
// IWYU pragma: no_include <bits/chrono.h>
36
#include <chrono> // IWYU pragma: keep
37
#include <map>
38
#include <ostream>
39
#include <string>
40
41
#include "cloud/config.h"
42
#include "common/config.h"
43
#include "common/logging.h"
44
#include "common/metrics/doris_metrics.h"
45
#include "common/metrics/metrics.h"
46
#include "common/metrics/system_metrics.h"
47
#include "common/status.h"
48
#include "load/memtable/memtable_memory_limiter.h"
49
#include "runtime/be_proc_monitor.h"
50
#include "runtime/exec_env.h"
51
#include "runtime/fragment_mgr.h"
52
#include "runtime/memory/global_memory_arbitrator.h"
53
#include "runtime/memory/mem_tracker_limiter.h"
54
#include "runtime/memory/memory_reclamation.h"
55
#include "runtime/process_profile.h"
56
#include "runtime/runtime_query_statistics_mgr.h"
57
#include "runtime/workload_group/workload_group_manager.h"
58
#include "storage/storage_engine.h"
59
#include "storage/tablet/tablet_manager.h"
60
#include "util/algorithm_util.h"
61
#include "util/mem_info.h"
62
#include "util/perf_counters.h"
63
#include "util/s3_rate_limiter_manager.h"
64
#include "util/time.h"
65
66
namespace doris {
67
namespace {
68
69
std::atomic<int64_t> last_print_proc_mem = 0;
70
std::atomic<int32_t> refresh_cache_capacity_sleep_time_ms = 0;
71
std::atomic<int32_t> memory_gc_sleep_time = 0;
72
#ifdef USE_JEMALLOC
73
std::atomic<int32_t> je_reset_dirty_decay_sleep_time_ms = 0;
74
#endif
75
76
324
void update_rowsets_and_segments_num_metrics() {
77
324
    if (config::is_cloud_mode()) {
78
        // TODO(plat1ko): CloudStorageEngine
79
212
    } else {
80
112
        StorageEngine& engine = ExecEnv::GetInstance()->storage_engine().to_local();
81
112
        auto* metrics = DorisMetrics::instance();
82
112
        metrics->all_rowsets_num->set_value(engine.tablet_manager()->get_rowset_nums());
83
112
        metrics->all_segments_num->set_value(engine.tablet_manager()->get_segment_nums());
84
112
    }
85
324
}
86
87
} // namespace
88
89
7
void Daemon::tcmalloc_gc_thread() {
90
    // TODO All cache GC wish to be supported
91
#if !defined(ADDRESS_SANITIZER) && !defined(LEAK_SANITIZER) && !defined(THREAD_SANITIZER) && \
92
        !defined(USE_JEMALLOC)
93
94
    // Limit size of tcmalloc cache via release_rate and max_cache_percent.
95
    // We adjust release_rate according to memory_pressure, which is usage percent of memory.
96
    int64_t max_cache_percent = 60;
97
    double release_rates[10] = {1.0, 1.0, 1.0, 5.0, 5.0, 20.0, 50.0, 100.0, 500.0, 2000.0};
98
    int64_t pressure_limit = 90;
99
    bool is_performance_mode = false;
100
    int64_t physical_limit_bytes =
101
            std::min(MemInfo::physical_mem() - MemInfo::sys_mem_available_low_water_mark(),
102
                     MemInfo::mem_limit());
103
104
    if (config::memory_mode == std::string("performance")) {
105
        max_cache_percent = 100;
106
        pressure_limit = 90;
107
        is_performance_mode = true;
108
        physical_limit_bytes = std::min(MemInfo::mem_limit(), MemInfo::physical_mem());
109
    } else if (config::memory_mode == std::string("compact")) {
110
        max_cache_percent = 20;
111
        pressure_limit = 80;
112
    }
113
114
    int last_ms = 0;
115
    const int kMaxLastMs = 30000;
116
    const int kIntervalMs = 10;
117
    size_t init_aggressive_decommit = 0;
118
    size_t current_aggressive_decommit = 0;
119
    size_t expected_aggressive_decommit = 0;
120
    int64_t last_memory_pressure = 0;
121
122
    MallocExtension::instance()->GetNumericProperty("tcmalloc.aggressive_memory_decommit",
123
                                                    &init_aggressive_decommit);
124
    current_aggressive_decommit = init_aggressive_decommit;
125
126
    while (!_stop_background_threads_latch.wait_for(std::chrono::milliseconds(kIntervalMs))) {
127
        size_t tc_used_bytes = 0;
128
        size_t tc_alloc_bytes = 0;
129
        size_t rss = PerfCounters::get_vm_rss();
130
131
        MallocExtension::instance()->GetNumericProperty("generic.total_physical_bytes",
132
                                                        &tc_alloc_bytes);
133
        MallocExtension::instance()->GetNumericProperty("generic.current_allocated_bytes",
134
                                                        &tc_used_bytes);
135
        int64_t tc_cached_bytes = (int64_t)tc_alloc_bytes - (int64_t)tc_used_bytes;
136
        int64_t to_free_bytes =
137
                (int64_t)tc_cached_bytes - ((int64_t)tc_used_bytes * max_cache_percent / 100);
138
        to_free_bytes = std::max(to_free_bytes, (int64_t)0);
139
140
        int64_t memory_pressure = 0;
141
        int64_t rss_pressure = 0;
142
        int64_t alloc_bytes = std::max(rss, tc_alloc_bytes);
143
        memory_pressure = alloc_bytes * 100 / physical_limit_bytes;
144
        rss_pressure = rss * 100 / physical_limit_bytes;
145
146
        expected_aggressive_decommit = init_aggressive_decommit;
147
        if (memory_pressure > pressure_limit) {
148
            // We are reaching oom, so release cache aggressively.
149
            // Ideally, we should reuse cache and not allocate from system any more,
150
            // however, it is hard to set limit on cache of tcmalloc and doris
151
            // use mmap in vectorized mode.
152
            // Limit cache capactiy is enough.
153
            if (rss_pressure > pressure_limit) {
154
                int64_t min_free_bytes = alloc_bytes - physical_limit_bytes * 9 / 10;
155
                to_free_bytes = std::max(to_free_bytes, min_free_bytes);
156
                to_free_bytes = std::max(to_free_bytes, tc_cached_bytes * 30 / 100);
157
                // We assure that we have at least 500M bytes in cache.
158
                to_free_bytes = std::min(to_free_bytes, tc_cached_bytes - 500 * 1024 * 1024);
159
                expected_aggressive_decommit = 1;
160
            }
161
            last_ms = kMaxLastMs;
162
        } else if (memory_pressure > (pressure_limit - 10)) {
163
            // In most cases, adjusting release rate is enough, if memory are consumed quickly
164
            // we should release manually.
165
            if (last_memory_pressure <= (pressure_limit - 10)) {
166
                to_free_bytes = std::max(to_free_bytes, tc_cached_bytes * 10 / 100);
167
            }
168
        }
169
170
        int release_rate_index = int(memory_pressure) / 10;
171
        double release_rate = 1.0;
172
        if (release_rate_index >= sizeof(release_rates) / sizeof(release_rates[0])) {
173
            release_rate = 2000.0;
174
        } else {
175
            release_rate = release_rates[release_rate_index];
176
        }
177
        MallocExtension::instance()->SetMemoryReleaseRate(release_rate);
178
179
        if ((current_aggressive_decommit != expected_aggressive_decommit) && !is_performance_mode) {
180
            MallocExtension::instance()->SetNumericProperty("tcmalloc.aggressive_memory_decommit",
181
                                                            expected_aggressive_decommit);
182
            current_aggressive_decommit = expected_aggressive_decommit;
183
        }
184
185
        last_memory_pressure = memory_pressure;
186
        // We release at least 2% bytes once, frequent releasing hurts performance.
187
        if (to_free_bytes > (physical_limit_bytes * 2 / 100)) {
188
            last_ms += kIntervalMs;
189
            if (last_ms >= kMaxLastMs) {
190
                LOG(INFO) << "generic.current_allocated_bytes " << tc_used_bytes
191
                          << ", generic.total_physical_bytes " << tc_alloc_bytes << ", rss " << rss
192
                          << ", max_cache_percent " << max_cache_percent << ", release_rate "
193
                          << release_rate << ", memory_pressure " << memory_pressure
194
                          << ", physical_limit_bytes " << physical_limit_bytes << ", to_free_bytes "
195
                          << to_free_bytes << ", current_aggressive_decommit "
196
                          << current_aggressive_decommit;
197
                MallocExtension::instance()->ReleaseToSystem(to_free_bytes);
198
                last_ms = 0;
199
            }
200
        } else {
201
            last_ms = 0;
202
        }
203
    }
204
#endif
205
7
}
206
207
89.0k
void refresh_process_memory_metrics() {
208
89.0k
    doris::PerfCounters::refresh_proc_status();
209
89.0k
    doris::MemInfo::refresh_proc_meminfo();
210
89.0k
    doris::GlobalMemoryArbitrator::reset_refresh_interval_memory_growth();
211
89.0k
    ExecEnv::GetInstance()->brpc_iobuf_block_memory_tracker()->set_consumption(
212
89.0k
            butil::IOBuf::block_memory());
213
89.0k
}
214
215
89.0k
void refresh_common_allocator_metrics() {
216
#if !defined(ADDRESS_SANITIZER) && !defined(LEAK_SANITIZER) && !defined(THREAD_SANITIZER)
217
    doris::JemallocControl::refresh_allocator_mem();
218
    if (config::enable_system_metrics) {
219
        DorisMetrics::instance()->system_metrics()->update_allocator_metrics();
220
    }
221
#endif
222
89.0k
    doris::GlobalMemoryArbitrator::refresh_memory_bvar();
223
89.0k
}
224
225
89.0k
void refresh_memory_state_after_memory_change() {
226
89.0k
    if (abs(last_print_proc_mem - PerfCounters::get_vm_rss()) > 268435456) {
227
510
        last_print_proc_mem = PerfCounters::get_vm_rss();
228
510
        doris::MemTrackerLimiter::clean_tracker_limiter_group();
229
510
        doris::ProcessProfile::instance()->memory_profile()->enable_print_log_process_usage();
230
510
        doris::ProcessProfile::instance()->memory_profile()->refresh_memory_overview_profile();
231
510
        doris::JemallocControl::notify_je_purge_dirty_pages();
232
510
        LOG(INFO) << doris::GlobalMemoryArbitrator::
233
510
                        process_mem_log_str(); // print mem log when memory state by 256M
234
510
    }
235
89.0k
}
236
237
89.0k
void refresh_cache_capacity() {
238
89.0k
    if (doris::GlobalMemoryArbitrator::cache_adjust_capacity_notify.load(
239
89.0k
                std::memory_order_relaxed)) {
240
        // the last cache capacity adjustment has not been completed.
241
        // if not return, last_periodic_refreshed_cache_capacity_adjust_weighted may be modified, but notify is ignored.
242
0
        return;
243
0
    }
244
89.0k
    if (refresh_cache_capacity_sleep_time_ms <= 0) {
245
89.0k
        auto cache_capacity_reduce_mem_limit = int64_t(
246
89.0k
                doris::MemInfo::soft_mem_limit() * config::cache_capacity_reduce_mem_limit_frac);
247
89.0k
        int64_t process_memory_usage = doris::GlobalMemoryArbitrator::process_memory_usage();
248
        // the rule is like this:
249
        // 1. if the process mem usage < soft memlimit * 0.6, then do not need adjust cache capacity.
250
        // 2. if the process mem usage > soft memlimit * 0.6 and process mem usage < soft memlimit, then it will be adjusted to a lower value.
251
        // 3. if the process mem usage > soft memlimit, then the capacity is adjusted to 0.
252
89.0k
        double new_cache_capacity_adjust_weighted =
253
89.0k
                AlgoUtil::descent_by_step(10, cache_capacity_reduce_mem_limit,
254
89.0k
                                          doris::MemInfo::soft_mem_limit(), process_memory_usage);
255
89.0k
        if (new_cache_capacity_adjust_weighted !=
256
89.0k
            doris::GlobalMemoryArbitrator::last_periodic_refreshed_cache_capacity_adjust_weighted) {
257
0
            doris::GlobalMemoryArbitrator::last_periodic_refreshed_cache_capacity_adjust_weighted =
258
0
                    new_cache_capacity_adjust_weighted;
259
0
            doris::GlobalMemoryArbitrator::notify_cache_adjust_capacity();
260
0
            refresh_cache_capacity_sleep_time_ms = config::memory_gc_sleep_time_ms;
261
89.0k
        } else {
262
89.0k
            refresh_cache_capacity_sleep_time_ms = 0;
263
89.0k
        }
264
89.0k
    }
265
89.0k
    refresh_cache_capacity_sleep_time_ms -= config::memory_maintenance_sleep_time_ms;
266
89.0k
}
267
268
89.0k
void je_reset_dirty_decay() {
269
#ifdef USE_JEMALLOC
270
    if (doris::JemallocControl::je_reset_dirty_decay_notify.load(std::memory_order_relaxed)) {
271
        // if not return, je_enable_dirty_page may be modified, but notify is ignored.
272
        return;
273
    }
274
275
    if (je_reset_dirty_decay_sleep_time_ms <= 0) {
276
        bool new_je_enable_dirty_page = true;
277
        if (doris::JemallocControl::je_enable_dirty_page) {
278
            // if Jemalloc dirty page is enabled and process memory exceed soft mem limit,
279
            // disable Jemalloc dirty page.
280
            new_je_enable_dirty_page = !GlobalMemoryArbitrator::is_exceed_soft_mem_limit();
281
        } else {
282
            // if Jemalloc dirty page is disabled and 10% free memory left to exceed soft mem limit,
283
            // enable Jemalloc dirty page, this is to avoid frequent changes
284
            // between enabling and disabling Jemalloc dirty pages, if the process memory does
285
            // not exceed the soft mem limit after turning off Jemalloc dirty pages,
286
            // but it will exceed soft mem limit after turning it on.
287
            new_je_enable_dirty_page = !GlobalMemoryArbitrator::is_exceed_soft_mem_limit(
288
                    int64_t(doris::MemInfo::soft_mem_limit() * 0.1));
289
        }
290
291
        if (doris::JemallocControl::je_enable_dirty_page != new_je_enable_dirty_page) {
292
            // `notify_je_reset_dirty_decay` only if `je_enable_dirty_page` changes.
293
            doris::JemallocControl::je_enable_dirty_page = new_je_enable_dirty_page;
294
            doris::JemallocControl::notify_je_reset_dirty_decay();
295
            je_reset_dirty_decay_sleep_time_ms = config::memory_gc_sleep_time_ms;
296
        } else {
297
            je_reset_dirty_decay_sleep_time_ms = 0;
298
        }
299
    }
300
    je_reset_dirty_decay_sleep_time_ms -= config::memory_maintenance_sleep_time_ms;
301
#endif
302
89.0k
}
303
304
89.0k
void memory_gc() {
305
89.0k
    if (config::disable_memory_gc) {
306
0
        return;
307
0
    }
308
89.0k
    if (memory_gc_sleep_time <= 0) {
309
8.90k
        auto gc_func = [](const std::string& revoke_reason) {
310
0
            doris::ProcessProfile::instance()->memory_profile()->print_log_process_usage();
311
0
            if (doris::MemoryReclamation::revoke_process_memory(revoke_reason)) {
312
                // If there is not enough memory to be gc, the process memory usage will not be printed in the next continuous gc.
313
0
                doris::ProcessProfile::instance()
314
0
                        ->memory_profile()
315
0
                        ->enable_print_log_process_usage();
316
0
            }
317
0
        };
318
319
8.90k
        if (doris::GlobalMemoryArbitrator::sys_mem_available() <
320
8.90k
            doris::MemInfo::sys_mem_available_low_water_mark()) {
321
0
            gc_func("sys available memory less than low water mark");
322
8.90k
        } else if (doris::GlobalMemoryArbitrator::process_memory_usage() >
323
8.90k
                   doris::MemInfo::mem_limit()) {
324
0
            gc_func("process memory used exceed limit");
325
0
        }
326
8.90k
        memory_gc_sleep_time = config::memory_gc_sleep_time_ms;
327
8.90k
    }
328
89.0k
    memory_gc_sleep_time -= config::memory_maintenance_sleep_time_ms;
329
89.0k
}
330
331
7
void Daemon::memory_maintenance_thread() {
332
89.0k
    while (!_stop_background_threads_latch.wait_for(
333
89.0k
            std::chrono::milliseconds(config::memory_maintenance_sleep_time_ms))) {
334
        // step 1. Refresh process memory metrics.
335
89.0k
        refresh_process_memory_metrics();
336
337
        // step 2. Refresh jemalloc/tcmalloc metrics.
338
89.0k
        refresh_common_allocator_metrics();
339
340
        // step 3. Update and print memory stat when the memory changes by 256M.
341
89.0k
        refresh_memory_state_after_memory_change();
342
343
        // step 4. Asyn Refresh cache capacity
344
        // TODO adjust cache capacity based on smoothstep (smooth gradient).
345
89.0k
        refresh_cache_capacity();
346
347
        // step 5. Cancel top memory task when process memory exceed hard limit.
348
89.0k
        memory_gc();
349
350
        // step 6. Refresh weighted memory ratio of workload groups.
351
89.0k
        doris::ExecEnv::GetInstance()->workload_group_mgr()->do_sweep();
352
89.0k
        doris::ExecEnv::GetInstance()->workload_group_mgr()->refresh_workload_group_memory_state();
353
354
        // step 7: handle paused queries(caused by memory insufficient)
355
89.0k
        doris::ExecEnv::GetInstance()->workload_group_mgr()->handle_paused_queries();
356
357
        // step 8. Flush memtable
358
89.0k
        doris::GlobalMemoryArbitrator::notify_memtable_memory_refresh();
359
        // TODO notify flush memtable
360
361
        // step 9. Reset Jemalloc dirty page decay.
362
89.0k
        je_reset_dirty_decay();
363
89.0k
    }
364
7
}
365
366
7
void Daemon::memtable_memory_refresh_thread() {
367
    // Refresh the memory statistics of the load channel tracker more frequently,
368
    // which helps to accurately control the memory of LoadChannelMgr.
369
89.0k
    do {
370
89.0k
        std::unique_lock<std::mutex> l(doris::GlobalMemoryArbitrator::memtable_memory_refresh_lock);
371
180k
        while (_stop_background_threads_latch.count() != 0 &&
372
180k
               !doris::GlobalMemoryArbitrator::memtable_memory_refresh_notify.load(
373
180k
                       std::memory_order_relaxed)) {
374
91.2k
            doris::GlobalMemoryArbitrator::memtable_memory_refresh_cv.wait_for(
375
91.2k
                    l, std::chrono::milliseconds(100));
376
91.2k
        }
377
89.0k
        if (_stop_background_threads_latch.count() == 0) {
378
3
            break;
379
3
        }
380
381
89.0k
        Defer defer {[&]() {
382
89.0k
            doris::GlobalMemoryArbitrator::memtable_memory_refresh_notify.store(
383
89.0k
                    false, std::memory_order_relaxed);
384
89.0k
        }};
385
89.0k
        doris::ExecEnv::GetInstance()->memtable_memory_limiter()->refresh_mem_tracker();
386
89.0k
    } while (true);
387
7
}
388
389
/*
390
 * this thread will calculate some metrics at a fix interval(15 sec)
391
 * 1. push bytes per second
392
 * 2. scan bytes per second
393
 * 3. max io util of all disks
394
 * 4. max network send bytes rate
395
 * 5. max network receive bytes rate
396
 */
397
7
void Daemon::calculate_metrics_thread() {
398
7
    int64_t last_ts = -1L;
399
7
    int64_t lst_query_bytes = -1;
400
401
7
    std::map<std::string, int64_t> lst_disks_io_time;
402
7
    std::map<std::string, int64_t> lst_net_send_bytes;
403
7
    std::map<std::string, int64_t> lst_net_receive_bytes;
404
405
331
    do {
406
331
        DorisMetrics::instance()->metric_registry()->trigger_all_hooks(true);
407
408
331
        if (last_ts == -1L) {
409
7
            last_ts = GetMonoTimeMicros() / 1000;
410
7
            lst_query_bytes = DorisMetrics::instance()->query_scan_bytes->value();
411
7
            if (config::enable_system_metrics) {
412
1
                DorisMetrics::instance()->system_metrics()->get_disks_io_time(&lst_disks_io_time);
413
1
                DorisMetrics::instance()->system_metrics()->get_network_traffic(
414
1
                        &lst_net_send_bytes, &lst_net_receive_bytes);
415
1
            }
416
324
        } else {
417
324
            int64_t current_ts = GetMonoTimeMicros() / 1000;
418
324
            long interval = (current_ts - last_ts) / 1000;
419
324
            last_ts = current_ts;
420
421
            // 1. query bytes per second
422
324
            int64_t current_query_bytes = DorisMetrics::instance()->query_scan_bytes->value();
423
324
            int64_t qps = (current_query_bytes - lst_query_bytes) / (interval + 1);
424
324
            DorisMetrics::instance()->query_scan_bytes_per_second->set_value(qps < 0 ? 0 : qps);
425
324
            lst_query_bytes = current_query_bytes;
426
427
324
            if (config::enable_system_metrics) {
428
                // 2. max disk io util
429
212
                DorisMetrics::instance()->system_metrics()->update_max_disk_io_util_percent(
430
212
                        lst_disks_io_time, 15);
431
432
                // update lst map
433
212
                DorisMetrics::instance()->system_metrics()->get_disks_io_time(&lst_disks_io_time);
434
435
                // 3. max network traffic
436
212
                int64_t max_send = 0;
437
212
                int64_t max_receive = 0;
438
212
                DorisMetrics::instance()->system_metrics()->get_max_net_traffic(
439
212
                        lst_net_send_bytes, lst_net_receive_bytes, 15, &max_send, &max_receive);
440
212
                DorisMetrics::instance()->system_metrics()->update_max_network_send_bytes_rate(
441
212
                        max_send);
442
212
                DorisMetrics::instance()->system_metrics()->update_max_network_receive_bytes_rate(
443
212
                        max_receive);
444
                // update lst map
445
212
                DorisMetrics::instance()->system_metrics()->get_network_traffic(
446
212
                        &lst_net_send_bytes, &lst_net_receive_bytes);
447
448
212
                DorisMetrics::instance()->system_metrics()->update_be_avail_cpu_num();
449
212
            }
450
324
            update_rowsets_and_segments_num_metrics();
451
324
        }
452
331
    } while (!_stop_background_threads_latch.wait_for(std::chrono::seconds(15)));
453
7
}
454
455
7
void Daemon::report_runtime_query_statistics_thread() {
456
1.63k
    while (!_stop_background_threads_latch.wait_for(
457
1.63k
            std::chrono::milliseconds(config::report_query_statistics_interval_ms))) {
458
1.62k
        ExecEnv::GetInstance()->runtime_query_statistics_mgr()->report_runtime_query_statistics();
459
1.62k
    }
460
7
}
461
462
7
void Daemon::je_reset_dirty_decay_thread() const {
463
7
    do {
464
7
        std::unique_lock<std::mutex> l(doris::JemallocControl::je_reset_dirty_decay_lock);
465
49.2k
        while (_stop_background_threads_latch.count() != 0 &&
466
49.2k
               !doris::JemallocControl::je_reset_dirty_decay_notify.load(
467
49.2k
                       std::memory_order_relaxed)) {
468
49.2k
            doris::JemallocControl::je_reset_dirty_decay_cv.wait_for(
469
49.2k
                    l, std::chrono::milliseconds(100));
470
49.2k
        }
471
7
        if (_stop_background_threads_latch.count() == 0) {
472
3
            break;
473
3
        }
474
475
4
        Defer defer {[&]() {
476
0
            doris::JemallocControl::je_reset_dirty_decay_notify.store(false,
477
0
                                                                      std::memory_order_relaxed);
478
0
        }};
479
#ifdef USE_JEMALLOC
480
        if (config::disable_memory_gc || !config::enable_je_purge_dirty_pages) {
481
            continue;
482
        }
483
484
        // There is a significant difference only when dirty_decay_ms is equal to 0 or not.
485
        //
486
        // 1. When dirty_decay_ms is not equal to 0, the free memory will be cached in the Jemalloc
487
        // dirty page first. even if dirty_decay_ms is equal to 1, the Jemalloc dirty page will not
488
        // be released to the system exactly after 1ms, it will be released according to the decay rule.
489
        // The Jemalloc document specifies that dirty_decay_ms is an approximate time.
490
        //
491
        // 2. It has been observed in an actual cluster that even if dirty_decay_ms is changed
492
        // from th default 5000 to 1, Jemalloc dirty page will still cache a large amount of memory, everything
493
        // seems to be the same as `dirty_decay_ms:5000`. only when dirty_decay_ms is changed to 0,
494
        // jemalloc dirty page will stop caching and free memory will be released to the system immediately.
495
        // of course, performance will be affected.
496
        //
497
        // 3. After reducing dirty_decay_ms, manually calling `decay_all_arena_dirty_pages` may release dirty pages
498
        // as soon as possible, but no relevant experimental data can be found, so it is simple and safe
499
        // to adjust dirty_decay_ms only between zero and non-zero.
500
501
        if (doris::JemallocControl::je_enable_dirty_page) {
502
            doris::JemallocControl::je_reset_all_arena_dirty_decay_ms(config::je_dirty_decay_ms);
503
        } else {
504
            doris::JemallocControl::je_reset_all_arena_dirty_decay_ms(0);
505
        }
506
#endif
507
4
    } while (true);
508
7
}
509
510
7
void Daemon::cache_adjust_capacity_thread() {
511
7
    do {
512
7
        std::unique_lock<std::mutex> l(doris::GlobalMemoryArbitrator::cache_adjust_capacity_lock);
513
49.2k
        while (_stop_background_threads_latch.count() != 0 &&
514
49.2k
               !doris::GlobalMemoryArbitrator::cache_adjust_capacity_notify.load(
515
49.2k
                       std::memory_order_relaxed)) {
516
49.2k
            doris::GlobalMemoryArbitrator::cache_adjust_capacity_cv.wait_for(
517
49.2k
                    l, std::chrono::milliseconds(100));
518
49.2k
        }
519
7
        double adjust_weighted = std::min<double>(
520
7
                GlobalMemoryArbitrator::last_periodic_refreshed_cache_capacity_adjust_weighted,
521
7
                GlobalMemoryArbitrator::last_memory_exceeded_cache_capacity_adjust_weighted);
522
7
        if (_stop_background_threads_latch.count() == 0) {
523
3
            break;
524
3
        }
525
526
4
        Defer defer {[&]() {
527
0
            doris::GlobalMemoryArbitrator::cache_adjust_capacity_notify.store(
528
0
                    false, std::memory_order_relaxed);
529
0
        }};
530
4
        if (config::disable_memory_gc) {
531
0
            continue;
532
0
        }
533
4
        if (GlobalMemoryArbitrator::last_affected_cache_capacity_adjust_weighted ==
534
4
            adjust_weighted) {
535
0
            LOG(INFO) << fmt::format(
536
0
                    "[MemoryGC] adjust cache capacity end, adjust_weighted {} has not been "
537
0
                    "modified.",
538
0
                    adjust_weighted);
539
0
            continue;
540
0
        }
541
4
        std::unique_ptr<RuntimeProfile> profile = std::make_unique<RuntimeProfile>("");
542
4
        auto freed_mem = CacheManager::instance()->for_each_cache_refresh_capacity(adjust_weighted,
543
4
                                                                                   profile.get());
544
4
        std::stringstream ss;
545
4
        profile->pretty_print(&ss);
546
4
        LOG(INFO) << fmt::format(
547
4
                "[MemoryGC] adjust cache capacity end, free memory {}, details: {}",
548
4
                PrettyPrinter::print(freed_mem, TUnit::BYTES), ss.str());
549
4
        GlobalMemoryArbitrator::last_affected_cache_capacity_adjust_weighted = adjust_weighted;
550
4
    } while (true);
551
7
}
552
553
7
void Daemon::cache_prune_stale_thread() {
554
7
    int32_t interval = config::cache_periodic_prune_stale_sweep_sec;
555
86
    while (!_stop_background_threads_latch.wait_for(std::chrono::seconds(interval))) {
556
79
        if (config::cache_periodic_prune_stale_sweep_sec <= 0) {
557
0
            LOG(WARNING) << "config of cache clean interval is: [" << interval
558
0
                         << "], it means the cache prune stale thread is disabled, will wait 3s "
559
0
                            "and check again.";
560
0
            interval = 3;
561
0
            continue;
562
0
        }
563
79
        if (config::disable_memory_gc) {
564
0
            continue;
565
0
        }
566
79
        CacheManager::instance()->for_each_cache_prune_stale();
567
79
        interval = config::cache_periodic_prune_stale_sweep_sec;
568
79
    }
569
7
}
570
571
4
void Daemon::be_proc_monitor_thread() {
572
40
    while (!_stop_background_threads_latch.wait_for(
573
40
            std::chrono::milliseconds(config::be_proc_monitor_interval_ms))) {
574
36
        LOG(INFO) << "log be thread num, " << BeProcMonitor::get_be_thread_info();
575
36
    }
576
4
}
577
578
7
void Daemon::calculate_workload_group_metrics_thread() {
579
990
    while (!_stop_background_threads_latch.wait_for(
580
990
            std::chrono::milliseconds(config::workload_group_metrics_interval_ms))) {
581
983
        ExecEnv::GetInstance()->workload_group_mgr()->refresh_workload_group_metrics();
582
983
    }
583
7
}
584
585
7
void Daemon::s3_rate_limiter_refresh_thread() {
586
    // Single trigger for dynamic rate limiter changes: picks up both mutable
587
    // s3_{get,put}_* config updates and cgroup CPU quota changes (serverless BEs can
588
    // be resized in place). refresh() is idempotent and compares against the buckets'
589
    // own parameters, so quiet iterations are cheap no-ops.
590
497
    while (!_stop_background_threads_latch.wait_for(std::chrono::seconds(10))) {
591
490
        if (config::enable_s3_rate_limiter) {
592
0
            S3RateLimiterManager::instance().refresh();
593
0
        }
594
490
    }
595
7
}
596
597
7
void Daemon::start() {
598
7
    Status st;
599
7
    st = Thread::create(
600
7
            "Daemon", "tcmalloc_gc_thread", [this]() { this->tcmalloc_gc_thread(); },
601
7
            &_threads.emplace_back());
602
7
    CHECK(st.ok()) << st;
603
7
    st = Thread::create(
604
7
            "Daemon", "memory_maintenance_thread", [this]() { this->memory_maintenance_thread(); },
605
7
            &_threads.emplace_back());
606
7
    CHECK(st.ok()) << st;
607
7
    st = Thread::create(
608
7
            "Daemon", "memtable_memory_refresh_thread",
609
7
            [this]() { this->memtable_memory_refresh_thread(); }, &_threads.emplace_back());
610
7
    CHECK(st.ok()) << st;
611
612
7
    if (config::enable_metric_calculator) {
613
7
        st = Thread::create(
614
7
                "Daemon", "calculate_metrics_thread",
615
7
                [this]() { this->calculate_metrics_thread(); }, &_threads.emplace_back());
616
7
        CHECK(st.ok()) << st;
617
7
    }
618
7
    st = Thread::create(
619
7
            "Daemon", "s3_rate_limiter_refresh_thread",
620
7
            [this]() { this->s3_rate_limiter_refresh_thread(); }, &_threads.emplace_back());
621
7
    CHECK(st.ok()) << st;
622
7
    st = Thread::create(
623
7
            "Daemon", "je_reset_dirty_decay_thread",
624
7
            [this]() { this->je_reset_dirty_decay_thread(); }, &_threads.emplace_back());
625
7
    CHECK(st.ok()) << st;
626
7
    st = Thread::create(
627
7
            "Daemon", "cache_adjust_capacity_thread",
628
7
            [this]() { this->cache_adjust_capacity_thread(); }, &_threads.emplace_back());
629
7
    CHECK(st.ok()) << st;
630
7
    st = Thread::create(
631
7
            "Daemon", "cache_prune_stale_thread", [this]() { this->cache_prune_stale_thread(); },
632
7
            &_threads.emplace_back());
633
7
    CHECK(st.ok()) << st;
634
7
    st = Thread::create(
635
7
            "Daemon", "query_runtime_statistics_thread",
636
7
            [this]() { this->report_runtime_query_statistics_thread(); }, &_threads.emplace_back());
637
7
    CHECK(st.ok()) << st;
638
639
7
    if (config::enable_be_proc_monitor) {
640
4
        st = Thread::create(
641
4
                "Daemon", "be_proc_monitor_thread", [this]() { this->be_proc_monitor_thread(); },
642
4
                &_threads.emplace_back());
643
4
    }
644
7
    CHECK(st.ok()) << st;
645
646
7
    st = Thread::create(
647
7
            "Daemon", "workload_group_metrics",
648
7
            [this]() { this->calculate_workload_group_metrics_thread(); },
649
7
            &_threads.emplace_back());
650
7
    CHECK(st.ok()) << st;
651
7
}
652
653
3
void Daemon::stop() {
654
3
    LOG(INFO) << "Doris daemon is stopping.";
655
3
    if (_stop_background_threads_latch.count() == 0) {
656
0
        LOG(INFO) << "Doris daemon stop returned since no bg threads latch.";
657
0
        return;
658
0
    }
659
3
    _stop_background_threads_latch.count_down();
660
32
    for (auto&& t : _threads) {
661
32
        if (t) {
662
32
            t->join();
663
32
        }
664
32
    }
665
    LOG(INFO) << "Doris daemon stopped after background threads are joined.";
666
3
}
667
668
} // namespace doris