Coverage Report

Created: 2026-07-13 02:26

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