Coverage Report

Created: 2026-04-01 07:58

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