Coverage Report

Created: 2026-03-30 11:06

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/cloud/cloud_storage_engine.cpp
Line
Count
Source
1
// Licensed to the Apache Software Foundation (ASF) under one
2
// or more contributor license agreements.  See the NOTICE file
3
// distributed with this work for additional information
4
// regarding copyright ownership.  The ASF licenses this file
5
// to you under the Apache License, Version 2.0 (the
6
// "License"); you may not use this file except in compliance
7
// with the License.  You may obtain a copy of the License at
8
//
9
//   http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied.  See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
18
#include "cloud/cloud_storage_engine.h"
19
20
#include <bvar/reducer.h>
21
#include <gen_cpp/PlanNodes_types.h>
22
#include <gen_cpp/cloud.pb.h>
23
#include <gen_cpp/olap_file.pb.h>
24
#include <rapidjson/document.h>
25
#include <rapidjson/encodings.h>
26
#include <rapidjson/prettywriter.h>
27
#include <rapidjson/stringbuffer.h>
28
29
#include <algorithm>
30
#include <memory>
31
#include <variant>
32
33
#include "cloud/cloud_base_compaction.h"
34
#include "cloud/cloud_compaction_stop_token.h"
35
#include "cloud/cloud_cumulative_compaction.h"
36
#include "cloud/cloud_cumulative_compaction_policy.h"
37
#include "cloud/cloud_full_compaction.h"
38
#include "cloud/cloud_index_change_compaction.h"
39
#include "cloud/cloud_meta_mgr.h"
40
#include "cloud/cloud_snapshot_mgr.h"
41
#include "cloud/cloud_tablet_hotspot.h"
42
#include "cloud/cloud_tablet_mgr.h"
43
#include "cloud/cloud_txn_delete_bitmap_cache.h"
44
#include "cloud/cloud_warm_up_manager.h"
45
#include "cloud/config.h"
46
#include "common/config.h"
47
#include "common/metrics/doris_metrics.h"
48
#include "common/signal_handler.h"
49
#include "common/status.h"
50
#include "core/assert_cast.h"
51
#include "io/cache/block_file_cache_downloader.h"
52
#include "io/cache/block_file_cache_factory.h"
53
#include "io/cache/file_cache_common.h"
54
#include "io/fs/file_system.h"
55
#include "io/fs/hdfs_file_system.h"
56
#include "io/fs/s3_file_system.h"
57
#include "io/hdfs_util.h"
58
#include "io/io_common.h"
59
#include "load/memtable/memtable_flush_executor.h"
60
#include "runtime/exec_env.h"
61
#include "runtime/memory/cache_manager.h"
62
#include "storage/compaction/cumulative_compaction_policy.h"
63
#include "storage/compaction/cumulative_compaction_time_series_policy.h"
64
#include "storage/storage_policy.h"
65
#include "util/parse_util.h"
66
#include "util/time.h"
67
68
namespace doris {
69
#include "common/compile_check_begin.h"
70
71
using namespace std::literals;
72
73
bvar::Adder<uint64_t> g_base_compaction_running_task_count("base_compaction_running_task_count");
74
bvar::Adder<uint64_t> g_full_compaction_running_task_count("full_compaction_running_task_count");
75
bvar::Adder<uint64_t> g_cumu_compaction_running_task_count(
76
        "cumulative_compaction_running_task_count");
77
78
20.4k
int get_cumu_thread_num() {
79
20.4k
    if (config::max_cumu_compaction_threads > 0) {
80
0
        return config::max_cumu_compaction_threads;
81
0
    }
82
83
20.4k
    int num_cores = doris::CpuInfo::num_cores();
84
20.4k
    return std::min(std::max(int(num_cores * config::cumu_compaction_thread_num_factor), 2), 20);
85
20.4k
}
86
87
20.4k
int get_base_thread_num() {
88
20.4k
    if (config::max_base_compaction_threads > 0) {
89
20.4k
        return config::max_base_compaction_threads;
90
20.4k
    }
91
92
0
    int num_cores = doris::CpuInfo::num_cores();
93
0
    return std::min(std::max(int(num_cores * config::base_compaction_thread_num_factor), 1), 10);
94
20.4k
}
95
96
CloudStorageEngine::CloudStorageEngine(const EngineOptions& options)
97
154
        : BaseStorageEngine(Type::CLOUD, options.backend_uid),
98
154
          _meta_mgr(std::make_unique<cloud::CloudMetaMgr>()),
99
154
          _tablet_mgr(std::make_unique<CloudTabletMgr>(*this)),
100
154
          _options(options) {
101
154
    _cumulative_compaction_policies[CUMULATIVE_SIZE_BASED_POLICY] =
102
154
            std::make_shared<CloudSizeBasedCumulativeCompactionPolicy>();
103
154
    _cumulative_compaction_policies[CUMULATIVE_TIME_SERIES_POLICY] =
104
154
            std::make_shared<CloudTimeSeriesCumulativeCompactionPolicy>();
105
154
    _startup_timepoint = std::chrono::system_clock::now();
106
154
}
107
108
153
CloudStorageEngine::~CloudStorageEngine() {
109
153
    stop();
110
153
}
111
112
static Status vault_process_error(std::string_view id,
113
0
                                  std::variant<S3Conf, cloud::HdfsVaultInfo>& vault, Status err) {
114
0
    std::stringstream ss;
115
0
    std::visit(
116
0
            [&]<typename T>(T& val) {
117
0
                if constexpr (std::is_same_v<T, S3Conf>) {
118
0
                    ss << val.to_string();
119
0
                } else if constexpr (std::is_same_v<T, cloud::HdfsVaultInfo>) {
120
0
                    val.SerializeToOstream(&ss);
121
0
                }
122
0
            },
Unexecuted instantiation: cloud_storage_engine.cpp:_ZZN5dorisL19vault_process_errorESt17basic_string_viewIcSt11char_traitsIcEERSt7variantIJNS_6S3ConfENS_5cloud13HdfsVaultInfoEEENS_6StatusEENK3$_0clIS5_EEDaRT_
Unexecuted instantiation: cloud_storage_engine.cpp:_ZZN5dorisL19vault_process_errorESt17basic_string_viewIcSt11char_traitsIcEERSt7variantIJNS_6S3ConfENS_5cloud13HdfsVaultInfoEEENS_6StatusEENK3$_0clIS7_EEDaRT_
123
0
            vault);
124
0
    return Status::IOError("Invalid vault, id {}, err {}, detail conf {}", id, err, ss.str());
125
0
}
126
127
struct VaultCreateFSVisitor {
128
    VaultCreateFSVisitor(const std::string& id, const cloud::StorageVaultPB_PathFormat& path_format,
129
                         bool check_fs)
130
1
            : id(id), path_format(path_format), check_fs(check_fs) {}
131
1
    Status operator()(const S3Conf& s3_conf) const {
132
1
        LOG(INFO) << "get new s3 info: " << s3_conf.to_string() << " resource_id=" << id
133
1
                  << " check_fs: " << check_fs;
134
135
1
        auto fs = DORIS_TRY(io::S3FileSystem::create(s3_conf, id));
136
1
        if (check_fs && !s3_conf.client_conf.role_arn.empty()) {
137
0
            bool res = false;
138
            // just check connectivity, not care object if exist
139
0
            auto st = fs->exists("not_exist_object", &res);
140
0
            if (!st.ok()) {
141
0
                LOG(FATAL) << "failed to check s3 fs, resource_id: " << id << " st: " << st
142
0
                           << "s3_conf: " << s3_conf.to_string()
143
0
                           << "add enable_check_storage_vault=false to be.conf to skip the check";
144
0
            }
145
0
        }
146
147
1
        put_storage_resource(id, {std::move(fs), path_format}, 0);
148
1
        LOG_INFO("successfully create s3 vault, vault id {}", id);
149
1
        return Status::OK();
150
1
    }
151
152
    // TODO(ByteYue): Make sure enable_java_support is on
153
0
    Status operator()(const cloud::HdfsVaultInfo& vault) const {
154
0
        auto hdfs_params = io::to_hdfs_params(vault);
155
0
        auto fs = DORIS_TRY(io::HdfsFileSystem::create(hdfs_params, hdfs_params.fs_name, id,
156
0
                                                       nullptr, vault.prefix()));
157
0
        put_storage_resource(id, {std::move(fs), path_format}, 0);
158
0
        LOG_INFO("successfully create hdfs vault, vault id {}", id);
159
0
        return Status::OK();
160
0
    }
161
162
    const std::string& id;
163
    const cloud::StorageVaultPB_PathFormat& path_format;
164
    bool check_fs;
165
};
166
167
struct RefreshFSVaultVisitor {
168
    RefreshFSVaultVisitor(const std::string& id, io::FileSystemSPtr fs,
169
                          const cloud::StorageVaultPB_PathFormat& path_format)
170
241
            : id(id), fs(std::move(fs)), path_format(path_format) {}
171
172
241
    Status operator()(const S3Conf& s3_conf) const {
173
241
        DCHECK_EQ(fs->type(), io::FileSystemType::S3) << id;
174
241
        auto s3_fs = std::static_pointer_cast<io::S3FileSystem>(fs);
175
241
        auto client_holder = s3_fs->client_holder();
176
241
        auto st = client_holder->reset(s3_conf.client_conf);
177
241
        if (!st.ok()) {
178
0
            LOG(WARNING) << "failed to update s3 fs, resource_id=" << id << ": " << st;
179
0
        }
180
241
        return st;
181
241
    }
182
183
0
    Status operator()(const cloud::HdfsVaultInfo& vault) const {
184
0
        auto hdfs_params = io::to_hdfs_params(vault);
185
0
        auto hdfs_fs =
186
0
                DORIS_TRY(io::HdfsFileSystem::create(hdfs_params, hdfs_params.fs_name, id, nullptr,
187
0
                                                     vault.has_prefix() ? vault.prefix() : ""));
188
0
        auto hdfs = std::static_pointer_cast<io::HdfsFileSystem>(hdfs_fs);
189
0
        put_storage_resource(id, {std::move(hdfs), path_format}, 0);
190
0
        return Status::OK();
191
0
    }
192
193
    const std::string& id;
194
    io::FileSystemSPtr fs;
195
    const cloud::StorageVaultPB_PathFormat& path_format;
196
};
197
198
1
Status CloudStorageEngine::open() {
199
1
    sync_storage_vault();
200
201
    // TODO(plat1ko): DeleteBitmapTxnManager
202
203
1
    _memtable_flush_executor = std::make_unique<MemTableFlushExecutor>();
204
    // Use file cache disks number
205
1
    _memtable_flush_executor->init(
206
1
            cast_set<int32_t>(io::FileCacheFactory::instance()->get_cache_instance_size()));
207
208
1
    _calc_delete_bitmap_executor = std::make_unique<CalcDeleteBitmapExecutor>();
209
1
    _calc_delete_bitmap_executor->init(config::calc_delete_bitmap_max_thread);
210
211
1
    _calc_delete_bitmap_executor_for_load = std::make_unique<CalcDeleteBitmapExecutor>();
212
1
    _calc_delete_bitmap_executor_for_load->init(
213
1
            config::calc_delete_bitmap_for_load_max_thread > 0
214
1
                    ? config::calc_delete_bitmap_for_load_max_thread
215
1
                    : std::max(1, CpuInfo::num_cores() / 2));
216
217
    // The default cache is set to 100MB, use memory limit to dynamic adjustment
218
1
    bool is_percent = false;
219
1
    int64_t delete_bitmap_agg_cache_cache_limit =
220
1
            ParseUtil::parse_mem_spec(config::delete_bitmap_dynamic_agg_cache_limit,
221
1
                                      MemInfo::mem_limit(), MemInfo::physical_mem(), &is_percent);
222
1
    _txn_delete_bitmap_cache = std::make_unique<CloudTxnDeleteBitmapCache>(
223
1
            delete_bitmap_agg_cache_cache_limit > config::delete_bitmap_agg_cache_capacity
224
1
                    ? delete_bitmap_agg_cache_cache_limit
225
1
                    : config::delete_bitmap_agg_cache_capacity);
226
1
    RETURN_IF_ERROR(_txn_delete_bitmap_cache->init());
227
228
1
    _committed_rs_mgr = std::make_unique<CloudCommittedRSMgr>();
229
1
    RETURN_IF_ERROR(_committed_rs_mgr->init());
230
231
1
    _file_cache_block_downloader = std::make_unique<io::FileCacheBlockDownloader>(*this);
232
233
1
    _cloud_warm_up_manager = std::make_unique<CloudWarmUpManager>(*this);
234
235
1
    _tablet_hotspot = std::make_unique<TabletHotspot>();
236
237
1
    _cloud_snapshot_mgr = std::make_unique<CloudSnapshotMgr>(*this);
238
239
1
    RETURN_NOT_OK_STATUS_WITH_WARN(
240
1
            init_stream_load_recorder(ExecEnv::GetInstance()->store_paths()[0].path),
241
1
            "init StreamLoadRecorder failed");
242
243
    // check cluster id
244
1
    RETURN_NOT_OK_STATUS_WITH_WARN(_check_all_root_path_cluster_id(), "fail to check cluster id");
245
246
1
    RETURN_NOT_OK_STATUS_WITH_WARN(ThreadPoolBuilder("SyncLoadForTabletsThreadPool")
247
1
                                           .set_max_threads(config::sync_load_for_tablets_thread)
248
1
                                           .set_min_threads(config::sync_load_for_tablets_thread)
249
1
                                           .build(&_sync_load_for_tablets_thread_pool),
250
1
                                   "fail to build SyncLoadForTabletsThreadPool");
251
252
1
    RETURN_NOT_OK_STATUS_WITH_WARN(ThreadPoolBuilder("WarmupCacheAsyncThreadPool")
253
1
                                           .set_max_threads(config::warmup_cache_async_thread)
254
1
                                           .set_min_threads(config::warmup_cache_async_thread)
255
1
                                           .build(&_warmup_cache_async_thread_pool),
256
1
                                   "fail to build WarmupCacheAsyncThreadPool");
257
258
1
    return Status::OK();
259
1
}
260
261
153
void CloudStorageEngine::stop() {
262
153
    if (_stopped) {
263
0
        return;
264
0
    }
265
266
153
    _stopped = true;
267
153
    _stop_background_threads_latch.count_down();
268
269
153
    for (auto&& t : _bg_threads) {
270
0
        if (t) {
271
0
            t->join();
272
0
        }
273
0
    }
274
275
153
    if (_base_compaction_thread_pool) {
276
0
        _base_compaction_thread_pool->shutdown();
277
0
    }
278
153
    if (_cumu_compaction_thread_pool) {
279
0
        _cumu_compaction_thread_pool->shutdown();
280
0
    }
281
153
    _adaptive_thread_controller.stop();
282
153
    LOG(INFO) << "Cloud storage engine is stopped.";
283
284
153
    if (_calc_tablet_delete_bitmap_task_thread_pool) {
285
0
        _calc_tablet_delete_bitmap_task_thread_pool->shutdown();
286
0
    }
287
153
    if (_sync_delete_bitmap_thread_pool) {
288
0
        _sync_delete_bitmap_thread_pool->shutdown();
289
0
    }
290
153
}
291
292
61.1k
bool CloudStorageEngine::stopped() {
293
61.1k
    return _stopped;
294
61.1k
}
295
296
Result<BaseTabletSPtr> CloudStorageEngine::get_tablet(int64_t tablet_id,
297
                                                      SyncRowsetStats* sync_stats,
298
                                                      bool force_use_only_cached,
299
1.29M
                                                      bool cache_on_miss) {
300
1.29M
    return _tablet_mgr
301
1.29M
            ->get_tablet(tablet_id, false, true, sync_stats, force_use_only_cached, cache_on_miss)
302
1.29M
            .transform([](auto&& t) { return static_pointer_cast<BaseTablet>(std::move(t)); });
303
1.29M
}
304
305
Status CloudStorageEngine::get_tablet_meta(int64_t tablet_id, TabletMetaSharedPtr* tablet_meta,
306
203k
                                           bool force_use_only_cached) {
307
203k
    if (tablet_meta == nullptr) {
308
0
        return Status::InvalidArgument("tablet_meta output is null");
309
0
    }
310
311
#if 0
312
    if (_tablet_mgr && _tablet_mgr->peek_tablet_meta(tablet_id, tablet_meta)) {
313
        return Status::OK();
314
    }
315
316
    if (force_use_only_cached) {
317
        return Status::NotFound("tablet meta {} not found in cache", tablet_id);
318
    }
319
#endif
320
321
203k
    if (_meta_mgr == nullptr) {
322
0
        return Status::InternalError("cloud meta manager is not initialized");
323
0
    }
324
325
203k
    return _meta_mgr->get_tablet_meta(tablet_id, tablet_meta);
326
203k
}
327
328
1
Status CloudStorageEngine::start_bg_threads(std::shared_ptr<WorkloadGroup> wg_sptr) {
329
1
    RETURN_IF_ERROR(Thread::create(
330
1
            "CloudStorageEngine", "refresh_s3_info_thread",
331
1
            [this]() { this->_refresh_storage_vault_info_thread_callback(); },
332
1
            &_bg_threads.emplace_back()));
333
1
    LOG(INFO) << "refresh s3 info thread started";
334
335
1
    RETURN_IF_ERROR(Thread::create(
336
1
            "CloudStorageEngine", "vacuum_stale_rowsets_thread",
337
1
            [this]() { this->_vacuum_stale_rowsets_thread_callback(); },
338
1
            &_bg_threads.emplace_back()));
339
1
    LOG(INFO) << "vacuum stale rowsets thread started";
340
341
1
    RETURN_IF_ERROR(Thread::create(
342
1
            "CloudStorageEngine", "sync_tablets_thread",
343
1
            [this]() { this->_sync_tablets_thread_callback(); }, &_bg_threads.emplace_back()));
344
1
    LOG(INFO) << "sync tablets thread started";
345
346
1
    RETURN_IF_ERROR(Thread::create(
347
1
            "CloudStorageEngine", "evict_querying_rowset_thread",
348
1
            [this]() { this->_evict_quring_rowset_thread_callback(); },
349
1
            &_evict_quering_rowset_thread));
350
1
    LOG(INFO) << "evict quering thread started";
351
352
    // add calculate tablet delete bitmap task thread pool
353
1
    RETURN_IF_ERROR(ThreadPoolBuilder("TabletCalDeleteBitmapThreadPool")
354
1
                            .set_min_threads(config::calc_tablet_delete_bitmap_task_max_thread)
355
1
                            .set_max_threads(config::calc_tablet_delete_bitmap_task_max_thread)
356
1
                            .build(&_calc_tablet_delete_bitmap_task_thread_pool));
357
1
    RETURN_IF_ERROR(ThreadPoolBuilder("SyncDeleteBitmapThreadPool")
358
1
                            .set_min_threads(config::sync_delete_bitmap_task_max_thread)
359
1
                            .set_max_threads(config::sync_delete_bitmap_task_max_thread)
360
1
                            .build(&_sync_delete_bitmap_thread_pool));
361
362
    // TODO(plat1ko): check_bucket_enable_versioning_thread
363
364
    // compaction tasks producer thread
365
1
    int base_thread_num = get_base_thread_num();
366
1
    int cumu_thread_num = get_cumu_thread_num();
367
368
1
    RETURN_IF_ERROR(ThreadPoolBuilder("BaseCompactionTaskThreadPool")
369
1
                            .set_min_threads(base_thread_num)
370
1
                            .set_max_threads(base_thread_num)
371
1
                            .build(&_base_compaction_thread_pool));
372
1
    RETURN_IF_ERROR(ThreadPoolBuilder("CumuCompactionTaskThreadPool")
373
1
                            .set_min_threads(cumu_thread_num)
374
1
                            .set_max_threads(cumu_thread_num)
375
1
                            .build(&_cumu_compaction_thread_pool));
376
1
    RETURN_IF_ERROR(Thread::create(
377
1
            "StorageEngine", "compaction_tasks_producer_thread",
378
1
            [this]() { this->_compaction_tasks_producer_callback(); },
379
1
            &_bg_threads.emplace_back()));
380
1
    LOG(INFO) << "compaction tasks producer thread started,"
381
1
              << " base thread num " << base_thread_num << " cumu thread num " << cumu_thread_num;
382
383
1
    RETURN_IF_ERROR(Thread::create(
384
1
            "StorageEngine", "lease_compaction_thread",
385
1
            [this]() { this->_lease_compaction_thread_callback(); }, &_bg_threads.emplace_back()));
386
387
1
    LOG(INFO) << "lease compaction thread started";
388
389
1
    RETURN_IF_ERROR(Thread::create(
390
1
            "StorageEngine", "check_tablet_delete_bitmap_score_thread",
391
1
            [this]() { this->_check_tablet_delete_bitmap_score_callback(); },
392
1
            &_bg_threads.emplace_back()));
393
1
    LOG(INFO) << "check tablet delete bitmap score thread started";
394
395
1
    _start_adaptive_thread_controller();
396
397
1
    return Status::OK();
398
1
}
399
400
242
void CloudStorageEngine::sync_storage_vault() {
401
242
    cloud::StorageVaultInfos vault_infos;
402
242
    bool enable_storage_vault = false;
403
404
242
    auto st = _meta_mgr->get_storage_vault_info(&vault_infos, &enable_storage_vault);
405
242
    if (!st.ok()) {
406
0
        LOG(WARNING) << "failed to get storage vault info. err=" << st;
407
0
        return;
408
0
    }
409
410
242
    if (vault_infos.empty()) {
411
0
        LOG(WARNING) << "empty storage vault info";
412
0
        return;
413
0
    }
414
415
242
    bool check_storage_vault = false;
416
242
    bool expected = false;
417
242
    if (first_sync_storage_vault.compare_exchange_strong(expected, true)) {
418
0
        check_storage_vault = config::enable_check_storage_vault;
419
0
        LOG(INFO) << "first sync storage vault info, BE try to check iam role connectivity, "
420
0
                     "check_storage_vault="
421
0
                  << check_storage_vault;
422
0
    }
423
424
242
    for (auto& [id, vault_info, path_format] : vault_infos) {
425
242
        auto fs = get_filesystem(id);
426
242
        auto status =
427
242
                (fs == nullptr)
428
242
                        ? std::visit(VaultCreateFSVisitor {id, path_format, check_storage_vault},
429
1
                                     vault_info)
430
242
                        : std::visit(RefreshFSVaultVisitor {id, std::move(fs), path_format},
431
241
                                     vault_info);
432
242
        if (!status.ok()) [[unlikely]] {
433
0
            LOG(WARNING) << vault_process_error(id, vault_info, std::move(st));
434
0
        }
435
242
    }
436
437
242
    if (auto& id = std::get<0>(vault_infos.back());
438
242
        (latest_fs() == nullptr || latest_fs()->id() != id) && !enable_storage_vault) {
439
1
        set_latest_fs(get_filesystem(id));
440
1
    }
441
242
}
442
443
// We should enable_java_support if we want to use hdfs vault
444
1
void CloudStorageEngine::_refresh_storage_vault_info_thread_callback() {
445
66
    while (!_stop_background_threads_latch.wait_for(
446
66
            std::chrono::seconds(config::refresh_s3_info_interval_s))) {
447
65
        sync_storage_vault();
448
65
    }
449
1
}
450
451
1
void CloudStorageEngine::_vacuum_stale_rowsets_thread_callback() {
452
14
    while (!_stop_background_threads_latch.wait_for(
453
14
            std::chrono::seconds(config::vacuum_stale_rowsets_interval_s))) {
454
13
        _tablet_mgr->vacuum_stale_rowsets(_stop_background_threads_latch);
455
13
    }
456
1
}
457
458
1
void CloudStorageEngine::_sync_tablets_thread_callback() {
459
7
    while (!_stop_background_threads_latch.wait_for(
460
7
            std::chrono::seconds(config::schedule_sync_tablets_interval_s))) {
461
6
        _tablet_mgr->sync_tablets(_stop_background_threads_latch);
462
6
    }
463
1
}
464
465
void CloudStorageEngine::get_cumu_compaction(
466
117k
        int64_t tablet_id, std::vector<std::shared_ptr<CloudCumulativeCompaction>>& res) {
467
117k
    std::lock_guard lock(_compaction_mtx);
468
117k
    if (auto it = _submitted_cumu_compactions.find(tablet_id);
469
117k
        it != _submitted_cumu_compactions.end()) {
470
0
        res = it->second;
471
0
    }
472
117k
}
473
474
20.4k
Status CloudStorageEngine::_adjust_compaction_thread_num() {
475
20.4k
    int base_thread_num = get_base_thread_num();
476
477
20.4k
    if (!_base_compaction_thread_pool || !_cumu_compaction_thread_pool) {
478
0
        LOG(WARNING) << "base or cumu compaction thread pool is not created";
479
0
        return Status::Error<ErrorCode::INTERNAL_ERROR, false>("");
480
0
    }
481
482
20.4k
    if (_base_compaction_thread_pool->max_threads() != base_thread_num) {
483
0
        int old_max_threads = _base_compaction_thread_pool->max_threads();
484
0
        Status status = _base_compaction_thread_pool->set_max_threads(base_thread_num);
485
0
        if (status.ok()) {
486
0
            VLOG_NOTICE << "update base compaction thread pool max_threads from " << old_max_threads
487
0
                        << " to " << base_thread_num;
488
0
        }
489
0
    }
490
20.4k
    if (_base_compaction_thread_pool->min_threads() != base_thread_num) {
491
0
        int old_min_threads = _base_compaction_thread_pool->min_threads();
492
0
        Status status = _base_compaction_thread_pool->set_min_threads(base_thread_num);
493
0
        if (status.ok()) {
494
0
            VLOG_NOTICE << "update base compaction thread pool min_threads from " << old_min_threads
495
0
                        << " to " << base_thread_num;
496
0
        }
497
0
    }
498
499
20.4k
    int cumu_thread_num = get_cumu_thread_num();
500
20.4k
    if (_cumu_compaction_thread_pool->max_threads() != cumu_thread_num) {
501
0
        int old_max_threads = _cumu_compaction_thread_pool->max_threads();
502
0
        Status status = _cumu_compaction_thread_pool->set_max_threads(cumu_thread_num);
503
0
        if (status.ok()) {
504
0
            VLOG_NOTICE << "update cumu compaction thread pool max_threads from " << old_max_threads
505
0
                        << " to " << cumu_thread_num;
506
0
        }
507
0
    }
508
20.4k
    if (_cumu_compaction_thread_pool->min_threads() != cumu_thread_num) {
509
0
        int old_min_threads = _cumu_compaction_thread_pool->min_threads();
510
0
        Status status = _cumu_compaction_thread_pool->set_min_threads(cumu_thread_num);
511
0
        if (status.ok()) {
512
0
            VLOG_NOTICE << "update cumu compaction thread pool min_threads from " << old_min_threads
513
0
                        << " to " << cumu_thread_num;
514
0
        }
515
0
    }
516
20.4k
    return Status::OK();
517
20.4k
}
518
519
1
void CloudStorageEngine::_compaction_tasks_producer_callback() {
520
1
    LOG(INFO) << "try to start compaction producer process!";
521
522
1
    int round = 0;
523
1
    CompactionType compaction_type;
524
525
    // Used to record the time when the score metric was last updated.
526
    // The update of the score metric is accompanied by the logic of selecting the tablet.
527
    // If there is no slot available, the logic of selecting the tablet will be terminated,
528
    // which causes the score metric update to be terminated.
529
    // In order to avoid this situation, we need to update the score regularly.
530
1
    int64_t last_cumulative_score_update_time = 0;
531
1
    int64_t last_base_score_update_time = 0;
532
1
    static const int64_t check_score_interval_ms = 5000; // 5 secs
533
534
1
    int64_t interval = config::generate_compaction_tasks_interval_ms;
535
20.4k
    do {
536
20.4k
        int64_t cur_time = UnixMillis();
537
20.4k
        if (!config::disable_auto_compaction) {
538
20.4k
            Status st = _adjust_compaction_thread_num();
539
20.4k
            if (!st.ok()) {
540
0
                break;
541
0
            }
542
543
20.4k
            bool check_score = false;
544
20.4k
            if (round < config::cumulative_compaction_rounds_for_each_base_compaction_round) {
545
18.3k
                compaction_type = CompactionType::CUMULATIVE_COMPACTION;
546
18.3k
                round++;
547
18.3k
                if (cur_time - last_cumulative_score_update_time >= check_score_interval_ms) {
548
756
                    check_score = true;
549
756
                    last_cumulative_score_update_time = cur_time;
550
756
                }
551
18.3k
            } else {
552
2.04k
                compaction_type = CompactionType::BASE_COMPACTION;
553
2.04k
                round = 0;
554
2.04k
                if (cur_time - last_base_score_update_time >= check_score_interval_ms) {
555
626
                    check_score = true;
556
626
                    last_base_score_update_time = cur_time;
557
626
                }
558
2.04k
            }
559
20.4k
            std::unique_ptr<ThreadPool>& thread_pool =
560
20.4k
                    (compaction_type == CompactionType::CUMULATIVE_COMPACTION)
561
20.4k
                            ? _cumu_compaction_thread_pool
562
20.4k
                            : _base_compaction_thread_pool;
563
20.4k
            VLOG_CRITICAL << "compaction thread pool. type: "
564
0
                          << (compaction_type == CompactionType::CUMULATIVE_COMPACTION ? "CUMU"
565
0
                                                                                       : "BASE")
566
0
                          << ", num_threads: " << thread_pool->num_threads()
567
0
                          << ", num_threads_pending_start: "
568
0
                          << thread_pool->num_threads_pending_start()
569
0
                          << ", num_active_threads: " << thread_pool->num_active_threads()
570
0
                          << ", max_threads: " << thread_pool->max_threads()
571
0
                          << ", min_threads: " << thread_pool->min_threads()
572
0
                          << ", num_total_queued_tasks: " << thread_pool->get_queue_size();
573
20.4k
            std::vector<CloudTabletSPtr> tablets_compaction =
574
20.4k
                    _generate_cloud_compaction_tasks(compaction_type, check_score);
575
576
            /// Regardless of whether the tablet is submitted for compaction or not,
577
            /// we need to call 'reset_compaction' to clean up the base_compaction or cumulative_compaction objects
578
            /// in the tablet, because these two objects store the tablet's own shared_ptr.
579
            /// If it is not cleaned up, the reference count of the tablet will always be greater than 1,
580
            /// thus cannot be collected by the garbage collector. (TabletManager::start_trash_sweep)
581
120k
            for (const auto& tablet : tablets_compaction) {
582
120k
                Status status = submit_compaction_task(tablet, compaction_type);
583
120k
                if (status.ok()) continue;
584
114k
                if ((!status.is<ErrorCode::BE_NO_SUITABLE_VERSION>() &&
585
114k
                     !status.is<ErrorCode::CUMULATIVE_NO_SUITABLE_VERSION>()) ||
586
114k
                    VLOG_DEBUG_IS_ON) {
587
40
                    LOG(WARNING) << "failed to submit compaction task for tablet: "
588
40
                                 << tablet->tablet_id() << ", err: " << status;
589
40
                }
590
114k
            }
591
20.4k
            interval = config::generate_compaction_tasks_interval_ms;
592
20.4k
        } else {
593
0
            interval = config::check_auto_compaction_interval_seconds * 1000;
594
0
        }
595
20.4k
        int64_t end_time = UnixMillis();
596
20.4k
        DorisMetrics::instance()->compaction_producer_callback_a_round_time->set_value(end_time -
597
20.4k
                                                                                       cur_time);
598
20.4k
    } while (!_stop_background_threads_latch.wait_for(std::chrono::milliseconds(interval)));
599
1
}
600
601
void CloudStorageEngine::unregister_index_change_compaction(int64_t tablet_id,
602
835
                                                            bool is_base_compact) {
603
835
    std::lock_guard lock(_compaction_mtx);
604
835
    if (is_base_compact) {
605
0
        _submitted_index_change_base_compaction.erase(tablet_id);
606
835
    } else {
607
835
        _submitted_index_change_cumu_compaction.erase(tablet_id);
608
835
    }
609
835
}
610
611
bool CloudStorageEngine::register_index_change_compaction(
612
        std::shared_ptr<CloudIndexChangeCompaction> compact, int64_t tablet_id,
613
837
        bool is_base_compact, std::string& err_reason) {
614
837
    std::lock_guard lock(_compaction_mtx);
615
837
    if (is_base_compact) {
616
2
        if (_submitted_base_compactions.contains(tablet_id) ||
617
2
            _submitted_full_compactions.contains(tablet_id) ||
618
2
            _submitted_index_change_base_compaction.contains(tablet_id)) {
619
1
            std::stringstream ss;
620
1
            ss << "reason:" << ((int)_submitted_base_compactions.contains(tablet_id)) << ", "
621
1
               << ((int)_submitted_full_compactions.contains(tablet_id)) << ", "
622
1
               << ((int)_submitted_index_change_base_compaction.contains(tablet_id));
623
1
            err_reason = ss.str();
624
1
            return false;
625
1
        } else {
626
1
            _submitted_index_change_base_compaction[tablet_id] = compact;
627
1
            return true;
628
1
        }
629
835
    } else {
630
835
        if (_tablet_preparing_cumu_compaction.contains(tablet_id) ||
631
839
            _submitted_cumu_compactions.contains(tablet_id) ||
632
836
            _submitted_index_change_cumu_compaction.contains(tablet_id)) {
633
3
            std::stringstream ss;
634
3
            ss << "reason:" << ((int)_tablet_preparing_cumu_compaction.contains(tablet_id)) << ", "
635
3
               << ((int)_submitted_cumu_compactions.contains(tablet_id)) << ", "
636
3
               << ((int)_submitted_index_change_cumu_compaction.contains(tablet_id));
637
3
            err_reason = ss.str();
638
3
            return false;
639
832
        } else {
640
832
            _submitted_index_change_cumu_compaction[tablet_id] = compact;
641
832
        }
642
832
        return true;
643
835
    }
644
837
}
645
646
std::vector<CloudTabletSPtr> CloudStorageEngine::_generate_cloud_compaction_tasks(
647
20.4k
        CompactionType compaction_type, bool check_score) {
648
20.4k
    std::vector<std::shared_ptr<CloudTablet>> tablets_compaction;
649
650
20.4k
    int64_t max_compaction_score = 0;
651
20.4k
    std::unordered_set<int64_t> tablet_preparing_cumu_compaction;
652
20.4k
    std::unordered_map<int64_t, std::vector<std::shared_ptr<CloudCumulativeCompaction>>>
653
20.4k
            submitted_cumu_compactions;
654
20.4k
    std::unordered_map<int64_t, std::shared_ptr<CloudBaseCompaction>> submitted_base_compactions;
655
20.4k
    std::unordered_map<int64_t, std::shared_ptr<CloudFullCompaction>> submitted_full_compactions;
656
20.4k
    std::unordered_map<int64_t, std::shared_ptr<CloudIndexChangeCompaction>>
657
20.4k
            submitted_index_change_cumu_compactions;
658
20.4k
    std::unordered_map<int64_t, std::shared_ptr<CloudIndexChangeCompaction>>
659
20.4k
            submitted_index_change_base_compactions;
660
20.4k
    {
661
20.4k
        std::lock_guard lock(_compaction_mtx);
662
20.4k
        tablet_preparing_cumu_compaction = _tablet_preparing_cumu_compaction;
663
20.4k
        submitted_cumu_compactions = _submitted_cumu_compactions;
664
20.4k
        submitted_base_compactions = _submitted_base_compactions;
665
20.4k
        submitted_full_compactions = _submitted_full_compactions;
666
20.4k
        submitted_index_change_cumu_compactions = _submitted_index_change_cumu_compaction;
667
20.4k
        submitted_index_change_base_compactions = _submitted_index_change_base_compaction;
668
20.4k
    }
669
670
20.4k
    bool need_pick_tablet = true;
671
20.4k
    int thread_per_disk =
672
20.4k
            config::compaction_task_num_per_fast_disk; // all disks are fast in cloud mode
673
20.4k
    int num_cumu =
674
20.4k
            std::accumulate(submitted_cumu_compactions.begin(), submitted_cumu_compactions.end(), 0,
675
20.4k
                            [](int a, auto& b) { return a + b.second.size(); });
676
20.4k
    int num_base =
677
20.4k
            cast_set<int>(submitted_base_compactions.size() + submitted_full_compactions.size());
678
20.4k
    int n = thread_per_disk - num_cumu - num_base;
679
20.4k
    if (compaction_type == CompactionType::BASE_COMPACTION) {
680
        // We need to reserve at least one thread for cumulative compaction,
681
        // because base compactions may take too long to complete, which may
682
        // leads to "too many rowsets" error.
683
2.04k
        int base_n = std::min(config::max_base_compaction_task_num_per_disk, thread_per_disk - 1) -
684
2.04k
                     num_base;
685
2.04k
        n = std::min(base_n, n);
686
2.04k
    }
687
20.4k
    if (n <= 0) { // No threads available
688
556
        if (!check_score) return tablets_compaction;
689
33
        need_pick_tablet = false;
690
33
        n = 0;
691
33
    }
692
693
    // Return true for skipping compaction
694
19.9k
    std::function<bool(CloudTablet*)> filter_out;
695
19.9k
    if (compaction_type == CompactionType::BASE_COMPACTION) {
696
2.00k
        filter_out = [&submitted_base_compactions, &submitted_full_compactions,
697
75.6M
                      &submitted_index_change_base_compactions](CloudTablet* t) {
698
75.6M
            return submitted_base_compactions.contains(t->tablet_id()) ||
699
75.6M
                   submitted_full_compactions.contains(t->tablet_id()) ||
700
75.6M
                   submitted_index_change_base_compactions.contains(t->tablet_id()) ||
701
75.6M
                   t->tablet_state() != TABLET_RUNNING;
702
75.6M
        };
703
17.9k
    } else if (config::enable_parallel_cumu_compaction) {
704
0
        filter_out = [&tablet_preparing_cumu_compaction,
705
0
                      &submitted_index_change_cumu_compactions](CloudTablet* t) {
706
0
            return tablet_preparing_cumu_compaction.contains(t->tablet_id()) ||
707
0
                   submitted_index_change_cumu_compactions.contains(t->tablet_id()) ||
708
0
                   (t->tablet_state() != TABLET_RUNNING &&
709
0
                    (!config::enable_new_tablet_do_compaction || t->alter_version() == -1));
710
0
        };
711
17.9k
    } else {
712
17.9k
        filter_out = [&tablet_preparing_cumu_compaction, &submitted_cumu_compactions,
713
254M
                      &submitted_index_change_cumu_compactions](CloudTablet* t) {
714
254M
            return tablet_preparing_cumu_compaction.contains(t->tablet_id()) ||
715
254M
                   submitted_index_change_cumu_compactions.contains(t->tablet_id()) ||
716
254M
                   submitted_cumu_compactions.contains(t->tablet_id()) ||
717
254M
                   (t->tablet_state() != TABLET_RUNNING &&
718
254M
                    (!config::enable_new_tablet_do_compaction || t->alter_version() == -1));
719
254M
        };
720
17.9k
    }
721
722
    // Even if need_pick_tablet is false, we still need to call find_best_tablet_to_compaction(),
723
    // So that we can update the max_compaction_score metric.
724
19.9k
    do {
725
19.9k
        std::vector<CloudTabletSPtr> tablets;
726
19.9k
        auto st = tablet_mgr().get_topn_tablets_to_compact(n, compaction_type, filter_out, &tablets,
727
19.9k
                                                           &max_compaction_score);
728
19.9k
        if (!st.ok()) {
729
0
            LOG(WARNING) << "failed to get tablets to compact, err=" << st;
730
0
            break;
731
0
        }
732
19.9k
        if (!need_pick_tablet) break;
733
19.8k
        tablets_compaction = std::move(tablets);
734
19.8k
    } while (false);
735
736
19.9k
    if (max_compaction_score > 0) {
737
19.4k
        if (compaction_type == CompactionType::BASE_COMPACTION) {
738
1.95k
            DorisMetrics::instance()->tablet_base_max_compaction_score->set_value(
739
1.95k
                    max_compaction_score);
740
17.4k
        } else {
741
17.4k
            DorisMetrics::instance()->tablet_cumulative_max_compaction_score->set_value(
742
17.4k
                    max_compaction_score);
743
17.4k
        }
744
19.4k
    }
745
746
19.9k
    return tablets_compaction;
747
20.4k
}
748
749
Status CloudStorageEngine::_request_tablet_global_compaction_lock(
750
        ReaderType compaction_type, const CloudTabletSPtr& tablet,
751
6.97k
        std::shared_ptr<CloudCompactionMixin> compaction) {
752
6.97k
    long now = duration_cast<std::chrono::milliseconds>(
753
6.97k
                       std::chrono::system_clock::now().time_since_epoch())
754
6.97k
                       .count();
755
6.97k
    if (compaction_type == ReaderType::READER_CUMULATIVE_COMPACTION) {
756
6.81k
        auto cumu_compaction = static_pointer_cast<CloudCumulativeCompaction>(compaction);
757
6.81k
        if (auto st = cumu_compaction->request_global_lock(); !st.ok()) {
758
540
            LOG_WARNING("failed to request cumu compactoin global lock")
759
540
                    .tag("tablet id", tablet->tablet_id())
760
540
                    .tag("msg", st.to_string());
761
540
            tablet->set_last_cumu_compaction_failure_time(now);
762
540
            return st;
763
540
        }
764
6.27k
        {
765
6.27k
            std::lock_guard lock(_compaction_mtx);
766
6.27k
            _executing_cumu_compactions[tablet->tablet_id()].push_back(cumu_compaction);
767
6.27k
        }
768
6.27k
        return Status::OK();
769
6.81k
    } else if (compaction_type == ReaderType::READER_BASE_COMPACTION) {
770
55
        auto base_compaction = static_pointer_cast<CloudBaseCompaction>(compaction);
771
55
        if (auto st = base_compaction->request_global_lock(); !st.ok()) {
772
6
            LOG_WARNING("failed to request base compactoin global lock")
773
6
                    .tag("tablet id", tablet->tablet_id())
774
6
                    .tag("msg", st.to_string());
775
6
            tablet->set_last_base_compaction_failure_time(now);
776
6
            return st;
777
6
        }
778
49
        {
779
49
            std::lock_guard lock(_compaction_mtx);
780
49
            _executing_base_compactions[tablet->tablet_id()] = base_compaction;
781
49
        }
782
49
        return Status::OK();
783
105
    } else if (compaction_type == ReaderType::READER_FULL_COMPACTION) {
784
105
        auto full_compaction = static_pointer_cast<CloudFullCompaction>(compaction);
785
105
        if (auto st = full_compaction->request_global_lock(); !st.ok()) {
786
1
            LOG_WARNING("failed to request full compactoin global lock")
787
1
                    .tag("tablet id", tablet->tablet_id())
788
1
                    .tag("msg", st.to_string());
789
1
            tablet->set_last_full_compaction_failure_time(now);
790
1
            return st;
791
1
        }
792
104
        {
793
104
            std::lock_guard lock(_compaction_mtx);
794
104
            _executing_full_compactions[tablet->tablet_id()] = full_compaction;
795
104
        }
796
104
        return Status::OK();
797
105
    } else {
798
0
        LOG(WARNING) << "unsupport compaction task for tablet: " << tablet->tablet_id()
799
0
                     << ", compaction name: " << compaction->compaction_name();
800
0
        return Status::NotFound("Unsupport compaction type {}", compaction->compaction_name());
801
0
    }
802
6.97k
}
803
804
3.61k
Status CloudStorageEngine::_submit_base_compaction_task(const CloudTabletSPtr& tablet) {
805
3.61k
    using namespace std::chrono;
806
3.61k
    {
807
3.61k
        std::lock_guard lock(_compaction_mtx);
808
        // Take a placeholder for base compaction
809
3.61k
        auto [_, success] = _submitted_base_compactions.emplace(tablet->tablet_id(), nullptr);
810
3.61k
        if (!success) {
811
0
            return Status::AlreadyExist(
812
0
                    "other base compaction or full compaction is submitted, tablet_id={}",
813
0
                    tablet->tablet_id());
814
0
        }
815
3.61k
    }
816
3.61k
    auto compaction = std::make_shared<CloudBaseCompaction>(*this, tablet);
817
3.61k
    auto st = compaction->prepare_compact();
818
3.61k
    if (!st.ok()) {
819
3.56k
        long now = duration_cast<std::chrono::milliseconds>(
820
3.56k
                           std::chrono::system_clock::now().time_since_epoch())
821
3.56k
                           .count();
822
3.56k
        tablet->set_last_base_compaction_failure_time(now);
823
3.56k
        std::lock_guard lock(_compaction_mtx);
824
3.56k
        _submitted_base_compactions.erase(tablet->tablet_id());
825
3.56k
        return st;
826
3.56k
    }
827
55
    {
828
55
        std::lock_guard lock(_compaction_mtx);
829
55
        _submitted_base_compactions[tablet->tablet_id()] = compaction;
830
55
    }
831
55
    st = _base_compaction_thread_pool->submit_func([=, this, compaction = std::move(compaction)]() {
832
55
        DorisMetrics::instance()->base_compaction_task_running_total->increment(1);
833
55
        DorisMetrics::instance()->base_compaction_task_pending_total->set_value(
834
55
                _base_compaction_thread_pool->get_queue_size());
835
55
        g_base_compaction_running_task_count << 1;
836
55
        signal::tablet_id = tablet->tablet_id();
837
55
        Defer defer {[&]() {
838
55
            g_base_compaction_running_task_count << -1;
839
55
            std::lock_guard lock(_compaction_mtx);
840
55
            _submitted_base_compactions.erase(tablet->tablet_id());
841
55
            DorisMetrics::instance()->base_compaction_task_running_total->increment(-1);
842
55
            DorisMetrics::instance()->base_compaction_task_pending_total->set_value(
843
55
                    _base_compaction_thread_pool->get_queue_size());
844
55
        }};
845
55
        auto st = _request_tablet_global_compaction_lock(ReaderType::READER_BASE_COMPACTION, tablet,
846
55
                                                         compaction);
847
55
        if (!st.ok()) return;
848
49
        st = compaction->execute_compact();
849
49
        if (!st.ok()) {
850
            // Error log has been output in `execute_compact`
851
0
            long now = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
852
0
            tablet->set_last_base_compaction_failure_time(now);
853
0
        }
854
49
        std::lock_guard lock(_compaction_mtx);
855
49
        _executing_base_compactions.erase(tablet->tablet_id());
856
49
    });
857
55
    DorisMetrics::instance()->base_compaction_task_pending_total->set_value(
858
55
            _base_compaction_thread_pool->get_queue_size());
859
55
    if (!st.ok()) {
860
0
        std::lock_guard lock(_compaction_mtx);
861
0
        _submitted_base_compactions.erase(tablet->tablet_id());
862
0
        return Status::InternalError("failed to submit base compaction, tablet_id={}",
863
0
                                     tablet->tablet_id());
864
0
    }
865
55
    return st;
866
55
}
867
868
117k
Status CloudStorageEngine::_submit_cumulative_compaction_task(const CloudTabletSPtr& tablet) {
869
117k
    using namespace std::chrono;
870
117k
    {
871
117k
        std::lock_guard lock(_compaction_mtx);
872
117k
        if (!config::enable_parallel_cumu_compaction &&
873
117k
            _submitted_cumu_compactions.count(tablet->tablet_id())) {
874
2
            return Status::AlreadyExist("other cumu compaction is submitted, tablet_id={}",
875
2
                                        tablet->tablet_id());
876
2
        }
877
117k
        auto [_, success] = _tablet_preparing_cumu_compaction.insert(tablet->tablet_id());
878
117k
        if (!success) {
879
0
            return Status::AlreadyExist("other cumu compaction is preparing, tablet_id={}",
880
0
                                        tablet->tablet_id());
881
0
        }
882
117k
    }
883
117k
    auto compaction = std::make_shared<CloudCumulativeCompaction>(*this, tablet);
884
117k
    auto st = compaction->prepare_compact();
885
117k
    if (!st.ok()) {
886
110k
        long now = duration_cast<std::chrono::milliseconds>(
887
110k
                           std::chrono::system_clock::now().time_since_epoch())
888
110k
                           .count();
889
110k
        if (!st.is<ErrorCode::CUMULATIVE_MEET_DELETE_VERSION>()) {
890
110k
            if (st.is<ErrorCode::CUMULATIVE_NO_SUITABLE_VERSION>()) {
891
                // Backoff strategy if no suitable version
892
110k
                tablet->last_cumu_no_suitable_version_ms = now;
893
110k
            } else {
894
0
                tablet->set_last_cumu_compaction_failure_time(now);
895
0
            }
896
110k
        }
897
110k
        std::lock_guard lock(_compaction_mtx);
898
110k
        _tablet_preparing_cumu_compaction.erase(tablet->tablet_id());
899
110k
        return st;
900
110k
    }
901
6.81k
    {
902
6.81k
        std::lock_guard lock(_compaction_mtx);
903
6.81k
        _tablet_preparing_cumu_compaction.erase(tablet->tablet_id());
904
6.81k
        _submitted_cumu_compactions[tablet->tablet_id()].push_back(compaction);
905
6.81k
    }
906
6.81k
    auto erase_submitted_cumu_compaction = [=, this]() {
907
6.81k
        std::lock_guard lock(_compaction_mtx);
908
6.81k
        auto it = _submitted_cumu_compactions.find(tablet->tablet_id());
909
6.81k
        DCHECK(it != _submitted_cumu_compactions.end());
910
6.81k
        auto& compactions = it->second;
911
6.81k
        auto it1 = std::find(compactions.begin(), compactions.end(), compaction);
912
6.81k
        DCHECK(it1 != compactions.end());
913
6.81k
        compactions.erase(it1);
914
6.81k
        if (compactions.empty()) { // No compactions on this tablet, erase key
915
6.81k
            _submitted_cumu_compactions.erase(it);
916
            // No cumu compaction on this tablet, reset `last_cumu_no_suitable_version_ms` to enable this tablet to
917
            // enter the compaction scheduling candidate set. The purpose of doing this is to have at least one BE perform
918
            // cumu compaction on tablet which has suitable versions for cumu compaction.
919
6.81k
            tablet->last_cumu_no_suitable_version_ms = 0;
920
6.81k
        }
921
6.81k
    };
922
6.81k
    auto erase_executing_cumu_compaction = [=, this]() {
923
6.26k
        std::lock_guard lock(_compaction_mtx);
924
6.26k
        auto it = _executing_cumu_compactions.find(tablet->tablet_id());
925
6.26k
        DCHECK(it != _executing_cumu_compactions.end());
926
6.26k
        auto& compactions = it->second;
927
6.26k
        auto it1 = std::find(compactions.begin(), compactions.end(), compaction);
928
6.26k
        DCHECK(it1 != compactions.end());
929
6.26k
        compactions.erase(it1);
930
6.27k
        if (compactions.empty()) { // No compactions on this tablet, erase key
931
6.27k
            _executing_cumu_compactions.erase(it);
932
            // No cumu compaction on this tablet, reset `last_cumu_no_suitable_version_ms` to enable this tablet to
933
            // enter the compaction scheduling candidate set. The purpose of doing this is to have at least one BE perform
934
            // cumu compaction on tablet which has suitable versions for cumu compaction.
935
6.27k
            tablet->last_cumu_no_suitable_version_ms = 0;
936
6.27k
        }
937
6.26k
    };
938
6.81k
    st = _cumu_compaction_thread_pool->submit_func([=, this, compaction = std::move(compaction)]() {
939
6.81k
        DorisMetrics::instance()->cumulative_compaction_task_running_total->increment(1);
940
6.81k
        DorisMetrics::instance()->cumulative_compaction_task_pending_total->set_value(
941
6.81k
                _cumu_compaction_thread_pool->get_queue_size());
942
6.81k
        DBUG_EXECUTE_IF("CloudStorageEngine._submit_cumulative_compaction_task.wait_in_line",
943
6.81k
                        { sleep(5); })
944
6.81k
        signal::tablet_id = tablet->tablet_id();
945
6.81k
        g_cumu_compaction_running_task_count << 1;
946
6.81k
        bool is_large_task = true;
947
6.81k
        Defer defer {[&]() {
948
6.81k
            DBUG_EXECUTE_IF("CloudStorageEngine._submit_cumulative_compaction_task.sleep",
949
6.81k
                            { sleep(5); })
950
6.81k
            std::lock_guard lock(_cumu_compaction_delay_mtx);
951
6.81k
            _cumu_compaction_thread_pool_used_threads--;
952
6.81k
            if (!is_large_task) {
953
6.27k
                _cumu_compaction_thread_pool_small_tasks_running--;
954
6.27k
            }
955
6.81k
            g_cumu_compaction_running_task_count << -1;
956
6.81k
            erase_submitted_cumu_compaction();
957
6.81k
            DorisMetrics::instance()->cumulative_compaction_task_running_total->increment(-1);
958
6.81k
            DorisMetrics::instance()->cumulative_compaction_task_pending_total->set_value(
959
6.81k
                    _cumu_compaction_thread_pool->get_queue_size());
960
6.81k
        }};
961
6.81k
        auto st = _request_tablet_global_compaction_lock(ReaderType::READER_CUMULATIVE_COMPACTION,
962
6.81k
                                                         tablet, compaction);
963
6.81k
        if (!st.ok()) return;
964
6.27k
        do {
965
6.27k
            std::lock_guard lock(_cumu_compaction_delay_mtx);
966
6.27k
            _cumu_compaction_thread_pool_used_threads++;
967
6.27k
            if (config::large_cumu_compaction_task_min_thread_num > 1 &&
968
6.27k
                _cumu_compaction_thread_pool->max_threads() >=
969
6.27k
                        config::large_cumu_compaction_task_min_thread_num) {
970
                // Determine if this is a small task based on configured thresholds
971
6.27k
                is_large_task = (compaction->get_input_rowsets_bytes() >
972
6.27k
                                         config::large_cumu_compaction_task_bytes_threshold ||
973
6.27k
                                 compaction->get_input_num_rows() >
974
6.27k
                                         config::large_cumu_compaction_task_row_num_threshold);
975
                // Small task. No delay needed
976
6.27k
                if (!is_large_task) {
977
6.27k
                    _cumu_compaction_thread_pool_small_tasks_running++;
978
6.27k
                    break;
979
6.27k
                }
980
                // Deal with large task
981
0
                if (_should_delay_large_task()) {
982
0
                    long now = duration_cast<milliseconds>(system_clock::now().time_since_epoch())
983
0
                                       .count();
984
                    // sleep 5s for this tablet
985
0
                    tablet->set_last_cumu_compaction_failure_time(now);
986
0
                    erase_executing_cumu_compaction();
987
0
                    LOG_WARNING(
988
0
                            "failed to do CloudCumulativeCompaction, cumu thread pool is "
989
0
                            "intensive, delay large task.")
990
0
                            .tag("tablet_id", tablet->tablet_id())
991
0
                            .tag("input_rows", compaction->get_input_num_rows())
992
0
                            .tag("input_rowsets_total_size", compaction->get_input_rowsets_bytes())
993
0
                            .tag("config::large_cumu_compaction_task_bytes_threshold",
994
0
                                 config::large_cumu_compaction_task_bytes_threshold)
995
0
                            .tag("config::large_cumu_compaction_task_row_num_threshold",
996
0
                                 config::large_cumu_compaction_task_row_num_threshold)
997
0
                            .tag("remaining threads", _cumu_compaction_thread_pool_used_threads)
998
0
                            .tag("small_tasks_running",
999
0
                                 _cumu_compaction_thread_pool_small_tasks_running);
1000
0
                    return;
1001
0
                }
1002
0
            }
1003
6.27k
        } while (false);
1004
6.27k
        st = compaction->execute_compact();
1005
6.27k
        if (!st.ok()) {
1006
            // Error log has been output in `execute_compact`
1007
52
            long now = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
1008
52
            tablet->set_last_cumu_compaction_failure_time(now);
1009
52
        }
1010
6.27k
        erase_executing_cumu_compaction();
1011
6.27k
    });
1012
6.81k
    DorisMetrics::instance()->cumulative_compaction_task_pending_total->set_value(
1013
6.81k
            _cumu_compaction_thread_pool->get_queue_size());
1014
6.81k
    if (!st.ok()) {
1015
0
        erase_submitted_cumu_compaction();
1016
0
        return Status::InternalError("failed to submit cumu compaction, tablet_id={}",
1017
0
                                     tablet->tablet_id());
1018
0
    }
1019
6.81k
    return st;
1020
6.81k
}
1021
1022
105
Status CloudStorageEngine::_submit_full_compaction_task(const CloudTabletSPtr& tablet) {
1023
105
    using namespace std::chrono;
1024
105
    {
1025
105
        std::lock_guard lock(_compaction_mtx);
1026
        // Take a placeholder for full compaction
1027
105
        auto [_, success] = _submitted_full_compactions.emplace(tablet->tablet_id(), nullptr);
1028
105
        if (!success) {
1029
0
            return Status::AlreadyExist(
1030
0
                    "other full compaction or base compaction is submitted, tablet_id={}",
1031
0
                    tablet->tablet_id());
1032
0
        }
1033
105
    }
1034
    //auto compaction = std::make_shared<CloudFullCompaction>(tablet);
1035
105
    auto compaction = std::make_shared<CloudFullCompaction>(*this, tablet);
1036
105
    auto st = compaction->prepare_compact();
1037
105
    if (!st.ok()) {
1038
0
        long now = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
1039
0
        tablet->set_last_full_compaction_failure_time(now);
1040
0
        std::lock_guard lock(_compaction_mtx);
1041
0
        _submitted_full_compactions.erase(tablet->tablet_id());
1042
0
        return st;
1043
0
    }
1044
105
    {
1045
105
        std::lock_guard lock(_compaction_mtx);
1046
105
        _submitted_full_compactions[tablet->tablet_id()] = compaction;
1047
105
    }
1048
105
    st = _base_compaction_thread_pool->submit_func([=, this, compaction = std::move(compaction)]() {
1049
105
        g_full_compaction_running_task_count << 1;
1050
105
        signal::tablet_id = tablet->tablet_id();
1051
105
        Defer defer {[&]() {
1052
105
            g_full_compaction_running_task_count << -1;
1053
105
            std::lock_guard lock(_compaction_mtx);
1054
105
            _submitted_full_compactions.erase(tablet->tablet_id());
1055
105
        }};
1056
105
        auto st = _request_tablet_global_compaction_lock(ReaderType::READER_FULL_COMPACTION, tablet,
1057
105
                                                         compaction);
1058
105
        if (!st.ok()) return;
1059
104
        st = compaction->execute_compact();
1060
104
        if (!st.ok()) {
1061
            // Error log has been output in `execute_compact`
1062
0
            long now = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
1063
0
            tablet->set_last_full_compaction_failure_time(now);
1064
0
        }
1065
104
        std::lock_guard lock(_compaction_mtx);
1066
104
        _executing_full_compactions.erase(tablet->tablet_id());
1067
104
    });
1068
105
    if (!st.ok()) {
1069
0
        std::lock_guard lock(_compaction_mtx);
1070
0
        _submitted_full_compactions.erase(tablet->tablet_id());
1071
0
        return Status::InternalError("failed to submit full compaction, tablet_id={}",
1072
0
                                     tablet->tablet_id());
1073
0
    }
1074
105
    return st;
1075
105
}
1076
1077
Status CloudStorageEngine::submit_compaction_task(const CloudTabletSPtr& tablet,
1078
121k
                                                  CompactionType compaction_type) {
1079
121k
    DCHECK(compaction_type == CompactionType::CUMULATIVE_COMPACTION ||
1080
121k
           compaction_type == CompactionType::BASE_COMPACTION ||
1081
121k
           compaction_type == CompactionType::FULL_COMPACTION);
1082
121k
    switch (compaction_type) {
1083
3.61k
    case CompactionType::BASE_COMPACTION:
1084
3.61k
        RETURN_IF_ERROR(_submit_base_compaction_task(tablet));
1085
55
        return Status::OK();
1086
117k
    case CompactionType::CUMULATIVE_COMPACTION:
1087
117k
        RETURN_IF_ERROR(_submit_cumulative_compaction_task(tablet));
1088
6.81k
        return Status::OK();
1089
105
    case CompactionType::FULL_COMPACTION:
1090
105
        RETURN_IF_ERROR(_submit_full_compaction_task(tablet));
1091
105
        return Status::OK();
1092
0
    default:
1093
0
        return Status::InternalError("unknown compaction type!");
1094
121k
    }
1095
121k
}
1096
1097
1
void CloudStorageEngine::_lease_compaction_thread_callback() {
1098
196
    while (!_stop_background_threads_latch.wait_for(
1099
196
            std::chrono::seconds(config::lease_compaction_interval_seconds))) {
1100
195
        std::vector<std::shared_ptr<CloudFullCompaction>> full_compactions;
1101
195
        std::vector<std::shared_ptr<CloudBaseCompaction>> base_compactions;
1102
195
        std::vector<std::shared_ptr<CloudCumulativeCompaction>> cumu_compactions;
1103
195
        std::vector<std::shared_ptr<CloudCompactionStopToken>> compation_stop_tokens;
1104
195
        std::vector<std::shared_ptr<CloudIndexChangeCompaction>> index_change_compations;
1105
195
        {
1106
195
            std::lock_guard lock(_compaction_mtx);
1107
195
            for (auto& [_, base] : _executing_base_compactions) {
1108
1
                if (base) { // `base` might be a nullptr placeholder
1109
1
                    base_compactions.push_back(base);
1110
1
                }
1111
1
            }
1112
195
            for (auto& [_, cumus] : _executing_cumu_compactions) {
1113
181
                for (auto& cumu : cumus) {
1114
181
                    cumu_compactions.push_back(cumu);
1115
181
                }
1116
181
            }
1117
195
            for (auto& [_, full] : _executing_full_compactions) {
1118
3
                if (full) {
1119
3
                    full_compactions.push_back(full);
1120
3
                }
1121
3
            }
1122
195
            for (auto& [_, stop_token] : _active_compaction_stop_tokens) {
1123
6
                if (stop_token) {
1124
6
                    compation_stop_tokens.push_back(stop_token);
1125
6
                }
1126
6
            }
1127
195
            for (auto& [_, index_change] : _submitted_index_change_cumu_compaction) {
1128
0
                if (index_change) {
1129
0
                    index_change_compations.push_back(index_change);
1130
0
                }
1131
0
            }
1132
195
            for (auto& [_, index_change] : _submitted_index_change_base_compaction) {
1133
0
                if (index_change) {
1134
0
                    index_change_compations.push_back(index_change);
1135
0
                }
1136
0
            }
1137
195
        }
1138
        // TODO(plat1ko): Support batch lease rpc
1139
195
        for (auto& stop_token : compation_stop_tokens) {
1140
6
            stop_token->do_lease();
1141
6
        }
1142
195
        for (auto& comp : full_compactions) {
1143
3
            comp->do_lease();
1144
3
        }
1145
195
        for (auto& comp : cumu_compactions) {
1146
181
            comp->do_lease();
1147
181
        }
1148
195
        for (auto& comp : base_compactions) {
1149
1
            comp->do_lease();
1150
1
        }
1151
195
        for (auto& comp : index_change_compations) {
1152
0
            comp->do_lease();
1153
0
        }
1154
195
    }
1155
1
}
1156
1157
1
void CloudStorageEngine::_check_tablet_delete_bitmap_score_callback() {
1158
1
    LOG(INFO) << "try to start check tablet delete bitmap score!";
1159
14
    while (!_stop_background_threads_latch.wait_for(
1160
14
            std::chrono::seconds(config::check_tablet_delete_bitmap_interval_seconds))) {
1161
13
        if (!config::enable_check_tablet_delete_bitmap_score) {
1162
0
            return;
1163
0
        }
1164
13
        uint64_t max_delete_bitmap_score = 0;
1165
13
        uint64_t max_base_rowset_delete_bitmap_score = 0;
1166
13
        tablet_mgr().get_topn_tablet_delete_bitmap_score(&max_delete_bitmap_score,
1167
13
                                                         &max_base_rowset_delete_bitmap_score);
1168
13
        if (max_delete_bitmap_score > 0) {
1169
13
            _tablet_max_delete_bitmap_score_metrics->set_value(max_delete_bitmap_score);
1170
13
        }
1171
13
        if (max_base_rowset_delete_bitmap_score > 0) {
1172
12
            _tablet_max_base_rowset_delete_bitmap_score_metrics->set_value(
1173
12
                    max_base_rowset_delete_bitmap_score);
1174
12
        }
1175
13
    }
1176
1
}
1177
1178
0
Status CloudStorageEngine::get_compaction_status_json(std::string* result) {
1179
0
    rapidjson::Document root;
1180
0
    root.SetObject();
1181
1182
0
    std::lock_guard lock(_compaction_mtx);
1183
    // cumu
1184
0
    std::string_view cumu = "CumulativeCompaction";
1185
0
    rapidjson::Value cumu_key;
1186
0
    cumu_key.SetString(cumu.data(), cast_set<uint32_t>(cumu.length()), root.GetAllocator());
1187
0
    rapidjson::Document cumu_arr;
1188
0
    cumu_arr.SetArray();
1189
0
    for (auto& [tablet_id, v] : _submitted_cumu_compactions) {
1190
0
        for (int i = 0; i < v.size(); ++i) {
1191
0
            cumu_arr.PushBack(tablet_id, root.GetAllocator());
1192
0
        }
1193
0
    }
1194
0
    root.AddMember(cumu_key, cumu_arr, root.GetAllocator());
1195
    // base
1196
0
    std::string_view base = "BaseCompaction";
1197
0
    rapidjson::Value base_key;
1198
0
    base_key.SetString(base.data(), cast_set<uint32_t>(base.length()), root.GetAllocator());
1199
0
    rapidjson::Document base_arr;
1200
0
    base_arr.SetArray();
1201
0
    for (auto& [tablet_id, _] : _submitted_base_compactions) {
1202
0
        base_arr.PushBack(tablet_id, root.GetAllocator());
1203
0
    }
1204
0
    root.AddMember(base_key, base_arr, root.GetAllocator());
1205
1206
0
    rapidjson::StringBuffer strbuf;
1207
0
    rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(strbuf);
1208
0
    root.Accept(writer);
1209
0
    *result = std::string(strbuf.GetString());
1210
0
    return Status::OK();
1211
0
}
1212
1213
std::shared_ptr<CloudCumulativeCompactionPolicy> CloudStorageEngine::cumu_compaction_policy(
1214
130k
        std::string_view compaction_policy) {
1215
130k
    if (!_cumulative_compaction_policies.contains(compaction_policy)) {
1216
0
        return _cumulative_compaction_policies.at(CUMULATIVE_SIZE_BASED_POLICY);
1217
0
    }
1218
130k
    return _cumulative_compaction_policies.at(compaction_policy);
1219
130k
}
1220
1221
Status CloudStorageEngine::register_compaction_stop_token(CloudTabletSPtr tablet,
1222
1.21k
                                                          int64_t initiator) {
1223
1.21k
    {
1224
1.21k
        std::lock_guard lock(_compaction_mtx);
1225
1.21k
        auto [_, success] = _active_compaction_stop_tokens.emplace(tablet->tablet_id(), nullptr);
1226
1.21k
        if (!success) {
1227
0
            return Status::AlreadyExist("stop token already exists for tablet_id={}",
1228
0
                                        tablet->tablet_id());
1229
0
        }
1230
1.21k
    }
1231
1232
1.21k
    auto stop_token = std::make_shared<CloudCompactionStopToken>(*this, tablet, initiator);
1233
1.21k
    auto st = stop_token->do_register();
1234
1235
1.21k
    if (!st.ok()) {
1236
0
        std::lock_guard lock(_compaction_mtx);
1237
0
        _active_compaction_stop_tokens.erase(tablet->tablet_id());
1238
0
        return st;
1239
0
    }
1240
1241
1.21k
    {
1242
1.21k
        std::lock_guard lock(_compaction_mtx);
1243
1.21k
        _active_compaction_stop_tokens[tablet->tablet_id()] = stop_token;
1244
1.21k
    }
1245
1.21k
    LOG_INFO(
1246
1.21k
            "successfully register compaction stop token for tablet_id={}, "
1247
1.21k
            "delete_bitmap_lock_initiator={}",
1248
1.21k
            tablet->tablet_id(), initiator);
1249
1.21k
    return st;
1250
1.21k
}
1251
1252
1.21k
Status CloudStorageEngine::unregister_compaction_stop_token(CloudTabletSPtr tablet, bool clear_ms) {
1253
1.21k
    std::shared_ptr<CloudCompactionStopToken> stop_token;
1254
1.21k
    {
1255
1.21k
        std::lock_guard lock(_compaction_mtx);
1256
1.21k
        if (auto it = _active_compaction_stop_tokens.find(tablet->tablet_id());
1257
1.21k
            it != _active_compaction_stop_tokens.end()) {
1258
1.21k
            stop_token = it->second;
1259
1.21k
        } else {
1260
0
            return Status::NotFound("stop token not found for tablet_id={}", tablet->tablet_id());
1261
0
        }
1262
1.21k
        _active_compaction_stop_tokens.erase(tablet->tablet_id());
1263
1.21k
    }
1264
1.21k
    LOG_INFO("successfully unregister compaction stop token for tablet_id={}", tablet->tablet_id());
1265
1.21k
    if (stop_token && clear_ms) {
1266
1
        RETURN_IF_ERROR(stop_token->do_unregister());
1267
1
        LOG_INFO(
1268
1
                "successfully remove compaction stop token from MS for tablet_id={}, "
1269
1
                "delete_bitmap_lock_initiator={}",
1270
1
                tablet->tablet_id(), stop_token->initiator());
1271
1
    }
1272
1.21k
    return Status::OK();
1273
1.21k
}
1274
1275
1
Status CloudStorageEngine::_check_all_root_path_cluster_id() {
1276
    // Check if all root paths have the same cluster id
1277
1
    std::set<int32_t> cluster_ids;
1278
1
    for (const auto& path : _options.store_paths) {
1279
1
        auto cluster_id_path = fmt::format("{}/{}", path.path, CLUSTER_ID_PREFIX);
1280
1
        bool exists = false;
1281
1
        RETURN_IF_ERROR(io::global_local_filesystem()->exists(cluster_id_path, &exists));
1282
1
        if (exists) {
1283
0
            io::FileReaderSPtr reader;
1284
0
            RETURN_IF_ERROR(io::global_local_filesystem()->open_file(cluster_id_path, &reader));
1285
0
            size_t fsize = reader->size();
1286
0
            if (fsize > 0) {
1287
0
                std::string content;
1288
0
                content.resize(fsize, '\0');
1289
0
                size_t bytes_read = 0;
1290
0
                RETURN_IF_ERROR(reader->read_at(0, {content.data(), fsize}, &bytes_read));
1291
0
                DCHECK_EQ(fsize, bytes_read);
1292
0
                int32_t tmp_cluster_id = std::stoi(content);
1293
0
                cluster_ids.insert(tmp_cluster_id);
1294
0
            }
1295
0
        }
1296
1
    }
1297
1
    _effective_cluster_id = config::cluster_id;
1298
    // first init
1299
1
    if (cluster_ids.empty()) {
1300
        // not set configured cluster id
1301
1
        if (_effective_cluster_id == -1) {
1302
1
            return Status::OK();
1303
1
        } else {
1304
            // If no cluster id file exists, use the configured cluster id
1305
0
            return set_cluster_id(_effective_cluster_id);
1306
0
        }
1307
1
    }
1308
0
    if (cluster_ids.size() > 1) {
1309
0
        return Status::InternalError(
1310
0
                "All root paths must have the same cluster id, but you have "
1311
0
                "different cluster ids: {}",
1312
0
                fmt::join(cluster_ids, ", "));
1313
0
    }
1314
0
    if (_effective_cluster_id != -1 && !cluster_ids.empty() &&
1315
0
        *cluster_ids.begin() != _effective_cluster_id) {
1316
0
        return Status::Corruption(
1317
0
                "multiple cluster ids is not equal. config::cluster_id={}, "
1318
0
                "storage path cluster_id={}",
1319
0
                _effective_cluster_id, *cluster_ids.begin());
1320
0
    }
1321
0
    return Status::OK();
1322
0
}
1323
1324
1
Status CloudStorageEngine::set_cluster_id(int32_t cluster_id) {
1325
1
    std::lock_guard<std::mutex> l(_store_lock);
1326
1
    for (auto& path : _options.store_paths) {
1327
1
        auto cluster_id_path = fmt::format("{}/{}", path.path, CLUSTER_ID_PREFIX);
1328
1
        bool exists = false;
1329
1
        RETURN_IF_ERROR(io::global_local_filesystem()->exists(cluster_id_path, &exists));
1330
1
        if (!exists) {
1331
1
            io::FileWriterPtr file_writer;
1332
1
            RETURN_IF_ERROR(
1333
1
                    io::global_local_filesystem()->create_file(cluster_id_path, &file_writer));
1334
1
            RETURN_IF_ERROR(file_writer->append(std::to_string(cluster_id)));
1335
1
            RETURN_IF_ERROR(file_writer->close());
1336
1
        }
1337
1
    }
1338
1
    _effective_cluster_id = cluster_id;
1339
1
    return Status::OK();
1340
1
}
1341
1342
#include "common/compile_check_end.h"
1343
} // namespace doris