Coverage Report

Created: 2026-06-12 08:05

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