Coverage Report

Created: 2026-04-01 12:04

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