Coverage Report

Created: 2026-08-14 11:09

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