Coverage Report

Created: 2026-08-05 13:32

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/runtime/exec_env_init.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
// IWYU pragma: no_include <bthread/errno.h>
19
#include <gen_cpp/HeartbeatService_types.h>
20
#include <gen_cpp/Metrics_types.h>
21
#include <simdjson.h>
22
#include <sys/resource.h>
23
24
#include <cerrno> // IWYU pragma: keep
25
#include <cstdint>
26
#include <cstdlib>
27
#include <cstring>
28
#include <limits>
29
#include <memory>
30
#include <ostream>
31
#include <string>
32
#include <vector>
33
34
#include "cloud/cloud_cluster_info.h"
35
#include "cloud/cloud_meta_mgr.h"
36
#include "cloud/cloud_ms_rpc_rate_limit_services.h"
37
#include "cloud/cloud_ms_rpc_rate_limiters.h"
38
#include "cloud/cloud_storage_engine.h"
39
#include "cloud/cloud_stream_load_executor.h"
40
#include "cloud/cloud_tablet_hotspot.h"
41
#include "cloud/cloud_warm_up_manager.h"
42
#include "cloud/config.h"
43
#include "common/cast_set.h"
44
#include "common/config.h"
45
#include "common/kerberos/kerberos_ticket_mgr.h"
46
#include "common/logging.h"
47
#include "common/metrics/doris_metrics.h"
48
#include "common/multi_version.h"
49
#include "common/status.h"
50
#include "cpp/token_bucket_rate_limiter.h"
51
#include "exec/exchange/vdata_stream_mgr.h"
52
#include "exec/pipeline/task_queue.h"
53
#include "exec/pipeline/task_scheduler.h"
54
#include "exec/scan/scanner_scheduler.h"
55
#include "exec/sink/delta_writer_v2_pool.h"
56
#include "exec/sink/load_stream_map_pool.h"
57
#include "exec/spill/spill_file_manager.h"
58
#include "exprs/function/dictionary_factory.h"
59
#include "format/orc/orc_memory_pool.h"
60
#include "format/parquet/arrow_memory_pool.h"
61
#include "io/cache/block_file_cache_downloader.h"
62
#include "io/cache/block_file_cache_factory.h"
63
#include "io/cache/fs_file_cache_storage.h"
64
#include "io/fs/file_meta_cache.h"
65
#include "io/fs/local_file_reader.h"
66
#include "load/channel/load_channel_mgr.h"
67
#include "load/channel/load_stream_mgr.h"
68
#include "load/group_commit/group_commit_mgr.h"
69
#include "load/group_commit/wal/wal_manager.h"
70
#include "load/load_path_mgr.h"
71
#include "load/memtable/memtable_memory_limiter.h"
72
#include "load/routine_load/routine_load_task_executor.h"
73
#include "load/stream_load/new_load_stream_mgr.h"
74
#include "load/stream_load/stream_load_executor.h"
75
#include "load/stream_load/stream_load_recorder_manager.h"
76
#include "runtime/broker_mgr.h"
77
#include "runtime/cache/result_cache.h"
78
#include "runtime/cdc_client_mgr.h"
79
#include "runtime/exec_env.h"
80
#include "runtime/external_scan_context_mgr.h"
81
#include "runtime/fragment_mgr.h"
82
#include "runtime/frontend_info.h"
83
#include "runtime/heartbeat_flags.h"
84
#include "runtime/index_policy/index_policy_mgr.h"
85
#include "runtime/memory/cache_manager.h"
86
#include "runtime/memory/heap_profiler.h"
87
#include "runtime/memory/mem_tracker.h"
88
#include "runtime/memory/mem_tracker_limiter.h"
89
#include "runtime/memory/thread_mem_tracker_mgr.h"
90
#include "runtime/process_profile.h"
91
#include "runtime/query_cache/query_cache.h"
92
#include "runtime/result_buffer_mgr.h"
93
#include "runtime/result_queue_mgr.h"
94
#include "runtime/runtime_query_statistics_mgr.h"
95
#include "runtime/small_file_mgr.h"
96
#include "runtime/thread_context.h"
97
#include "runtime/user_function_cache.h"
98
#include "runtime/workload_group/workload_group_manager.h"
99
#include "runtime/workload_management/workload_sched_policy_mgr.h"
100
#include "service/backend_options.h"
101
#include "service/backend_service.h"
102
#include "service/point_query_executor.h"
103
#include "storage/cache/ann_index_ivf_list_cache.h"
104
#include "storage/cache/page_cache.h"
105
#include "storage/id_manager.h"
106
#include "storage/index/ann/ann_index_result_cache/ann_index_result_cache.h"
107
#include "storage/index/inverted/inverted_index_cache.h"
108
#include "storage/olap_define.h"
109
#include "storage/options.h"
110
#include "storage/segment/condition_cache.h"
111
#include "storage/segment/encoding_info.h"
112
#include "storage/segment/segment_loader.h"
113
#include "storage/storage_engine.h"
114
#include "storage/storage_policy.h"
115
#include "storage/tablet/tablet_column_object_pool.h"
116
#include "storage/tablet/tablet_meta.h"
117
#include "storage/tablet/tablet_schema_cache.h"
118
#include "udf/python/python_server.h"
119
#include "util/bfd_parser.h"
120
#include "util/bit_util.h"
121
#include "util/brpc_client_cache.h"
122
#include "util/client_cache.h"
123
#include "util/cpu_info.h"
124
#include "util/disk_info.h"
125
#include "util/dns_cache.h"
126
#include "util/mem_info.h"
127
#include "util/parse_util.h"
128
#include "util/pretty_printer.h"
129
#include "util/threadpool.h"
130
#include "util/thrift_rpc_helper.h"
131
#include "util/timezone_utils.h"
132
133
// clang-format off
134
// this must after util/brpc_client_cache.h
135
// /doris/thirdparty/installed/include/brpc/errno.pb.h:69:3: error: expected identifier
136
//  EINTERNAL = 2001,
137
//   ^
138
//  /doris/thirdparty/installed/include/hadoop_hdfs/hdfs.h:61:19: note: expanded from macro 'EINTERNAL'
139
//  #define EINTERNAL 255
140
#include "io/fs/hdfs/hdfs_mgr.h"
141
#include "io/fs/packed_file_manager.h"
142
// clang-format on
143
144
namespace doris {
145
146
class PBackendService_Stub;
147
class PFunctionService_Stub;
148
149
// Warmup download rate limiter metrics
150
bvar::LatencyRecorder warmup_download_rate_limit_latency("warmup_download_rate_limit_latency");
151
bvar::Adder<int64_t> warmup_download_rate_limit_ns("warmup_download_rate_limit_ns");
152
bvar::Adder<int64_t> warmup_download_rate_limit_exceed_req_num(
153
        "warmup_download_rate_limit_exceed_req_num");
154
155
6
static void init_doris_metrics(const std::vector<StorePath>& store_paths) {
156
6
    bool init_system_metrics = config::enable_system_metrics;
157
6
    std::set<std::string> disk_devices;
158
6
    std::vector<std::string> network_interfaces;
159
6
    std::vector<std::string> paths;
160
9
    for (const auto& store_path : store_paths) {
161
9
        paths.emplace_back(store_path.path);
162
9
    }
163
6
    if (init_system_metrics) {
164
2
        auto st = DiskInfo::get_disk_devices(paths, &disk_devices);
165
2
        if (!st.ok()) {
166
0
            LOG(WARNING) << "get disk devices failed, status=" << st;
167
0
            return;
168
0
        }
169
2
        st = get_inet_interfaces(&network_interfaces, BackendOptions::is_bind_ipv6());
170
2
        if (!st.ok()) {
171
0
            LOG(WARNING) << "get inet interfaces failed, status=" << st;
172
0
            return;
173
0
        }
174
2
    }
175
6
    DorisMetrics::instance()->initialize(init_system_metrics, disk_devices, network_interfaces);
176
6
}
177
178
// Used to calculate the num of min thread and max thread based on the passed config
179
12
static std::pair<size_t, size_t> get_num_threads(size_t min_num, size_t max_num) {
180
12
    auto num_cores = doris::CpuInfo::num_cores();
181
12
    min_num = (min_num == 0) ? num_cores : min_num;
182
12
    max_num = (max_num == 0) ? num_cores : max_num;
183
12
    auto factor = max_num / min_num;
184
12
    min_num = std::min(num_cores * factor, min_num);
185
12
    max_num = std::min(min_num * factor, max_num);
186
12
    return {min_num, max_num};
187
12
}
188
189
16.7k
ThreadPool* ExecEnv::non_block_close_thread_pool() {
190
16.7k
    return _non_block_close_thread_pool.get();
191
16.7k
}
192
193
13
ExecEnv::ExecEnv() : _frontends(std::make_unique<std::map<TNetworkAddress, FrontendInfo>>()) {}
194
195
9
ExecEnv::~ExecEnv() {
196
9
    destroy();
197
9
}
198
199
Status ExecEnv::init(ExecEnv* env, const std::vector<StorePath>& store_paths,
200
                     const std::vector<StorePath>& spill_store_paths,
201
6
                     const std::set<std::string>& broken_paths) {
202
6
    return env->_init(store_paths, spill_store_paths, broken_paths);
203
6
}
204
205
// pick simdjson implementation based on CPU capabilities
206
6
inline void init_simdjson_parser() {
207
    // haswell: AVX2 (2013 Intel Haswell or later, all AMD Zen processors)
208
6
    const auto* haswell_implementation = simdjson::get_available_implementations()["haswell"];
209
6
    if (!haswell_implementation || !haswell_implementation->supported_by_runtime_system()) {
210
        // pick available implementation
211
0
        for (const auto* implementation : simdjson::get_available_implementations()) {
212
0
            if (implementation->supported_by_runtime_system()) {
213
0
                LOG(INFO) << "Using SimdJSON implementation : " << implementation->name() << ": "
214
0
                          << implementation->description();
215
0
                simdjson::get_active_implementation() = implementation;
216
0
                return;
217
0
            }
218
0
        }
219
0
        LOG(WARNING) << "No available SimdJSON implementation found.";
220
6
    } else {
221
6
        LOG(INFO) << "Using SimdJSON Haswell implementation";
222
6
    }
223
6
}
224
225
Status ExecEnv::_init(const std::vector<StorePath>& store_paths,
226
                      const std::vector<StorePath>& spill_store_paths,
227
6
                      const std::set<std::string>& broken_paths) {
228
    //Only init once before be destroyed
229
6
    if (ready()) {
230
0
        return Status::OK();
231
0
    }
232
6
    std::unordered_map<std::string, std::unique_ptr<SpillDataDir>> spill_store_map;
233
9
    for (const auto& spill_path : spill_store_paths) {
234
9
        spill_store_map.emplace(spill_path.path, std::make_unique<SpillDataDir>(
235
9
                                                         spill_path.path, spill_path.capacity_bytes,
236
9
                                                         spill_path.storage_medium));
237
9
    }
238
6
    init_doris_metrics(store_paths);
239
6
    _store_paths = store_paths;
240
6
    _tmp_file_dirs = std::make_unique<segment_v2::TmpFileDirs>(_store_paths);
241
6
    RETURN_IF_ERROR(_tmp_file_dirs->init());
242
6
    _user_function_cache = new UserFunctionCache();
243
6
    static_cast<void>(_user_function_cache->init(doris::config::user_function_dir));
244
6
    _external_scan_context_mgr = new ExternalScanContextMgr(this);
245
6
    set_stream_mgr(new doris::VDataStreamMgr());
246
6
    _result_mgr = new ResultBufferMgr();
247
6
    _result_queue_mgr = new ResultQueueMgr();
248
6
    _backend_client_cache = new BackendServiceClientCache(config::max_client_cache_size_per_host);
249
6
    _frontend_client_cache = new FrontendServiceClientCache(config::max_client_cache_size_per_host);
250
6
    _broker_client_cache = new BrokerServiceClientCache(config::max_client_cache_size_per_host);
251
252
6
    TimezoneUtils::load_timezones_to_cache();
253
254
6
    static_cast<void>(ThreadPoolBuilder("SendBatchThreadPool")
255
6
                              .set_min_threads(config::send_batch_thread_pool_thread_num)
256
6
                              .set_max_threads(config::send_batch_thread_pool_thread_num)
257
6
                              .set_max_queue_size(config::send_batch_thread_pool_queue_size)
258
6
                              .build(&_send_batch_thread_pool));
259
260
6
    static_cast<void>(ThreadPoolBuilder("UDFCloseWorkers")
261
6
                              .set_min_threads(4)
262
6
                              .set_max_threads(std::min(32, CpuInfo::num_cores()))
263
6
                              .build(&_udf_close_workers_thread_pool));
264
265
6
    auto [buffered_reader_min_threads, buffered_reader_max_threads] =
266
6
            get_num_threads(config::num_buffered_reader_prefetch_thread_pool_min_thread,
267
6
                            config::num_buffered_reader_prefetch_thread_pool_max_thread);
268
6
    static_cast<void>(ThreadPoolBuilder("BufferedReaderPrefetchThreadPool")
269
6
                              .set_min_threads(cast_set<int>(buffered_reader_min_threads))
270
6
                              .set_max_threads(cast_set<int>(buffered_reader_max_threads))
271
6
                              .build(&_buffered_reader_prefetch_thread_pool));
272
273
6
    static_cast<void>(ThreadPoolBuilder("SegmentPrefetchThreadPool")
274
6
                              .set_min_threads(cast_set<int>(
275
6
                                      config::segment_prefetch_thread_pool_thread_num_min))
276
6
                              .set_max_threads(cast_set<int>(
277
6
                                      config::segment_prefetch_thread_pool_thread_num_max))
278
6
                              .build(&_segment_prefetch_thread_pool));
279
280
6
    static_cast<void>(ThreadPoolBuilder("SendTableStatsThreadPool")
281
6
                              .set_min_threads(8)
282
6
                              .set_max_threads(32)
283
6
                              .build(&_send_table_stats_thread_pool));
284
285
6
    auto [s3_file_upload_min_threads, s3_file_upload_max_threads] =
286
6
            get_num_threads(config::num_s3_file_upload_thread_pool_min_thread,
287
6
                            config::num_s3_file_upload_thread_pool_max_thread);
288
6
    static_cast<void>(ThreadPoolBuilder("S3FileUploadThreadPool")
289
6
                              .set_min_threads(cast_set<int>(s3_file_upload_min_threads))
290
6
                              .set_max_threads(cast_set<int>(s3_file_upload_max_threads))
291
6
                              .build(&_s3_file_upload_thread_pool));
292
293
    // min num equal to fragment pool's min num
294
    // max num is useless because it will start as many as requested in the past
295
    // queue size is useless because the max thread num is very large
296
6
    static_cast<void>(ThreadPoolBuilder("LazyReleaseMemoryThreadPool")
297
6
                              .set_min_threads(1)
298
6
                              .set_max_threads(1)
299
6
                              .set_max_queue_size(1000000)
300
6
                              .build(&_lazy_release_obj_pool));
301
6
    static_cast<void>(ThreadPoolBuilder("NonBlockCloseThreadPool")
302
6
                              .set_min_threads(cast_set<int>(config::min_nonblock_close_thread_num))
303
6
                              .set_max_threads(cast_set<int>(config::max_nonblock_close_thread_num))
304
6
                              .build(&_non_block_close_thread_pool));
305
6
    static_cast<void>(ThreadPoolBuilder("S3FileSystemThreadPool")
306
6
                              .set_min_threads(config::min_s3_file_system_thread_num)
307
6
                              .set_max_threads(config::max_s3_file_system_thread_num)
308
6
                              .build(&_s3_file_system_thread_pool));
309
6
    static_cast<void>(ThreadPoolBuilder("PeerRaceS3ThreadPool")
310
6
                              .set_min_threads(config::min_peer_race_s3_thread_num)
311
6
                              .set_max_threads(config::max_peer_race_s3_thread_num)
312
6
                              .build(&_peer_race_s3_thread_pool));
313
6
    RETURN_IF_ERROR(init_mem_env());
314
315
    // NOTE: runtime query statistics mgr could be visited by query and daemon thread
316
    // so it should be created before all query begin and deleted after all query and daemon thread stoppped
317
6
    _runtime_query_statistics_mgr = new RuntimeQueryStatisticsMgr();
318
6
    CgroupCpuCtl::init_doris_cgroup_path();
319
6
    _file_cache_open_fd_cache = std::make_unique<io::FDCache>();
320
6
    _file_cache_factory = new io::FileCacheFactory();
321
6
    std::vector<doris::CachePath> cache_paths;
322
6
    init_file_cache_factory(cache_paths);
323
6
    doris::io::BeConfDataDirReader::init_be_conf_data_dir(store_paths, spill_store_paths,
324
6
                                                          cache_paths);
325
6
    _init_runtime_filter_timer_queue();
326
327
6
    _workload_group_manager = new WorkloadGroupMgr();
328
329
6
    _fragment_mgr = new FragmentMgr(this);
330
6
    _result_cache = new ResultCache(config::query_cache_max_size_mb,
331
6
                                    config::query_cache_elasticity_size_mb);
332
6
    if (config::is_cloud_mode()) {
333
1
        _cluster_info = new CloudClusterInfo();
334
5
    } else {
335
5
        _cluster_info = new ClusterInfo();
336
5
    }
337
338
6
    _load_path_mgr = new LoadPathMgr(this);
339
6
    _bfd_parser = BfdParser::create();
340
6
    _broker_mgr = new BrokerMgr(this);
341
6
    _load_channel_mgr = new LoadChannelMgr();
342
6
    auto num_flush_threads = std::min(
343
6
            _store_paths.size() * config::flush_thread_num_per_store,
344
6
            static_cast<size_t>(CpuInfo::num_cores()) * config::max_flush_thread_num_per_cpu);
345
6
    _load_stream_mgr = std::make_unique<LoadStreamMgr>(num_flush_threads);
346
6
    _new_load_stream_mgr = NewLoadStreamMgr::create_unique();
347
6
    _internal_client_cache = new BrpcClientCache<PBackendService_Stub>();
348
6
    _streaming_client_cache =
349
6
            new BrpcClientCache<PBackendService_Stub>("baidu_std", "single", "streaming");
350
6
    _function_client_cache =
351
6
            new BrpcClientCache<PFunctionService_Stub>(config::function_service_protocol);
352
6
    if (config::is_cloud_mode()) {
353
1
        _stream_load_executor = CloudStreamLoadExecutor::create_unique(this);
354
5
    } else {
355
5
        _stream_load_executor = StreamLoadExecutor::create_unique(this);
356
5
    }
357
6
    _routine_load_task_executor = new RoutineLoadTaskExecutor(this);
358
6
    RETURN_IF_ERROR(_routine_load_task_executor->init(MemInfo::mem_limit()));
359
6
    _small_file_mgr = new SmallFileMgr(this, config::small_file_dir);
360
6
    _group_commit_mgr = new GroupCommitMgr(this);
361
6
    _cdc_client_mgr = new CdcClientMgr();
362
6
    _memtable_memory_limiter = std::make_unique<MemTableMemoryLimiter>();
363
6
    _load_stream_map_pool = std::make_unique<LoadStreamMapPool>();
364
6
    _delta_writer_v2_pool = std::make_unique<DeltaWriterV2Pool>();
365
6
    _wal_manager = WalManager::create_unique(this, config::group_commit_wal_path);
366
6
    _dns_cache = new DNSCache();
367
6
    _write_cooldown_meta_executors = std::make_unique<WriteCooldownMetaExecutors>();
368
369
6
    _spill_file_mgr = new SpillFileManager(std::move(spill_store_map));
370
6
    _kerberos_ticket_mgr = new kerberos::KerberosTicketMgr(config::kerberos_ccache_path);
371
6
    _hdfs_mgr = new io::HdfsMgr();
372
6
    _backend_client_cache->init_metrics("backend");
373
6
    _frontend_client_cache->init_metrics("frontend");
374
6
    _broker_client_cache->init_metrics("broker");
375
6
    static_cast<void>(_result_mgr->init());
376
6
    Status status = _load_path_mgr->init();
377
6
    if (!status.ok()) {
378
0
        LOG(ERROR) << "Load path mgr init failed. " << status;
379
0
        return status;
380
0
    }
381
6
    _broker_mgr->init();
382
6
    static_cast<void>(_small_file_mgr->init());
383
6
    if (!status.ok()) {
384
0
        LOG(ERROR) << "Scanner scheduler init failed. " << status;
385
0
        return status;
386
0
    }
387
388
6
    RETURN_IF_ERROR(_memtable_memory_limiter->init(MemInfo::mem_limit()));
389
6
    RETURN_IF_ERROR(_load_channel_mgr->init(MemInfo::mem_limit()));
390
6
    RETURN_IF_ERROR(_wal_manager->init());
391
6
    _heartbeat_flags = new HeartbeatFlags();
392
393
6
    _tablet_schema_cache =
394
6
            TabletSchemaCache::create_global_schema_cache(config::tablet_schema_cache_capacity);
395
396
6
    _tablet_column_object_pool = TabletColumnObjectPool::create_global_column_cache(
397
6
            config::tablet_schema_cache_capacity);
398
399
    // Storage engine
400
6
    doris::EngineOptions options;
401
6
    options.store_paths = store_paths;
402
6
    options.broken_paths = broken_paths;
403
6
    options.backend_uid = doris::UniqueId::gen_uid();
404
    // Check if the startup mode has been modified
405
6
    RETURN_IF_ERROR(_check_deploy_mode());
406
6
    if (config::is_cloud_mode()) {
407
1
        std::cout << "start BE in cloud mode, cloud_unique_id: " << config::cloud_unique_id
408
1
                  << ", meta_service_endpoint: " << config::meta_service_endpoint << std::endl;
409
1
        _storage_engine = std::make_unique<CloudStorageEngine>(options);
410
5
    } else {
411
5
        std::cout << "start BE in local mode" << std::endl;
412
5
        _storage_engine = std::make_unique<StorageEngine>(options);
413
5
    }
414
6
    auto st = _storage_engine->open();
415
6
    if (!st.ok()) {
416
0
        LOG(ERROR) << "Fail to open StorageEngine, res=" << st;
417
0
        return st;
418
0
    }
419
6
    _storage_engine->set_heartbeat_flags(this->heartbeat_flags());
420
6
    if (st = _storage_engine->start_bg_threads(nullptr); !st.ok()) {
421
0
        LOG(ERROR) << "Failed to starge bg threads of storage engine, res=" << st;
422
0
        return st;
423
0
    }
424
425
    // should start after storage_engine->open()
426
6
    _stream_load_recorder_manager = new StreamLoadRecorderManager();
427
6
    _stream_load_recorder_manager->start();
428
429
    // create internal workload group should be after storage_engin->open()
430
6
    RETURN_IF_ERROR(_create_internal_workload_group());
431
6
    _workload_sched_mgr = new WorkloadSchedPolicyMgr();
432
6
    _workload_sched_mgr->start(this);
433
434
    // Initialize packed file manager
435
6
    _packed_file_manager = io::PackedFileManager::instance();
436
6
    if (config::is_cloud_mode()) {
437
1
        RETURN_IF_ERROR(_packed_file_manager->init());
438
1
        _packed_file_manager->start_background_manager();
439
440
        // Start cluster info background worker for compaction read-write separation
441
1
        static_cast<CloudClusterInfo*>(_cluster_info)->start_bg_worker();
442
443
        // Initialize MS RPC rate limiters and table-level backpressure handling.
444
1
        _ms_rpc_rate_limit_services = std::make_unique<MSRpcRateLimitServices>();
445
1
        static_cast<CloudStorageEngine*>(_storage_engine.get())
446
1
                ->meta_mgr()
447
1
                .set_host_level_ms_rpc_rate_limiters(
448
1
                        _ms_rpc_rate_limit_services->host_level_ms_rpc_rate_limiters());
449
1
        static_cast<CloudStorageEngine*>(_storage_engine.get())
450
1
                ->meta_mgr()
451
1
                .set_ms_backpressure_handler(
452
1
                        _ms_rpc_rate_limit_services->ms_backpressure_handler());
453
1
    }
454
455
6
    _index_policy_mgr = new IndexPolicyMgr();
456
457
    // Initialize warmup download rate limiter for cloud mode
458
    // Always create the rate limiter in cloud mode to support dynamic rate limit changes
459
6
    if (config::is_cloud_mode()) {
460
1
        int64_t rate_limit = config::file_cache_warmup_download_rate_limit_bytes_per_second;
461
        // When rate_limit <= 0, pass 0 to disable rate limiting
462
1
        int64_t rate = rate_limit > 0 ? rate_limit : 0;
463
        // max_burst is the same as rate (1 second burst)
464
        // limit is 0 which means no total limit
465
        // When rate is 0, S3RateLimiter will not throttle (no rate limiting)
466
1
        _warmup_download_rate_limiter = new S3RateLimiterHolder(rate, rate, 0, [&](int64_t ns) {
467
0
            if (ns > 0) {
468
0
                warmup_download_rate_limit_latency << ns / 1000;
469
0
                warmup_download_rate_limit_ns << ns;
470
0
                warmup_download_rate_limit_exceed_req_num << 1;
471
0
            }
472
0
        });
473
1
    }
474
475
6
    RETURN_IF_ERROR(_spill_file_mgr->init());
476
6
    RETURN_IF_ERROR(_runtime_query_statistics_mgr->start_report_thread());
477
6
    _dict_factory = new doris::DictionaryFactory();
478
6
    _s_ready = true;
479
480
6
    init_simdjson_parser();
481
482
    // Make aws-sdk-cpp InitAPI and ShutdownAPI called in the same thread
483
6
    S3ClientFactory::instance();
484
6
    return Status::OK();
485
6
}
486
487
// when user not sepcify a workload group in FE, then query could
488
// use dummy workload group.
489
6
Status ExecEnv::_create_internal_workload_group() {
490
6
    LOG(INFO) << "begin create internal workload group.";
491
492
6
    RETURN_IF_ERROR(_workload_group_manager->create_internal_wg());
493
6
    return Status::OK();
494
6
}
495
496
8
void ExecEnv::_init_runtime_filter_timer_queue() {
497
8
    _runtime_filter_timer_queue = new doris::RuntimeFilterTimerQueue();
498
8
    _runtime_filter_timer_queue->run();
499
8
}
500
501
6
void ExecEnv::init_file_cache_factory(std::vector<doris::CachePath>& cache_paths) {
502
    // Load file cache before starting up daemon threads to make sure StorageEngine is read.
503
6
    if (!config::enable_file_cache) {
504
3
        if (config::is_cloud_mode()) {
505
0
            LOG(FATAL) << "Cloud mode requires to enable file cache, plz set "
506
0
                          "config::enable_file_cache "
507
0
                          "= true";
508
0
            exit(-1);
509
0
        }
510
3
        return;
511
3
    }
512
3
    if (config::file_cache_each_block_size > config::s3_write_buffer_size ||
513
3
        config::s3_write_buffer_size % config::file_cache_each_block_size != 0) {
514
0
        LOG_FATAL(
515
0
                "The config file_cache_each_block_size {} must less than or equal to config "
516
0
                "s3_write_buffer_size {} and config::s3_write_buffer_size % "
517
0
                "config::file_cache_each_block_size must be zero",
518
0
                config::file_cache_each_block_size, config::s3_write_buffer_size);
519
0
        exit(-1);
520
0
    }
521
3
    Status rest = doris::parse_conf_cache_paths(doris::config::file_cache_path, cache_paths);
522
3
    if (!rest) {
523
0
        throw Exception(
524
0
                Status::FatalError("parse config file cache path failed, path={}, reason={}",
525
0
                                   doris::config::file_cache_path, rest.msg()));
526
0
    }
527
528
3
    auto cache_status = doris::io::FileCacheFactory::instance()->create_file_caches(
529
3
            cache_paths, [](const std::string&, const Status& status) {
530
0
                if (!doris::config::ignore_broken_disk) {
531
0
                    return false;
532
0
                }
533
0
                LOG(WARNING) << "failed to init file cache, err: " << status;
534
0
                return true;
535
0
            });
536
3
    if (!cache_status.ok()) {
537
0
        throw Exception(Status::FatalError("failed to init file cache, err: {}", cache_status));
538
0
    }
539
3
}
540
541
6
Status ExecEnv::init_mem_env() {
542
6
    bool is_percent = false;
543
6
    std::stringstream ss;
544
    // 1. init mem tracker
545
6
    _process_profile = ProcessProfile::create_global_instance();
546
6
    _heap_profiler = HeapProfiler::create_global_instance();
547
6
    init_mem_tracker();
548
6
    thread_context()->thread_mem_tracker_mgr->init();
549
550
6
    if (!BitUtil::IsPowerOf2(config::min_buffer_size)) {
551
0
        ss << "Config min_buffer_size must be a power-of-two: " << config::min_buffer_size;
552
0
        return Status::InternalError(ss.str());
553
0
    }
554
555
6
    _id_manager = new IdManager();
556
6
    _cache_manager = CacheManager::create_global_instance();
557
558
6
    int64_t storage_cache_limit =
559
6
            ParseUtil::parse_mem_spec(config::storage_page_cache_limit, MemInfo::mem_limit(),
560
6
                                      MemInfo::physical_mem(), &is_percent);
561
6
    while (!is_percent && storage_cache_limit > MemInfo::mem_limit() / 2) {
562
0
        storage_cache_limit = storage_cache_limit / 2;
563
0
    }
564
6
    int32_t index_percentage = config::index_page_cache_percentage;
565
6
    int32_t num_shards = config::storage_page_cache_shard_size;
566
6
    if ((num_shards & (num_shards - 1)) != 0) {
567
0
        int old_num_shards = num_shards;
568
0
        num_shards = cast_set<int>(BitUtil::RoundUpToPowerOfTwo(num_shards));
569
0
        LOG(WARNING) << "num_shards should be power of two, but got " << old_num_shards
570
0
                     << ". Rounded up to " << num_shards
571
0
                     << ". Please modify the 'storage_page_cache_shard_size' parameter in your "
572
0
                        "conf file to be a power of two for better performance.";
573
0
    }
574
6
    if (storage_cache_limit < num_shards * 2) {
575
0
        LOG(WARNING) << "storage_cache_limit(" << storage_cache_limit << ") less than num_shards("
576
0
                     << num_shards
577
0
                     << ") * 2, cache capacity will be 0, continuing to use "
578
0
                        "cache will only have negative effects, will be disabled.";
579
0
    }
580
6
    int64_t pk_storage_page_cache_limit =
581
6
            ParseUtil::parse_mem_spec(config::pk_storage_page_cache_limit, MemInfo::mem_limit(),
582
6
                                      MemInfo::physical_mem(), &is_percent);
583
6
    while (!is_percent && pk_storage_page_cache_limit > MemInfo::mem_limit() / 2) {
584
0
        pk_storage_page_cache_limit = storage_cache_limit / 2;
585
0
    }
586
6
    _storage_page_cache = StoragePageCache::create_global_cache(
587
6
            storage_cache_limit, index_percentage, pk_storage_page_cache_limit, num_shards);
588
6
    LOG(INFO) << "Storage page cache memory limit: "
589
6
              << PrettyPrinter::print(storage_cache_limit, TUnit::BYTES)
590
6
              << ", origin config value: " << config::storage_page_cache_limit;
591
592
    // Init ANN index IVF list cache (dedicated cache for IVF on disk)
593
6
    {
594
6
        int64_t ann_cache_limit = ParseUtil::parse_mem_spec(config::ann_index_ivf_list_cache_limit,
595
6
                                                            MemInfo::mem_limit(),
596
6
                                                            MemInfo::physical_mem(), &is_percent);
597
6
        while (!is_percent && ann_cache_limit > MemInfo::mem_limit() / 2) {
598
0
            ann_cache_limit = ann_cache_limit / 2;
599
0
        }
600
6
        _ann_index_ivf_list_cache = AnnIndexIVFListCache::create_global_cache(ann_cache_limit);
601
6
        LOG(INFO) << "ANN index IVF list cache memory limit: "
602
6
                  << PrettyPrinter::print(ann_cache_limit, TUnit::BYTES)
603
6
                  << ", origin config value: " << config::ann_index_ivf_list_cache_limit;
604
6
    }
605
606
    // Init row cache
607
6
    int64_t row_cache_mem_limit =
608
6
            ParseUtil::parse_mem_spec(config::row_cache_mem_limit, MemInfo::mem_limit(),
609
6
                                      MemInfo::physical_mem(), &is_percent);
610
6
    while (!is_percent && row_cache_mem_limit > MemInfo::mem_limit() / 2) {
611
        // Reason same as buffer_pool_limit
612
0
        row_cache_mem_limit = row_cache_mem_limit / 2;
613
0
    }
614
6
    _row_cache = RowCache::create_global_cache(row_cache_mem_limit);
615
6
    LOG(INFO) << "Row cache memory limit: "
616
6
              << PrettyPrinter::print(row_cache_mem_limit, TUnit::BYTES)
617
6
              << ", origin config value: " << config::row_cache_mem_limit;
618
619
6
    uint64_t fd_number = config::min_file_descriptor_number;
620
6
    struct rlimit l;
621
6
    int ret = getrlimit(RLIMIT_NOFILE, &l);
622
6
    if (ret != 0) {
623
0
        LOG(WARNING) << "call getrlimit() failed. errno=" << strerror(errno)
624
0
                     << ", use default configuration instead.";
625
6
    } else {
626
6
        fd_number = static_cast<uint64_t>(l.rlim_cur);
627
6
    }
628
#ifdef __APPLE__
629
    // On macOS, rlim_cur can be RLIM_INFINITY (INT64_MAX), which causes
630
    // fd_number / 100 * percentage to overflow and crash cast_set<uint32_t>.
631
    // Linux kernels cap this via fs.nr_open (default 1M), so only macOS needs this.
632
    {
633
        constexpr uint64_t max_fd = UINT32_MAX >> 2;
634
        if (fd_number > max_fd) {
635
            fd_number = max_fd;
636
        }
637
    }
638
#endif
639
640
6
    int64_t segment_cache_capacity = 0;
641
6
    if (config::is_cloud_mode()) {
642
        // when in cloud mode, segment cache hold no system FD
643
        // thus the FD num limit makes no sense
644
        // cloud mode use FDCache to control FD
645
1
        segment_cache_capacity = UINT32_MAX;
646
5
    } else {
647
        // SegmentLoader caches segments in rowset granularity. So the size of
648
        // opened files will greater than segment_cache_capacity.
649
5
        segment_cache_capacity = config::segment_cache_capacity;
650
5
        int64_t segment_cache_fd_limit = fd_number / 100 * config::segment_cache_fd_percentage;
651
5
        if (segment_cache_capacity < 0 || segment_cache_capacity > segment_cache_fd_limit) {
652
5
            segment_cache_capacity = segment_cache_fd_limit;
653
5
        }
654
5
    }
655
656
6
    int64_t segment_cache_mem_limit =
657
6
            MemInfo::mem_limit() / 100 * config::segment_cache_memory_percentage;
658
659
6
    _segment_loader = new SegmentLoader(segment_cache_mem_limit, segment_cache_capacity);
660
6
    LOG(INFO) << "segment_cache_capacity <= fd_number * 1 / 5, fd_number: " << fd_number
661
6
              << " segment_cache_capacity: " << segment_cache_capacity
662
6
              << " min_segment_cache_mem_limit " << segment_cache_mem_limit;
663
664
6
    size_t block_file_cache_fd_cache_size =
665
6
            std::min((uint64_t)config::file_cache_max_file_reader_cache_size, fd_number / 3);
666
6
    LOG(INFO) << "max file reader cache size is: " << block_file_cache_fd_cache_size
667
6
              << ", resource hard limit is: " << fd_number
668
6
              << ", config file_cache_max_file_reader_cache_size is: "
669
6
              << config::file_cache_max_file_reader_cache_size;
670
6
    config::file_cache_max_file_reader_cache_size = block_file_cache_fd_cache_size;
671
672
6
    _file_meta_cache = new FileMetaCache(config::max_external_file_meta_cache_num);
673
674
6
    _lookup_connection_cache =
675
6
            LookupConnectionCache::create_global_instance(config::lookup_connection_cache_capacity);
676
677
    // use memory limit
678
6
    int64_t inverted_index_cache_limit =
679
6
            ParseUtil::parse_mem_spec(config::inverted_index_searcher_cache_limit,
680
6
                                      MemInfo::mem_limit(), MemInfo::physical_mem(), &is_percent);
681
6
    while (!is_percent && inverted_index_cache_limit > MemInfo::mem_limit() / 2) {
682
        // Reason same as buffer_pool_limit
683
0
        inverted_index_cache_limit = inverted_index_cache_limit / 2;
684
0
    }
685
6
    _inverted_index_searcher_cache =
686
6
            InvertedIndexSearcherCache::create_global_instance(inverted_index_cache_limit, 256);
687
6
    LOG(INFO) << "Inverted index searcher cache memory limit: "
688
6
              << PrettyPrinter::print(inverted_index_cache_limit, TUnit::BYTES)
689
6
              << ", origin config value: " << config::inverted_index_searcher_cache_limit;
690
691
    // use memory limit
692
6
    int64_t inverted_index_query_cache_limit =
693
6
            ParseUtil::parse_mem_spec(config::inverted_index_query_cache_limit,
694
6
                                      MemInfo::mem_limit(), MemInfo::physical_mem(), &is_percent);
695
6
    while (!is_percent && inverted_index_query_cache_limit > MemInfo::mem_limit() / 2) {
696
        // Reason same as buffer_pool_limit
697
0
        inverted_index_query_cache_limit = inverted_index_query_cache_limit / 2;
698
0
    }
699
6
    _inverted_index_query_cache = InvertedIndexQueryCache::create_global_cache(
700
6
            inverted_index_query_cache_limit, config::inverted_index_query_cache_shards);
701
6
    LOG(INFO) << "Inverted index query match cache memory limit: "
702
6
              << PrettyPrinter::print(inverted_index_query_cache_limit, TUnit::BYTES)
703
6
              << ", origin config value: " << config::inverted_index_query_cache_limit;
704
705
    // ANN index topn result cache
706
6
    int64_t ann_topn_cache_limit =
707
6
            ParseUtil::parse_mem_spec(config::ann_index_result_cache_limit, MemInfo::mem_limit(),
708
6
                                      MemInfo::physical_mem(), &is_percent);
709
6
    _ann_index_result_cache =
710
6
            segment_v2::AnnIndexResultCache::create_global_cache(ann_topn_cache_limit);
711
6
    LOG(INFO) << "ANN index topn result cache memory limit: "
712
6
              << PrettyPrinter::print(ann_topn_cache_limit, TUnit::BYTES)
713
6
              << ", origin config value: " << config::ann_index_result_cache_limit;
714
715
    // use memory limit
716
6
    int64_t condition_cache_limit = config::condition_cache_limit * 1024L * 1024L;
717
6
    _condition_cache = ConditionCache::create_global_cache(condition_cache_limit);
718
6
    LOG(INFO) << "Condition cache memory limit: "
719
6
              << PrettyPrinter::print(condition_cache_limit, TUnit::BYTES)
720
6
              << ", origin config value: " << config::condition_cache_limit;
721
722
    // Initialize encoding info resolver
723
6
    _encoding_info_resolver = new segment_v2::EncodingInfoResolver();
724
725
    // init orc memory pool
726
6
    _orc_memory_pool = new doris::ORCMemoryPool();
727
6
    _arrow_memory_pool = new doris::ArrowMemoryPool();
728
729
6
    _query_cache = QueryCache::create_global_cache(config::query_cache_size * 1024L * 1024L);
730
6
    LOG(INFO) << "query cache memory limit: " << config::query_cache_size << "MB";
731
732
    // The default delete bitmap cache is set to 100MB,
733
    // which can be insufficient and cause performance issues when the amount of user data is large.
734
    // To mitigate the problem of an inadequate cache,
735
    // we will take the larger of 0.5% of the total memory and 100MB as the delete bitmap cache size.
736
6
    int64_t delete_bitmap_agg_cache_cache_limit =
737
6
            ParseUtil::parse_mem_spec(config::delete_bitmap_dynamic_agg_cache_limit,
738
6
                                      MemInfo::mem_limit(), MemInfo::physical_mem(), &is_percent);
739
6
    _delete_bitmap_agg_cache = DeleteBitmapAggCache::create_instance(std::max(
740
6
            delete_bitmap_agg_cache_cache_limit, config::delete_bitmap_agg_cache_capacity));
741
742
6
    return Status::OK();
743
6
}
744
745
7
void ExecEnv::init_mem_tracker() {
746
7
    mem_tracker_limiter_pool.resize(MEM_TRACKER_GROUP_NUM,
747
7
                                    TrackerLimiterGroup()); // before all mem tracker init.
748
7
    _s_tracking_memory = true;
749
7
    _orphan_mem_tracker =
750
7
            MemTrackerLimiter::create_shared(MemTrackerLimiter::Type::GLOBAL, "Orphan");
751
7
    _brpc_iobuf_block_memory_tracker =
752
7
            MemTrackerLimiter::create_shared(MemTrackerLimiter::Type::GLOBAL, "IOBufBlockMemory");
753
7
    _segcompaction_mem_tracker =
754
7
            MemTrackerLimiter::create_shared(MemTrackerLimiter::Type::COMPACTION, "SegCompaction");
755
7
    _tablets_no_cache_mem_tracker = MemTrackerLimiter::create_shared(
756
7
            MemTrackerLimiter::Type::METADATA, "Tablets(not in TabletSchemaCache)");
757
7
    _segments_no_cache_mem_tracker = MemTrackerLimiter::create_shared(
758
7
            MemTrackerLimiter::Type::METADATA, "Segments(not in SegmentCache)");
759
7
    _rowsets_no_cache_mem_tracker =
760
7
            MemTrackerLimiter::create_shared(MemTrackerLimiter::Type::METADATA, "Rowsets");
761
7
    _point_query_executor_mem_tracker =
762
7
            MemTrackerLimiter::create_shared(MemTrackerLimiter::Type::GLOBAL, "PointQueryExecutor");
763
7
    _query_cache_mem_tracker =
764
7
            MemTrackerLimiter::create_shared(MemTrackerLimiter::Type::CACHE, "QueryCache");
765
7
    _block_compression_mem_tracker =
766
7
            MemTrackerLimiter::create_shared(MemTrackerLimiter::Type::GLOBAL, "BlockCompression");
767
7
    _rowid_storage_reader_tracker =
768
7
            MemTrackerLimiter::create_shared(MemTrackerLimiter::Type::GLOBAL, "RowIdStorageReader");
769
7
    _subcolumns_tree_tracker =
770
7
            MemTrackerLimiter::create_shared(MemTrackerLimiter::Type::GLOBAL, "SubcolumnsTree");
771
7
    _s3_file_buffer_tracker =
772
7
            MemTrackerLimiter::create_shared(MemTrackerLimiter::Type::GLOBAL, "S3FileBuffer");
773
7
    _stream_load_pipe_tracker =
774
7
            MemTrackerLimiter::create_shared(MemTrackerLimiter::Type::LOAD, "StreamLoadPipe");
775
7
    _parquet_meta_tracker =
776
7
            MemTrackerLimiter::create_shared(MemTrackerLimiter::Type::METADATA, "ParquetMeta");
777
7
}
778
779
6
Status ExecEnv::_check_deploy_mode() {
780
9
    for (auto _path : _store_paths) {
781
9
        auto deploy_mode_path = fmt::format("{}/{}", _path.path, DEPLOY_MODE_PREFIX);
782
9
        std::string expected_mode = doris::config::is_cloud_mode() ? "cloud" : "local";
783
9
        bool exists = false;
784
9
        RETURN_IF_ERROR(io::global_local_filesystem()->exists(deploy_mode_path, &exists));
785
9
        if (exists) {
786
            // check if is ok
787
6
            io::FileReaderSPtr reader;
788
6
            RETURN_IF_ERROR(io::global_local_filesystem()->open_file(deploy_mode_path, &reader));
789
6
            size_t fsize = reader->size();
790
6
            if (fsize > 0) {
791
6
                std::string actual_mode;
792
6
                actual_mode.resize(fsize, '\0');
793
6
                size_t bytes_read = 0;
794
6
                RETURN_IF_ERROR(reader->read_at(0, {actual_mode.data(), fsize}, &bytes_read));
795
6
                DCHECK_EQ(fsize, bytes_read);
796
6
                if (expected_mode != actual_mode) {
797
0
                    return Status::InternalError(
798
0
                            "You can't switch deploy mode from {} to {}, "
799
0
                            "maybe you need to check be.conf\n",
800
0
                            actual_mode.c_str(), expected_mode.c_str());
801
0
                }
802
6
                LOG(INFO) << "The current deployment mode is " << expected_mode << ".";
803
6
            }
804
6
        } else {
805
3
            io::FileWriterPtr file_writer;
806
3
            RETURN_IF_ERROR(
807
3
                    io::global_local_filesystem()->create_file(deploy_mode_path, &file_writer));
808
3
            RETURN_IF_ERROR(file_writer->append(expected_mode));
809
3
            RETURN_IF_ERROR(file_writer->close());
810
3
            LOG(INFO) << "The file deploy_mode doesn't exist, create it.";
811
3
            auto cluster_id_path = fmt::format("{}/{}", _path.path, CLUSTER_ID_PREFIX);
812
3
            RETURN_IF_ERROR(io::global_local_filesystem()->exists(cluster_id_path, &exists));
813
3
            if (exists) {
814
0
                LOG(WARNING) << "This may be an upgrade from old version,"
815
0
                             << "or the deploy_mode file has been manually deleted";
816
0
            }
817
3
        }
818
9
    }
819
6
    return Status::OK();
820
6
}
821
822
#ifdef BE_TEST
823
void ExecEnv::set_new_load_stream_mgr(std::unique_ptr<NewLoadStreamMgr>&& new_load_stream_mgr) {
824
    this->_new_load_stream_mgr = std::move(new_load_stream_mgr);
825
}
826
827
void ExecEnv::clear_new_load_stream_mgr() {
828
    this->_new_load_stream_mgr.reset();
829
}
830
831
void ExecEnv::set_stream_load_executor(std::unique_ptr<StreamLoadExecutor>&& stream_load_executor) {
832
    this->_stream_load_executor = std::move(stream_load_executor);
833
}
834
835
void ExecEnv::clear_stream_load_executor() {
836
    this->_stream_load_executor.reset();
837
}
838
839
void ExecEnv::set_wal_mgr(std::unique_ptr<WalManager>&& wm) {
840
    this->_wal_manager = std::move(wm);
841
}
842
void ExecEnv::clear_wal_mgr() {
843
    this->_wal_manager.reset();
844
}
845
#endif
846
// TODO(zhiqiang): Need refactor all thread pool. Each thread pool must have a Stop method.
847
// We need to stop all threads before releasing resource.
848
16
void ExecEnv::destroy() {
849
    //Only destroy once after init
850
16
    if (!ready()) {
851
10
        return;
852
10
    }
853
    // Memory barrier to prevent other threads from accessing destructed resources
854
6
    _s_ready = false;
855
856
6
    SAFE_STOP(_wal_manager);
857
6
    _wal_manager.reset();
858
6
    SAFE_STOP(_load_channel_mgr);
859
6
    SAFE_STOP(_broker_mgr);
860
6
    SAFE_STOP(_load_path_mgr);
861
6
    SAFE_STOP(_result_mgr);
862
6
    SAFE_STOP(_group_commit_mgr);
863
    // _routine_load_task_executor should be stopped before _new_load_stream_mgr.
864
6
    SAFE_STOP(_routine_load_task_executor);
865
6
    SAFE_STOP(_stream_load_recorder_manager);
866
    // stop workload scheduler
867
6
    SAFE_STOP(_workload_sched_mgr);
868
    // Stop workload group execution threads before FragmentMgr. Running pipeline tasks can still
869
    // report status through FragmentMgr's async thread pool.
870
6
    SAFE_STOP(_workload_group_manager);
871
872
6
    SAFE_STOP(_external_scan_context_mgr);
873
6
    SAFE_STOP(_fragment_mgr);
874
6
    SAFE_STOP(_runtime_filter_timer_queue);
875
    // NewLoadStreamMgr should be destoried before storage_engine & after fragment_mgr stopped.
876
6
    _load_stream_mgr.reset();
877
6
    _new_load_stream_mgr.reset();
878
6
    _stream_load_executor.reset();
879
6
    _memtable_memory_limiter.reset();
880
6
    _delta_writer_v2_pool.reset();
881
6
    _load_stream_map_pool.reset();
882
    // Workload group schedulers own the query pipeline, scan, and memtable flush queues.
883
    // Release them after fragment/load resources have stopped submitting cleanup work.
884
6
    if (_workload_group_manager) {
885
2
        _workload_group_manager->destroy_schedulers();
886
2
    }
887
6
    SAFE_STOP(_write_cooldown_meta_executors);
888
889
    // _id_manager must be destoried before tablet schema cache
890
6
    SAFE_DELETE(_id_manager);
891
892
    // Stop cluster info background worker before storage engine is destroyed
893
6
    if (config::is_cloud_mode() && _cluster_info) {
894
0
        static_cast<CloudClusterInfo*>(_cluster_info)->stop_bg_worker();
895
0
    }
896
897
    // StorageEngine must be destoried before _cache_manager destory.
898
6
    SAFE_STOP(_storage_engine);
899
6
    _storage_engine.reset();
900
901
6
    SAFE_STOP(_spill_file_mgr);
902
6
    if (_runtime_query_statistics_mgr) {
903
2
        _runtime_query_statistics_mgr->stop_report_thread();
904
2
    }
905
6
    SAFE_SHUTDOWN(_buffered_reader_prefetch_thread_pool);
906
6
    SAFE_SHUTDOWN(_segment_prefetch_thread_pool);
907
6
    SAFE_SHUTDOWN(_s3_file_upload_thread_pool);
908
6
    SAFE_SHUTDOWN(_lazy_release_obj_pool);
909
6
    SAFE_SHUTDOWN(_non_block_close_thread_pool);
910
6
    SAFE_SHUTDOWN(_s3_file_system_thread_pool);
911
6
    SAFE_SHUTDOWN(_peer_race_s3_thread_pool);
912
6
    SAFE_SHUTDOWN(_send_batch_thread_pool);
913
6
    SAFE_SHUTDOWN(_udf_close_workers_thread_pool);
914
6
    SAFE_SHUTDOWN(_send_table_stats_thread_pool);
915
916
6
    SAFE_DELETE(_load_channel_mgr);
917
918
6
    SAFE_DELETE(_inverted_index_query_cache);
919
6
    SAFE_DELETE(_inverted_index_searcher_cache);
920
6
    SAFE_DELETE(_condition_cache);
921
6
    SAFE_DELETE(_encoding_info_resolver);
922
6
    SAFE_DELETE(_lookup_connection_cache);
923
6
    SAFE_DELETE(_segment_loader);
924
6
    SAFE_DELETE(_row_cache);
925
6
    SAFE_DELETE(_query_cache);
926
6
    SAFE_DELETE(_delete_bitmap_agg_cache);
927
928
    // Free resource after threads are stopped.
929
    // Some threads are still running, like threads created by _new_load_stream_mgr ...
930
6
    SAFE_DELETE(_tablet_schema_cache);
931
6
    SAFE_DELETE(_tablet_column_object_pool);
932
933
    // _storage_page_cache must be destoried before _cache_manager
934
6
    SAFE_DELETE(_ann_index_ivf_list_cache);
935
6
    SAFE_DELETE(_storage_page_cache);
936
937
6
    SAFE_DELETE(_small_file_mgr);
938
6
    SAFE_DELETE(_broker_mgr);
939
6
    SAFE_DELETE(_load_path_mgr);
940
6
    SAFE_DELETE(_result_mgr);
941
6
    SAFE_DELETE(_file_meta_cache);
942
6
    SAFE_DELETE(_group_commit_mgr);
943
6
    SAFE_DELETE(_cdc_client_mgr);
944
6
    SAFE_DELETE(_routine_load_task_executor);
945
6
    SAFE_DELETE(_stream_load_recorder_manager);
946
    // _stream_load_executor
947
6
    SAFE_DELETE(_function_client_cache);
948
6
    SAFE_DELETE(_streaming_client_cache);
949
6
    SAFE_DELETE(_internal_client_cache);
950
951
6
    SAFE_DELETE(_bfd_parser);
952
6
    SAFE_DELETE(_result_cache);
953
6
    SAFE_DELETE(_vstream_mgr);
954
    // When _vstream_mgr is deconstructed, it will try call query context's dctor and will
955
    // access spill stream mgr, so spill stream mgr should be deconstructed after data stream manager
956
6
    SAFE_DELETE(_spill_file_mgr);
957
6
    SAFE_DELETE(_fragment_mgr);
958
6
    SAFE_DELETE(_workload_sched_mgr);
959
6
    SAFE_DELETE(_workload_group_manager);
960
6
    SAFE_DELETE(_file_cache_factory);
961
6
    SAFE_DELETE(_runtime_filter_timer_queue);
962
6
    SAFE_DELETE(_dict_factory);
963
    // TODO(zhiqiang): Maybe we should call shutdown before release thread pool?
964
6
    _lazy_release_obj_pool.reset(nullptr);
965
6
    _non_block_close_thread_pool.reset(nullptr);
966
6
    _s3_file_system_thread_pool.reset(nullptr);
967
6
    _peer_race_s3_thread_pool.reset(nullptr);
968
6
    _send_table_stats_thread_pool.reset(nullptr);
969
6
    _buffered_reader_prefetch_thread_pool.reset(nullptr);
970
6
    _segment_prefetch_thread_pool.reset(nullptr);
971
6
    _s3_file_upload_thread_pool.reset(nullptr);
972
6
    _send_batch_thread_pool.reset(nullptr);
973
6
    _udf_close_workers_thread_pool.reset(nullptr);
974
6
    _write_cooldown_meta_executors.reset(nullptr);
975
976
6
    SAFE_DELETE(_broker_client_cache);
977
6
    SAFE_DELETE(_frontend_client_cache);
978
6
    SAFE_DELETE(_backend_client_cache);
979
6
    SAFE_DELETE(_result_queue_mgr);
980
981
6
    SAFE_DELETE(_external_scan_context_mgr);
982
6
    SAFE_DELETE(_user_function_cache);
983
984
    // cache_manager must be destoried after all cache.
985
    // https://github.com/apache/doris/issues/24082#issuecomment-1712544039
986
6
    SAFE_DELETE(_cache_manager);
987
6
    _file_cache_open_fd_cache.reset(nullptr);
988
989
    // _heartbeat_flags must be destoried after staroge engine
990
6
    SAFE_DELETE(_heartbeat_flags);
991
992
    // Master Info is a thrift object, it could be the last one to deconstruct.
993
    // Master info should be deconstruct later than fragment manager, because fragment will
994
    // access cluster_info.backend_id to access some info. If there is a running query and master
995
    // info is deconstructed then BE process will core at coordinator back method in fragment mgr.
996
6
    SAFE_DELETE(_cluster_info);
997
998
    // NOTE: runtime query statistics mgr could be visited by query and daemon thread
999
    // so it should be created before all query begin and deleted after all query and daemon thread stoppped
1000
6
    SAFE_DELETE(_runtime_query_statistics_mgr);
1001
1002
6
    SAFE_DELETE(_arrow_memory_pool);
1003
1004
6
    SAFE_DELETE(_orc_memory_pool);
1005
1006
    // dns cache is a global instance and need to be released at last
1007
6
    SAFE_DELETE(_dns_cache);
1008
6
    SAFE_DELETE(_kerberos_ticket_mgr);
1009
6
    SAFE_DELETE(_hdfs_mgr);
1010
    // PackedFileManager is a singleton, just stop its background thread
1011
6
    if (_packed_file_manager) {
1012
2
        _packed_file_manager->stop_background_manager();
1013
2
        _packed_file_manager = nullptr;
1014
2
    }
1015
1016
6
    SAFE_DELETE(_process_profile);
1017
6
    SAFE_DELETE(_heap_profiler);
1018
1019
6
    SAFE_DELETE(_index_policy_mgr);
1020
6
    SAFE_DELETE(_warmup_download_rate_limiter);
1021
1022
6
    _s_tracking_memory = false;
1023
1024
6
    clear_storage_resource();
1025
6
    PythonServerManager::instance().shutdown();
1026
6
    LOG(INFO) << "Doris exec envorinment is destoried.";
1027
6
}
1028
1029
} // namespace doris
1030
1031
namespace doris::config {
1032
namespace {
1033
1034
0
void refresh_ms_rpc_rate_limiters() {
1035
0
    auto* services = ExecEnv::GetInstance()->ms_rpc_rate_limit_services();
1036
0
    if (services != nullptr) {
1037
0
        services->reset_host_level_rate_limiters();
1038
0
    }
1039
0
}
1040
1041
0
void refresh_ms_backpressure_throttle_params() {
1042
0
    auto* services = ExecEnv::GetInstance()->ms_rpc_rate_limit_services();
1043
0
    if (services != nullptr) {
1044
0
        services->update_backpressure_throttle_params(ms_backpressure_upgrade_top_k,
1045
0
                                                      ms_backpressure_throttle_ratio,
1046
0
                                                      ms_rpc_table_qps_limit_floor);
1047
0
    }
1048
0
}
1049
1050
0
void refresh_ms_backpressure_coordinator_params() {
1051
0
    auto* services = ExecEnv::GetInstance()->ms_rpc_rate_limit_services();
1052
0
    if (services != nullptr) {
1053
0
        services->update_backpressure_coordinator_params(ms_backpressure_upgrade_interval_ms,
1054
0
                                                         ms_backpressure_downgrade_interval_ms);
1055
0
    }
1056
0
}
1057
1058
} // namespace
1059
1060
// Callback to update warmup download rate limiter when config changes is registered
1061
DEFINE_ON_UPDATE(file_cache_warmup_download_rate_limit_bytes_per_second,
1062
                 [](int64_t old_val, int64_t new_val) {
1063
                     auto* rate_limiter = ExecEnv::GetInstance()->warmup_download_rate_limiter();
1064
                     if (rate_limiter != nullptr && new_val != old_val) {
1065
                         // Reset rate limiter with new rate limit value
1066
                         // When new_val <= 0, pass 0 to disable rate limiting
1067
                         int64_t rate = new_val > 0 ? new_val : 0;
1068
                         rate_limiter->reset(rate, rate, 0);
1069
                         if (rate > 0) {
1070
                             LOG(INFO) << "Warmup download rate limiter updated from " << old_val
1071
                                       << " to " << new_val << " bytes/s";
1072
                         } else {
1073
                             LOG(INFO) << "Warmup download rate limiter disabled";
1074
                         }
1075
                     }
1076
                 });
1077
1078
DEFINE_ON_UPDATE(ms_rpc_qps_default, [](int32_t old_val, int32_t new_val) {
1079
    if (old_val != new_val) {
1080
        refresh_ms_rpc_rate_limiters();
1081
    }
1082
});
1083
1084
#define DEFINE_MS_RPC_QPS_ON_UPDATE(enum_name, config_suffix, display_name)             \
1085
    DEFINE_ON_UPDATE(ms_rpc_qps_##config_suffix, [](int32_t old_val, int32_t new_val) { \
1086
        if (old_val != new_val) {                                                       \
1087
            refresh_ms_rpc_rate_limiters();                                             \
1088
        }                                                                               \
1089
    });
