Coverage Report

Created: 2026-07-17 03:22

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