1090
META_SERVICE_RPC_TYPES(DEFINE_MS_RPC_QPS_ON_UPDATE)
1091
#undef DEFINE_MS_RPC_QPS_ON_UPDATE
1092
1093
DEFINE_ON_UPDATE(ms_backpressure_upgrade_interval_ms, [](int32_t old_val, int32_t new_val) {
1094
    if (old_val != new_val) {
1095
        refresh_ms_backpressure_coordinator_params();
1096
    }
1097
});
1098
DEFINE_ON_UPDATE(ms_backpressure_downgrade_interval_ms, [](int32_t old_val, int32_t new_val) {
1099
    if (old_val != new_val) {
1100
        refresh_ms_backpressure_coordinator_params();
1101
    }
1102
});
1103
DEFINE_ON_UPDATE(ms_backpressure_upgrade_top_k, [](int32_t old_val, int32_t new_val) {
1104
    if (old_val != new_val) {
1105
        refresh_ms_backpressure_throttle_params();
1106
    }
1107
});
1108
DEFINE_ON_UPDATE(ms_backpressure_throttle_ratio, [](double old_val, double new_val) {
1109
    if (old_val != new_val) {
1110
        refresh_ms_backpressure_throttle_params();
1111
    }
1112
});
1113
DEFINE_ON_UPDATE(ms_rpc_table_qps_limit_floor, [](double old_val, double new_val) {
1114
    if (old_val != new_val) {
1115
        refresh_ms_backpressure_throttle_params();
1116
    }
1117
});
1118
} // namespace doris::config