Coverage Report

Created: 2025-04-28 13:59

/root/doris/be/src/olap/olap_server.cpp
Line
Count
Source (jump to first uncovered line)
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 <gen_cpp/Types_types.h>
19
#include <gen_cpp/olap_file.pb.h>
20
#include <glog/logging.h>
21
#include <rapidjson/prettywriter.h>
22
#include <rapidjson/stringbuffer.h>
23
#include <stdint.h>
24
#include <sys/types.h>
25
26
#include <algorithm>
27
#include <atomic>
28
// IWYU pragma: no_include <bits/chrono.h>
29
#include <chrono> // IWYU pragma: keep
30
#include <cmath>
31
#include <condition_variable>
32
#include <cstdint>
33
#include <ctime>
34
#include <functional>
35
#include <map>
36
#include <memory>
37
#include <mutex>
38
#include <ostream>
39
#include <random>
40
#include <shared_mutex>
41
#include <string>
42
#include <thread>
43
#include <unordered_set>
44
#include <utility>
45
#include <vector>
46
47
#include "agent/utils.h"
48
#include "common/config.h"
49
#include "common/logging.h"
50
#include "common/status.h"
51
#include "cpp/sync_point.h"
52
#include "gen_cpp/FrontendService.h"
53
#include "gen_cpp/internal_service.pb.h"
54
#include "gutil/ref_counted.h"
55
#include "io/fs/file_writer.h" // IWYU pragma: keep
56
#include "io/fs/path.h"
57
#include "olap/base_tablet.h"
58
#include "olap/cold_data_compaction.h"
59
#include "olap/compaction_permit_limiter.h"
60
#include "olap/cumulative_compaction.h"
61
#include "olap/cumulative_compaction_policy.h"
62
#include "olap/cumulative_compaction_time_series_policy.h"
63
#include "olap/data_dir.h"
64
#include "olap/olap_common.h"
65
#include "olap/olap_define.h"
66
#include "olap/rowset/segcompaction.h"
67
#include "olap/schema_change.h"
68
#include "olap/single_replica_compaction.h"
69
#include "olap/storage_engine.h"
70
#include "olap/storage_policy.h"
71
#include "olap/tablet.h"
72
#include "olap/tablet_manager.h"
73
#include "olap/tablet_meta.h"
74
#include "olap/tablet_meta_manager.h"
75
#include "olap/tablet_schema.h"
76
#include "olap/task/engine_publish_version_task.h"
77
#include "olap/task/index_builder.h"
78
#include "runtime/client_cache.h"
79
#include "runtime/memory/cache_manager.h"
80
#include "runtime/memory/global_memory_arbitrator.h"
81
#include "util/countdown_latch.h"
82
#include "util/debug_points.h"
83
#include "util/doris_metrics.h"
84
#include "util/mem_info.h"
85
#include "util/thread.h"
86
#include "util/threadpool.h"
87
#include "util/thrift_rpc_helper.h"
88
#include "util/time.h"
89
#include "util/uid_util.h"
90
#include "util/work_thread_pool.hpp"
91
92
using std::string;
93
94
namespace doris {
95
96
using io::Path;
97
98
// number of running SCHEMA-CHANGE threads
99
volatile uint32_t g_schema_change_active_threads = 0;
100
101
static const uint64_t DEFAULT_SEED = 104729;
102
static const uint64_t MOD_PRIME = 7652413;
103
104
0
CompactionSubmitRegistry::CompactionSubmitRegistry(CompactionSubmitRegistry&& r) {
105
0
    std::swap(_tablet_submitted_cumu_compaction, r._tablet_submitted_cumu_compaction);
106
0
    std::swap(_tablet_submitted_base_compaction, r._tablet_submitted_base_compaction);
107
0
    std::swap(_tablet_submitted_full_compaction, r._tablet_submitted_full_compaction);
108
0
}
109
110
0
CompactionSubmitRegistry CompactionSubmitRegistry::create_snapshot() {
111
    // full compaction is not engaged in this method
112
0
    std::unique_lock<std::mutex> l(_tablet_submitted_compaction_mutex);
113
0
    CompactionSubmitRegistry registry;
114
0
    registry._tablet_submitted_base_compaction = _tablet_submitted_base_compaction;
115
0
    registry._tablet_submitted_cumu_compaction = _tablet_submitted_cumu_compaction;
116
0
    return registry;
117
0
}
118
119
0
void CompactionSubmitRegistry::reset(const std::vector<DataDir*>& stores) {
120
    // full compaction is not engaged in this method
121
0
    for (const auto& store : stores) {
122
0
        _tablet_submitted_cumu_compaction[store] = {};
123
0
        _tablet_submitted_base_compaction[store] = {};
124
0
    }
125
0
}
126
127
uint32_t CompactionSubmitRegistry::count_executing_compaction(DataDir* dir,
128
2
                                                              CompactionType compaction_type) {
129
    // non-lock, used in snapshot
130
2
    const auto& compaction_tasks = _get_tablet_set(dir, compaction_type);
131
10
    return std::count_if(compaction_tasks.begin(), compaction_tasks.end(), [](const auto& task) {
132
10
        return task->compaction_stage == CompactionStage::EXECUTING;
133
10
    });
134
2
}
135
136
1
uint32_t CompactionSubmitRegistry::count_executing_cumu_and_base(DataDir* dir) {
137
    // non-lock, used in snapshot
138
1
    return count_executing_compaction(dir, CompactionType::BASE_COMPACTION) +
139
1
           count_executing_compaction(dir, CompactionType::CUMULATIVE_COMPACTION);
140
1
}
141
142
0
bool CompactionSubmitRegistry::has_compaction_task(DataDir* dir, CompactionType compaction_type) {
143
    // non-lock, used in snapshot
144
0
    return !_get_tablet_set(dir, compaction_type).empty();
145
0
}
146
147
std::vector<TabletSharedPtr> CompactionSubmitRegistry::pick_topn_tablets_for_compaction(
148
        TabletManager* tablet_mgr, DataDir* data_dir, CompactionType compaction_type,
149
0
        const CumuCompactionPolicyTable& cumu_compaction_policies, uint32_t* disk_max_score) {
150
    // non-lock, used in snapshot
151
0
    return tablet_mgr->find_best_tablets_to_compaction(compaction_type, data_dir,
152
0
                                                       _get_tablet_set(data_dir, compaction_type),
153
0
                                                       disk_max_score, cumu_compaction_policies);
154
0
}
155
156
10
bool CompactionSubmitRegistry::insert(TabletSharedPtr tablet, CompactionType compaction_type) {
157
10
    std::unique_lock<std::mutex> l(_tablet_submitted_compaction_mutex);
158
10
    auto& tablet_set = _get_tablet_set(tablet->data_dir(), compaction_type);
159
10
    bool already_exist = !(tablet_set.insert(tablet).second);
160
10
    return already_exist;
161
10
}
162
163
void CompactionSubmitRegistry::remove(TabletSharedPtr tablet, CompactionType compaction_type,
164
2
                                      std::function<void()> wakeup_cb) {
165
2
    std::unique_lock<std::mutex> l(_tablet_submitted_compaction_mutex);
166
2
    auto& tablet_set = _get_tablet_set(tablet->data_dir(), compaction_type);
167
2
    size_t removed = tablet_set.erase(tablet);
168
2
    if (removed == 1) {
169
2
        wakeup_cb();
170
2
    }
171
2
}
172
173
CompactionSubmitRegistry::TabletSet& CompactionSubmitRegistry::_get_tablet_set(
174
14
        DataDir* dir, CompactionType compaction_type) {
175
14
    switch (compaction_type) {
176
1
    case CompactionType::BASE_COMPACTION:
177
1
        return _tablet_submitted_base_compaction[dir];
178
13
    case CompactionType::CUMULATIVE_COMPACTION:
179
13
        return _tablet_submitted_cumu_compaction[dir];
180
0
    case CompactionType::FULL_COMPACTION:
181
0
        return _tablet_submitted_full_compaction[dir];
182
0
    default:
183
0
        CHECK(false) << "invalid compaction type";
184
14
    }
185
14
}
186
187
0
static int32_t get_cumu_compaction_threads_num(size_t data_dirs_num) {
188
0
    int32_t threads_num = config::max_cumu_compaction_threads;
189
0
    if (threads_num == -1) {
190
0
        threads_num = data_dirs_num;
191
0
    }
192
0
    threads_num = threads_num <= 0 ? 1 : threads_num;
193
0
    return threads_num;
194
0
}
195
196
0
static int32_t get_base_compaction_threads_num(size_t data_dirs_num) {
197
0
    int32_t threads_num = config::max_base_compaction_threads;
198
0
    if (threads_num == -1) {
199
0
        threads_num = data_dirs_num;
200
0
    }
201
0
    threads_num = threads_num <= 0 ? 1 : threads_num;
202
0
    return threads_num;
203
0
}
204
205
0
static int32_t get_single_replica_compaction_threads_num(size_t data_dirs_num) {
206
0
    int32_t threads_num = config::max_single_replica_compaction_threads;
207
0
    if (threads_num == -1) {
208
0
        threads_num = data_dirs_num;
209
0
    }
210
0
    threads_num = threads_num <= 0 ? 1 : threads_num;
211
0
    return threads_num;
212
0
}
213
214
0
Status StorageEngine::start_bg_threads(std::shared_ptr<WorkloadGroup> wg_sptr) {
215
0
    RETURN_IF_ERROR(Thread::create(
216
0
            "StorageEngine", "unused_rowset_monitor_thread",
217
0
            [this]() { this->_unused_rowset_monitor_thread_callback(); },
218
0
            &_unused_rowset_monitor_thread));
219
0
    LOG(INFO) << "unused rowset monitor thread started";
220
221
0
    RETURN_IF_ERROR(Thread::create(
222
0
            "StorageEngine", "evict_querying_rowset_thread",
223
0
            [this]() { this->_evict_quring_rowset_thread_callback(); },
224
0
            &_evict_quering_rowset_thread));
225
0
    LOG(INFO) << "evict quering thread started";
226
227
    // start thread for monitoring the snapshot and trash folder
228
0
    RETURN_IF_ERROR(Thread::create(
229
0
            "StorageEngine", "garbage_sweeper_thread",
230
0
            [this]() { this->_garbage_sweeper_thread_callback(); }, &_garbage_sweeper_thread));
231
0
    LOG(INFO) << "garbage sweeper thread started";
232
233
    // start thread for monitoring the tablet with io error
234
0
    RETURN_IF_ERROR(Thread::create(
235
0
            "StorageEngine", "disk_stat_monitor_thread",
236
0
            [this]() { this->_disk_stat_monitor_thread_callback(); }, &_disk_stat_monitor_thread));
237
0
    LOG(INFO) << "disk stat monitor thread started";
238
239
    // convert store map to vector
240
0
    std::vector<DataDir*> data_dirs = get_stores();
241
242
0
    auto base_compaction_threads = get_base_compaction_threads_num(data_dirs.size());
243
0
    auto cumu_compaction_threads = get_cumu_compaction_threads_num(data_dirs.size());
244
0
    auto single_replica_compaction_threads =
245
0
            get_single_replica_compaction_threads_num(data_dirs.size());
246
247
0
    RETURN_IF_ERROR(ThreadPoolBuilder("BaseCompactionTaskThreadPool")
248
0
                            .set_min_threads(base_compaction_threads)
249
0
                            .set_max_threads(base_compaction_threads)
250
0
                            .build(&_base_compaction_thread_pool));
251
0
    RETURN_IF_ERROR(ThreadPoolBuilder("CumuCompactionTaskThreadPool")
252
0
                            .set_min_threads(cumu_compaction_threads)
253
0
                            .set_max_threads(cumu_compaction_threads)
254
0
                            .build(&_cumu_compaction_thread_pool));
255
0
    RETURN_IF_ERROR(ThreadPoolBuilder("SingleReplicaCompactionTaskThreadPool")
256
0
                            .set_min_threads(single_replica_compaction_threads)
257
0
                            .set_max_threads(single_replica_compaction_threads)
258
0
                            .build(&_single_replica_compaction_thread_pool));
259
260
0
    if (config::enable_segcompaction) {
261
0
        RETURN_IF_ERROR(ThreadPoolBuilder("SegCompactionTaskThreadPool")
262
0
                                .set_min_threads(config::segcompaction_num_threads)
263
0
                                .set_max_threads(config::segcompaction_num_threads)
264
0
                                .build(&_seg_compaction_thread_pool));
265
0
    }
266
0
    RETURN_IF_ERROR(ThreadPoolBuilder("ColdDataCompactionTaskThreadPool")
267
0
                            .set_min_threads(config::cold_data_compaction_thread_num)
268
0
                            .set_max_threads(config::cold_data_compaction_thread_num)
269
0
                            .build(&_cold_data_compaction_thread_pool));
270
271
    // compaction tasks producer thread
272
0
    RETURN_IF_ERROR(Thread::create(
273
0
            "StorageEngine", "compaction_tasks_producer_thread",
274
0
            [this]() { this->_compaction_tasks_producer_callback(); },
275
0
            &_compaction_tasks_producer_thread));
276
0
    LOG(INFO) << "compaction tasks producer thread started";
277
278
0
    RETURN_IF_ERROR(Thread::create(
279
0
            "StorageEngine", "_update_replica_infos_thread",
280
0
            [this]() { this->_update_replica_infos_callback(); }, &_update_replica_infos_thread));
281
0
    LOG(INFO) << "tablet replicas info update thread started";
282
283
0
    int32_t max_checkpoint_thread_num = config::max_meta_checkpoint_threads;
284
0
    if (max_checkpoint_thread_num < 0) {
285
0
        max_checkpoint_thread_num = data_dirs.size();
286
0
    }
287
0
    RETURN_IF_ERROR(ThreadPoolBuilder("TabletMetaCheckpointTaskThreadPool")
288
0
                            .set_max_threads(max_checkpoint_thread_num)
289
0
                            .build(&_tablet_meta_checkpoint_thread_pool));
290
291
0
    RETURN_IF_ERROR(ThreadPoolBuilder("MultiGetTaskThreadPool")
292
0
                            .set_min_threads(config::multi_get_max_threads)
293
0
                            .set_max_threads(config::multi_get_max_threads)
294
0
                            .build(&_bg_multi_get_thread_pool));
295
0
    RETURN_IF_ERROR(Thread::create(
296
0
            "StorageEngine", "tablet_checkpoint_tasks_producer_thread",
297
0
            [this, data_dirs]() { this->_tablet_checkpoint_callback(data_dirs); },
298
0
            &_tablet_checkpoint_tasks_producer_thread));
299
0
    LOG(INFO) << "tablet checkpoint tasks producer thread started";
300
301
0
    RETURN_IF_ERROR(Thread::create(
302
0
            "StorageEngine", "tablet_path_check_thread",
303
0
            [this]() { this->_tablet_path_check_callback(); }, &_tablet_path_check_thread));
304
0
    LOG(INFO) << "tablet path check thread started";
305
306
    // path scan and gc thread
307
0
    if (config::path_gc_check) {
308
0
        for (auto data_dir : get_stores()) {
309
0
            scoped_refptr<Thread> path_gc_thread;
310
0
            RETURN_IF_ERROR(Thread::create(
311
0
                    "StorageEngine", "path_gc_thread",
312
0
                    [this, data_dir]() { this->_path_gc_thread_callback(data_dir); },
313
0
                    &path_gc_thread));
314
0
            _path_gc_threads.emplace_back(path_gc_thread);
315
0
        }
316
0
        LOG(INFO) << "path gc threads started. number:" << get_stores().size();
317
0
    }
318
319
0
    RETURN_IF_ERROR(ThreadPoolBuilder("CooldownTaskThreadPool")
320
0
                            .set_min_threads(config::cooldown_thread_num)
321
0
                            .set_max_threads(config::cooldown_thread_num)
322
0
                            .build(&_cooldown_thread_pool));
323
0
    LOG(INFO) << "cooldown thread pool started";
324
325
0
    RETURN_IF_ERROR(Thread::create(
326
0
            "StorageEngine", "cooldown_tasks_producer_thread",
327
0
            [this]() { this->_cooldown_tasks_producer_callback(); },
328
0
            &_cooldown_tasks_producer_thread));
329
0
    LOG(INFO) << "cooldown tasks producer thread started";
330
331
0
    RETURN_IF_ERROR(Thread::create(
332
0
            "StorageEngine", "remove_unused_remote_files_thread",
333
0
            [this]() { this->_remove_unused_remote_files_callback(); },
334
0
            &_remove_unused_remote_files_thread));
335
0
    LOG(INFO) << "remove unused remote files thread started";
336
337
0
    RETURN_IF_ERROR(Thread::create(
338
0
            "StorageEngine", "cold_data_compaction_producer_thread",
339
0
            [this]() { this->_cold_data_compaction_producer_callback(); },
340
0
            &_cold_data_compaction_producer_thread));
341
0
    LOG(INFO) << "cold data compaction producer thread started";
342
343
    // add tablet publish version thread pool
344
0
    RETURN_IF_ERROR(ThreadPoolBuilder("TabletPublishTxnThreadPool")
345
0
                            .set_min_threads(config::tablet_publish_txn_max_thread)
346
0
                            .set_max_threads(config::tablet_publish_txn_max_thread)
347
0
                            .build(&_tablet_publish_txn_thread_pool));
348
349
0
    RETURN_IF_ERROR(Thread::create(
350
0
            "StorageEngine", "async_publish_version_thread",
351
0
            [this]() { this->_async_publish_callback(); }, &_async_publish_thread));
352
0
    LOG(INFO) << "async publish thread started";
353
354
0
    RETURN_IF_ERROR(Thread::create(
355
0
            "StorageEngine", "check_tablet_delete_bitmap_score_thread",
356
0
            [this]() { this->_check_tablet_delete_bitmap_score_callback(); },
357
0
            &_check_delete_bitmap_score_thread));
358
0
    LOG(INFO) << "check tablet delete bitmap score thread started";
359
360
0
    LOG(INFO) << "all storage engine's background threads are started.";
361
0
    return Status::OK();
362
0
}
363
364
0
void StorageEngine::_garbage_sweeper_thread_callback() {
365
0
    uint32_t max_interval = config::max_garbage_sweep_interval;
366
0
    uint32_t min_interval = config::min_garbage_sweep_interval;
367
368
0
    if (max_interval < min_interval || min_interval <= 0) {
369
0
        LOG(WARNING) << "garbage sweep interval config is illegal: [max=" << max_interval
370
0
                     << " min=" << min_interval << "].";
371
0
        min_interval = 1;
372
0
        max_interval = max_interval >= min_interval ? max_interval : min_interval;
373
0
        LOG(INFO) << "force reset garbage sweep interval. "
374
0
                  << "max_interval=" << max_interval << ", min_interval=" << min_interval;
375
0
    }
376
377
0
    const double pi = M_PI;
378
0
    double usage = 1.0;
379
    // After the program starts, the first round of cleaning starts after min_interval.
380
0
    uint32_t curr_interval = min_interval;
381
0
    do {
382
        // Function properties:
383
        // when usage < 0.6,          ratio close to 1.(interval close to max_interval)
384
        // when usage at [0.6, 0.75], ratio is rapidly decreasing from 0.87 to 0.27.
385
        // when usage > 0.75,         ratio is slowly decreasing.
386
        // when usage > 0.8,          ratio close to min_interval.
387
        // when usage = 0.88,         ratio is approximately 0.0057.
388
0
        double ratio = (1.1 * (pi / 2 - std::atan(usage * 100 / 5 - 14)) - 0.28) / pi;
389
0
        ratio = ratio > 0 ? ratio : 0;
390
0
        auto curr_interval = uint32_t(max_interval * ratio);
391
0
        curr_interval = std::max(curr_interval, min_interval);
392
0
        curr_interval = std::min(curr_interval, max_interval);
393
394
        // start clean trash and update usage.
395
0
        Status res = start_trash_sweep(&usage);
396
0
        if (res.ok() && _need_clean_trash.exchange(false, std::memory_order_relaxed)) {
397
0
            res = start_trash_sweep(&usage, true);
398
0
        }
399
400
0
        if (!res.ok()) {
401
0
            LOG(WARNING) << "one or more errors occur when sweep trash."
402
0
                         << "see previous message for detail. err code=" << res;
403
            // do nothing. continue next loop.
404
0
        }
405
0
    } while (!_stop_background_threads_latch.wait_for(std::chrono::seconds(curr_interval)));
406
0
}
407
408
0
void StorageEngine::_disk_stat_monitor_thread_callback() {
409
0
    int32_t interval = config::disk_stat_monitor_interval;
410
0
    do {
411
0
        _start_disk_stat_monitor();
412
413
0
        interval = config::disk_stat_monitor_interval;
414
0
        if (interval <= 0) {
415
0
            LOG(WARNING) << "disk_stat_monitor_interval config is illegal: " << interval
416
0
                         << ", force set to 1";
417
0
            interval = 1;
418
0
        }
419
0
    } while (!_stop_background_threads_latch.wait_for(std::chrono::seconds(interval)));
420
0
}
421
422
0
void StorageEngine::_unused_rowset_monitor_thread_callback() {
423
0
    int32_t interval = config::unused_rowset_monitor_interval;
424
0
    do {
425
0
        start_delete_unused_rowset();
426
427
0
        interval = config::unused_rowset_monitor_interval;
428
0
        if (interval <= 0) {
429
0
            LOG(WARNING) << "unused_rowset_monitor_interval config is illegal: " << interval
430
0
                         << ", force set to 1";
431
0
            interval = 1;
432
0
        }
433
0
    } while (!_stop_background_threads_latch.wait_for(std::chrono::seconds(interval)));
434
0
}
435
436
0
int32_t StorageEngine::_auto_get_interval_by_disk_capacity(DataDir* data_dir) {
437
0
    double disk_used = data_dir->get_usage(0);
438
0
    double remain_used = 1 - disk_used;
439
0
    DCHECK(remain_used >= 0 && remain_used <= 1);
440
0
    DCHECK(config::path_gc_check_interval_second >= 0);
441
0
    int32_t ret = 0;
442
0
    if (remain_used > 0.9) {
443
        // if config::path_gc_check_interval_second == 24h
444
0
        ret = config::path_gc_check_interval_second;
445
0
    } else if (remain_used > 0.7) {
446
        // 12h
447
0
        ret = config::path_gc_check_interval_second / 2;
448
0
    } else if (remain_used > 0.5) {
449
        // 6h
450
0
        ret = config::path_gc_check_interval_second / 4;
451
0
    } else if (remain_used > 0.3) {
452
        // 4h
453
0
        ret = config::path_gc_check_interval_second / 6;
454
0
    } else {
455
        // 3h
456
0
        ret = config::path_gc_check_interval_second / 8;
457
0
    }
458
0
    return ret;
459
0
}
460
461
0
void StorageEngine::_path_gc_thread_callback(DataDir* data_dir) {
462
0
    LOG(INFO) << "try to start path gc thread!";
463
0
    int32_t last_exec_time = 0;
464
0
    do {
465
0
        int32_t current_time = time(nullptr);
466
467
0
        int32_t interval = _auto_get_interval_by_disk_capacity(data_dir);
468
0
        DBUG_EXECUTE_IF("_path_gc_thread_callback.interval.eq.1ms", {
469
0
            LOG(INFO) << "debug point change interval eq 1ms";
470
0
            interval = 1;
471
0
            while (DebugPoints::instance()->is_enable("_path_gc_thread_callback.always.do")) {
472
0
                data_dir->perform_path_gc();
473
0
                std::this_thread::sleep_for(std::chrono::milliseconds(10));
474
0
            }
475
0
        });
476
0
        if (interval <= 0) {
477
0
            LOG(WARNING) << "path gc thread check interval config is illegal:" << interval
478
0
                         << " will be forced set to half hour";
479
0
            interval = 1800; // 0.5 hour
480
0
        }
481
0
        if (current_time - last_exec_time >= interval) {
482
0
            LOG(INFO) << "try to perform path gc! disk remain [" << 1 - data_dir->get_usage(0)
483
0
                      << "] internal [" << interval << "]";
484
0
            data_dir->perform_path_gc();
485
0
            last_exec_time = time(nullptr);
486
0
        }
487
0
    } while (!_stop_background_threads_latch.wait_for(std::chrono::seconds(5)));
488
0
    LOG(INFO) << "stop path gc thread!";
489
0
}
490
491
0
void StorageEngine::_tablet_checkpoint_callback(const std::vector<DataDir*>& data_dirs) {
492
0
    int64_t interval = config::generate_tablet_meta_checkpoint_tasks_interval_secs;
493
0
    do {
494
0
        for (auto data_dir : data_dirs) {
495
0
            LOG(INFO) << "begin to produce tablet meta checkpoint tasks, data_dir="
496
0
                      << data_dir->path();
497
0
            auto st = _tablet_meta_checkpoint_thread_pool->submit_func(
498
0
                    [data_dir, this]() { _tablet_manager->do_tablet_meta_checkpoint(data_dir); });
499
0
            if (!st.ok()) {
500
0
                LOG(WARNING) << "submit tablet checkpoint tasks failed.";
501
0
            }
502
0
        }
503
0
        interval = config::generate_tablet_meta_checkpoint_tasks_interval_secs;
504
0
    } while (!_stop_background_threads_latch.wait_for(std::chrono::seconds(interval)));
505
0
}
506
507
0
void StorageEngine::_tablet_path_check_callback() {
508
0
    struct TabletIdComparator {
509
0
        bool operator()(Tablet* a, Tablet* b) { return a->tablet_id() < b->tablet_id(); }
510
0
    };
511
512
0
    using TabletQueue = std::priority_queue<Tablet*, std::vector<Tablet*>, TabletIdComparator>;
513
514
0
    int64_t interval = config::tablet_path_check_interval_seconds;
515
0
    if (interval <= 0) {
516
0
        return;
517
0
    }
518
519
0
    int64_t last_tablet_id = 0;
520
0
    do {
521
0
        int32_t batch_size = config::tablet_path_check_batch_size;
522
0
        if (batch_size <= 0) {
523
0
            if (_stop_background_threads_latch.wait_for(std::chrono::seconds(interval))) {
524
0
                break;
525
0
            }
526
0
            continue;
527
0
        }
528
529
0
        LOG(INFO) << "start to check tablet path";
530
531
0
        auto all_tablets = _tablet_manager->get_all_tablet(
532
0
                [](Tablet* t) { return t->is_used() && t->tablet_state() == TABLET_RUNNING; });
533
534
0
        TabletQueue big_id_tablets;
535
0
        TabletQueue small_id_tablets;
536
0
        for (auto tablet : all_tablets) {
537
0
            auto tablet_id = tablet->tablet_id();
538
0
            TabletQueue* belong_tablets = nullptr;
539
0
            if (tablet_id > last_tablet_id) {
540
0
                if (big_id_tablets.size() < batch_size ||
541
0
                    big_id_tablets.top()->tablet_id() > tablet_id) {
542
0
                    belong_tablets = &big_id_tablets;
543
0
                }
544
0
            } else if (big_id_tablets.size() < batch_size) {
545
0
                if (small_id_tablets.size() < batch_size ||
546
0
                    small_id_tablets.top()->tablet_id() > tablet_id) {
547
0
                    belong_tablets = &small_id_tablets;
548
0
                }
549
0
            }
550
0
            if (belong_tablets != nullptr) {
551
0
                belong_tablets->push(tablet.get());
552
0
                if (belong_tablets->size() > batch_size) {
553
0
                    belong_tablets->pop();
554
0
                }
555
0
            }
556
0
        }
557
558
0
        int32_t need_small_id_tablet_size =
559
0
                batch_size - static_cast<int32_t>(big_id_tablets.size());
560
561
0
        if (!big_id_tablets.empty()) {
562
0
            last_tablet_id = big_id_tablets.top()->tablet_id();
563
0
        }
564
0
        while (!big_id_tablets.empty()) {
565
0
            big_id_tablets.top()->check_tablet_path_exists();
566
0
            big_id_tablets.pop();
567
0
        }
568
569
0
        if (!small_id_tablets.empty() && need_small_id_tablet_size > 0) {
570
0
            while (static_cast<int32_t>(small_id_tablets.size()) > need_small_id_tablet_size) {
571
0
                small_id_tablets.pop();
572
0
            }
573
574
0
            last_tablet_id = small_id_tablets.top()->tablet_id();
575
0
            while (!small_id_tablets.empty()) {
576
0
                small_id_tablets.top()->check_tablet_path_exists();
577
0
                small_id_tablets.pop();
578
0
            }
579
0
        }
580
581
0
    } while (!_stop_background_threads_latch.wait_for(std::chrono::seconds(interval)));
582
0
}
583
584
0
void StorageEngine::_adjust_compaction_thread_num() {
585
0
    auto base_compaction_threads_num = get_base_compaction_threads_num(_store_map.size());
586
0
    if (_base_compaction_thread_pool->max_threads() != base_compaction_threads_num) {
587
0
        int old_max_threads = _base_compaction_thread_pool->max_threads();
588
0
        Status status = _base_compaction_thread_pool->set_max_threads(base_compaction_threads_num);
589
0
        if (status.ok()) {
590
0
            VLOG_NOTICE << "update base compaction thread pool max_threads from " << old_max_threads
591
0
                        << " to " << base_compaction_threads_num;
592
0
        }
593
0
    }
594
0
    if (_base_compaction_thread_pool->min_threads() != base_compaction_threads_num) {
595
0
        int old_min_threads = _base_compaction_thread_pool->min_threads();
596
0
        Status status = _base_compaction_thread_pool->set_min_threads(base_compaction_threads_num);
597
0
        if (status.ok()) {
598
0
            VLOG_NOTICE << "update base compaction thread pool min_threads from " << old_min_threads
599
0
                        << " to " << base_compaction_threads_num;
600
0
        }
601
0
    }
602
603
0
    auto cumu_compaction_threads_num = get_cumu_compaction_threads_num(_store_map.size());
604
0
    if (_cumu_compaction_thread_pool->max_threads() != cumu_compaction_threads_num) {
605
0
        int old_max_threads = _cumu_compaction_thread_pool->max_threads();
606
0
        Status status = _cumu_compaction_thread_pool->set_max_threads(cumu_compaction_threads_num);
607
0
        if (status.ok()) {
608
0
            VLOG_NOTICE << "update cumu compaction thread pool max_threads from " << old_max_threads
609
0
                        << " to " << cumu_compaction_threads_num;
610
0
        }
611
0
    }
612
0
    if (_cumu_compaction_thread_pool->min_threads() != cumu_compaction_threads_num) {
613
0
        int old_min_threads = _cumu_compaction_thread_pool->min_threads();
614
0
        Status status = _cumu_compaction_thread_pool->set_min_threads(cumu_compaction_threads_num);
615
0
        if (status.ok()) {
616
0
            VLOG_NOTICE << "update cumu compaction thread pool min_threads from " << old_min_threads
617
0
                        << " to " << cumu_compaction_threads_num;
618
0
        }
619
0
    }
620
621
0
    auto single_replica_compaction_threads_num =
622
0
            get_single_replica_compaction_threads_num(_store_map.size());
623
0
    if (_single_replica_compaction_thread_pool->max_threads() !=
624
0
        single_replica_compaction_threads_num) {
625
0
        int old_max_threads = _single_replica_compaction_thread_pool->max_threads();
626
0
        Status status = _single_replica_compaction_thread_pool->set_max_threads(
627
0
                single_replica_compaction_threads_num);
628
0
        if (status.ok()) {
629
0
            VLOG_NOTICE << "update single replica compaction thread pool max_threads from "
630
0
                        << old_max_threads << " to " << single_replica_compaction_threads_num;
631
0
        }
632
0
    }
633
0
    if (_single_replica_compaction_thread_pool->min_threads() !=
634
0
        single_replica_compaction_threads_num) {
635
0
        int old_min_threads = _single_replica_compaction_thread_pool->min_threads();
636
0
        Status status = _single_replica_compaction_thread_pool->set_min_threads(
637
0
                single_replica_compaction_threads_num);
638
0
        if (status.ok()) {
639
0
            VLOG_NOTICE << "update single replica compaction thread pool min_threads from "
640
0
                        << old_min_threads << " to " << single_replica_compaction_threads_num;
641
0
        }
642
0
    }
643
0
}
644
645
0
void StorageEngine::_compaction_tasks_producer_callback() {
646
0
    LOG(INFO) << "try to start compaction producer process!";
647
648
0
    std::vector<DataDir*> data_dirs = get_stores();
649
0
    _compaction_submit_registry.reset(data_dirs);
650
651
0
    int round = 0;
652
0
    CompactionType compaction_type;
653
654
    // Used to record the time when the score metric was last updated.
655
    // The update of the score metric is accompanied by the logic of selecting the tablet.
656
    // If there is no slot available, the logic of selecting the tablet will be terminated,
657
    // which causes the score metric update to be terminated.
658
    // In order to avoid this situation, we need to update the score regularly.
659
0
    int64_t last_cumulative_score_update_time = 0;
660
0
    int64_t last_base_score_update_time = 0;
661
0
    static const int64_t check_score_interval_ms = 5000; // 5 secs
662
663
0
    int64_t interval = config::generate_compaction_tasks_interval_ms;
664
0
    do {
665
0
        if (!config::disable_auto_compaction &&
666
0
            (!config::enable_compaction_pause_on_high_memory ||
667
0
             !GlobalMemoryArbitrator::is_exceed_soft_mem_limit(GB_EXCHANGE_BYTE))) {
668
0
            _adjust_compaction_thread_num();
669
670
0
            bool check_score = false;
671
0
            int64_t cur_time = UnixMillis();
672
0
            if (round < config::cumulative_compaction_rounds_for_each_base_compaction_round) {
673
0
                compaction_type = CompactionType::CUMULATIVE_COMPACTION;
674
0
                round++;
675
0
                if (cur_time - last_cumulative_score_update_time >= check_score_interval_ms) {
676
0
                    check_score = true;
677
0
                    last_cumulative_score_update_time = cur_time;
678
0
                }
679
0
            } else {
680
0
                compaction_type = CompactionType::BASE_COMPACTION;
681
0
                round = 0;
682
0
                if (cur_time - last_base_score_update_time >= check_score_interval_ms) {
683
0
                    check_score = true;
684
0
                    last_base_score_update_time = cur_time;
685
0
                }
686
0
            }
687
0
            std::vector<TabletSharedPtr> tablets_compaction =
688
0
                    _generate_compaction_tasks(compaction_type, data_dirs, check_score);
689
0
            if (tablets_compaction.size() == 0) {
690
0
                std::unique_lock<std::mutex> lock(_compaction_producer_sleep_mutex);
691
0
                _wakeup_producer_flag = 0;
692
                // It is necessary to wake up the thread on timeout to prevent deadlock
693
                // in case of no running compaction task.
694
0
                _compaction_producer_sleep_cv.wait_for(
695
0
                        lock, std::chrono::milliseconds(2000),
696
0
                        [this] { return _wakeup_producer_flag == 1; });
697
0
                continue;
698
0
            }
699
700
0
            for (const auto& tablet : tablets_compaction) {
701
0
                if (compaction_type == CompactionType::BASE_COMPACTION) {
702
0
                    tablet->set_last_base_compaction_schedule_time(UnixMillis());
703
0
                }
704
0
                Status st = _submit_compaction_task(tablet, compaction_type, false);
705
0
                if (!st.ok()) {
706
0
                    LOG(WARNING) << "failed to submit compaction task for tablet: "
707
0
                                 << tablet->tablet_id() << ", err: " << st;
708
0
                }
709
0
            }
710
0
            interval = config::generate_compaction_tasks_interval_ms;
711
0
        } else {
712
0
            interval = 5000; // 5s to check disable_auto_compaction
713
0
        }
714
0
    } while (!_stop_background_threads_latch.wait_for(std::chrono::milliseconds(interval)));
715
0
}
716
717
0
void StorageEngine::_update_replica_infos_callback() {
718
#ifdef GOOGLE_PROFILER
719
    ProfilerRegisterThread();
720
#endif
721
0
    LOG(INFO) << "start to update replica infos!";
722
723
0
    int64_t interval = config::update_replica_infos_interval_seconds;
724
0
    do {
725
0
        auto all_tablets = _tablet_manager->get_all_tablet([](Tablet* t) {
726
0
            return t->is_used() && t->tablet_state() == TABLET_RUNNING &&
727
0
                   !t->tablet_meta()->tablet_schema()->disable_auto_compaction() &&
728
0
                   t->tablet_meta()->tablet_schema()->enable_single_replica_compaction();
729
0
        });
730
0
        ClusterInfo* cluster_info = ExecEnv::GetInstance()->cluster_info();
731
0
        if (cluster_info == nullptr) {
732
0
            LOG(WARNING) << "Have not get FE Master heartbeat yet";
733
0
            std::this_thread::sleep_for(std::chrono::seconds(2));
734
0
            continue;
735
0
        }
736
0
        TNetworkAddress master_addr = cluster_info->master_fe_addr;
737
0
        if (master_addr.hostname == "" || master_addr.port == 0) {
738
0
            LOG(WARNING) << "Have not get FE Master heartbeat yet";
739
0
            std::this_thread::sleep_for(std::chrono::seconds(2));
740
0
            continue;
741
0
        }
742
743
0
        int start = 0;
744
0
        int tablet_size = all_tablets.size();
745
        // The while loop may take a long time, we should skip it when stop
746
0
        while (start < tablet_size && _stop_background_threads_latch.count() > 0) {
747
0
            int batch_size = std::min(100, tablet_size - start);
748
0
            int end = start + batch_size;
749
0
            TGetTabletReplicaInfosRequest request;
750
0
            TGetTabletReplicaInfosResult result;
751
0
            for (int i = start; i < end; i++) {
752
0
                request.tablet_ids.emplace_back(all_tablets[i]->tablet_id());
753
0
            }
754
0
            Status rpc_st = ThriftRpcHelper::rpc<FrontendServiceClient>(
755
0
                    master_addr.hostname, master_addr.port,
756
0
                    [&request, &result](FrontendServiceConnection& client) {
757
0
                        client->getTabletReplicaInfos(result, request);
758
0
                    });
759
760
0
            if (!rpc_st.ok()) {
761
0
                LOG(WARNING) << "Failed to get tablet replica infos, encounter rpc failure, "
762
0
                                "tablet start: "
763
0
                             << start << " end: " << end;
764
0
                continue;
765
0
            }
766
767
0
            std::unique_lock<std::mutex> lock(_peer_replica_infos_mutex);
768
0
            for (const auto& it : result.tablet_replica_infos) {
769
0
                auto tablet_id = it.first;
770
0
                auto tablet = _tablet_manager->get_tablet(tablet_id);
771
0
                if (tablet == nullptr) {
772
0
                    VLOG_CRITICAL << "tablet ptr is nullptr";
773
0
                    continue;
774
0
                }
775
776
0
                VLOG_NOTICE << tablet_id << " tablet has " << it.second.size() << " replicas";
777
0
                uint64_t min_modulo = MOD_PRIME;
778
0
                TReplicaInfo peer_replica;
779
0
                for (const auto& replica : it.second) {
780
0
                    int64_t peer_replica_id = replica.replica_id;
781
0
                    uint64_t modulo = HashUtil::hash64(&peer_replica_id, sizeof(peer_replica_id),
782
0
                                                       DEFAULT_SEED) %
783
0
                                      MOD_PRIME;
784
0
                    if (modulo < min_modulo) {
785
0
                        peer_replica = replica;
786
0
                        min_modulo = modulo;
787
0
                    }
788
0
                }
789
0
                VLOG_NOTICE << "tablet " << tablet_id << ", peer replica host is "
790
0
                            << peer_replica.host;
791
0
                _peer_replica_infos[tablet_id] = peer_replica;
792
0
            }
793
0
            _token = result.token;
794
0
            VLOG_NOTICE << "get tablet replica infos from fe, size is " << end - start
795
0
                        << " token = " << result.token;
796
0
            start = end;
797
0
        }
798
0
        interval = config::update_replica_infos_interval_seconds;
799
0
    } while (!_stop_background_threads_latch.wait_for(std::chrono::seconds(interval)));
800
0
}
801
802
Status StorageEngine::_submit_single_replica_compaction_task(TabletSharedPtr tablet,
803
0
                                                             CompactionType compaction_type) {
804
    // For single replica compaction, the local version to be merged is determined based on the version fetched from the peer replica.
805
    // Therefore, it is currently not possible to determine whether it should be a base compaction or cumulative compaction.
806
    // As a result, the tablet needs to be pushed to both the _tablet_submitted_cumu_compaction and the _tablet_submitted_base_compaction simultaneously.
807
0
    bool already_exist =
808
0
            _compaction_submit_registry.insert(tablet, CompactionType::CUMULATIVE_COMPACTION);
809
0
    if (already_exist) {
810
0
        return Status::AlreadyExist<false>(
811
0
                "compaction task has already been submitted, tablet_id={}", tablet->tablet_id());
812
0
    }
813
814
0
    already_exist = _compaction_submit_registry.insert(tablet, CompactionType::BASE_COMPACTION);
815
0
    if (already_exist) {
816
0
        _pop_tablet_from_submitted_compaction(tablet, CompactionType::CUMULATIVE_COMPACTION);
817
0
        return Status::AlreadyExist<false>(
818
0
                "compaction task has already been submitted, tablet_id={}", tablet->tablet_id());
819
0
    }
820
821
0
    auto compaction = std::make_shared<SingleReplicaCompaction>(*this, tablet, compaction_type);
822
0
    DorisMetrics::instance()->single_compaction_request_total->increment(1);
823
0
    auto st = compaction->prepare_compact();
824
825
0
    auto clean_single_replica_compaction = [tablet, this]() {
826
0
        _pop_tablet_from_submitted_compaction(tablet, CompactionType::CUMULATIVE_COMPACTION);
827
0
        _pop_tablet_from_submitted_compaction(tablet, CompactionType::BASE_COMPACTION);
828
0
    };
829
830
0
    if (!st.ok()) {
831
0
        clean_single_replica_compaction();
832
0
        if (!st.is<ErrorCode::CUMULATIVE_NO_SUITABLE_VERSION>()) {
833
0
            LOG(WARNING) << "failed to prepare single replica compaction, tablet_id="
834
0
                         << tablet->tablet_id() << " : " << st;
835
0
            return st;
836
0
        }
837
0
        return Status::OK(); // No suitable version, regard as OK
838
0
    }
839
840
0
    auto submit_st = _single_replica_compaction_thread_pool->submit_func(
841
0
            [tablet, compaction = std::move(compaction),
842
0
             clean_single_replica_compaction]() mutable {
843
0
                tablet->execute_single_replica_compaction(*compaction);
844
0
                clean_single_replica_compaction();
845
0
            });
846
0
    if (!submit_st.ok()) {
847
0
        clean_single_replica_compaction();
848
0
        return Status::InternalError(
849
0
                "failed to submit single replica compaction task to thread pool, "
850
0
                "tablet_id={}",
851
0
                tablet->tablet_id());
852
0
    }
853
0
    return Status::OK();
854
0
}
855
856
void StorageEngine::get_tablet_rowset_versions(const PGetTabletVersionsRequest* request,
857
0
                                               PGetTabletVersionsResponse* response) {
858
0
    TabletSharedPtr tablet = _tablet_manager->get_tablet(request->tablet_id());
859
0
    if (tablet == nullptr) {
860
0
        response->mutable_status()->set_status_code(TStatusCode::CANCELLED);
861
0
        return;
862
0
    }
863
0
    std::vector<Version> local_versions = tablet->get_all_local_versions();
864
0
    for (const auto& local_version : local_versions) {
865
0
        auto version = response->add_versions();
866
0
        version->set_first(local_version.first);
867
0
        version->set_second(local_version.second);
868
0
    }
869
0
    response->mutable_status()->set_status_code(0);
870
0
}
871
872
bool need_generate_compaction_tasks(int task_cnt_per_disk, int thread_per_disk,
873
0
                                    CompactionType compaction_type, bool all_base) {
874
    // We need to reserve at least one Slot for cumulative compaction.
875
    // So when there is only one Slot, we have to judge whether there is a cumulative compaction
876
    // in the current submitted tasks.
877
    // If so, the last Slot can be assigned to Base compaction,
878
    // otherwise, this Slot needs to be reserved for cumulative compaction.
879
0
    if (task_cnt_per_disk >= thread_per_disk) {
880
        // Return if no available slot
881
0
        return false;
882
0
    } else if (task_cnt_per_disk >= thread_per_disk - 1) {
883
        // Only one slot left, check if it can be assigned to base compaction task.
884
0
        if (compaction_type == CompactionType::BASE_COMPACTION) {
885
0
            if (all_base) {
886
0
                return false;
887
0
            }
888
0
        }
889
0
    }
890
0
    return true;
891
0
}
892
893
0
int get_concurrent_per_disk(int max_score, int thread_per_disk) {
894
0
    if (!config::enable_compaction_priority_scheduling) {
895
0
        return thread_per_disk;
896
0
    }
897
898
0
    double load_average = 0;
899
0
    if (DorisMetrics::instance()->system_metrics() != nullptr) {
900
0
        load_average = DorisMetrics::instance()->system_metrics()->get_load_average_1_min();
901
0
    }
902
0
    int num_cores = doris::CpuInfo::num_cores();
903
0
    bool cpu_usage_high = load_average > num_cores * 0.8;
904
905
0
    auto process_memory_usage = doris::GlobalMemoryArbitrator::process_memory_usage();
906
0
    bool memory_usage_high = process_memory_usage > MemInfo::soft_mem_limit() * 0.8;
907
908
0
    if (max_score <= config::low_priority_compaction_score_threshold &&
909
0
        (cpu_usage_high || memory_usage_high)) {
910
0
        return config::low_priority_compaction_task_num_per_disk;
911
0
    }
912
913
0
    return thread_per_disk;
914
0
}
915
916
0
int32_t disk_compaction_slot_num(const DataDir& data_dir) {
917
0
    return data_dir.is_ssd_disk() ? config::compaction_task_num_per_fast_disk
918
0
                                  : config::compaction_task_num_per_disk;
919
0
}
920
921
bool has_free_compaction_slot(CompactionSubmitRegistry* registry, DataDir* dir,
922
0
                              CompactionType compaction_type, uint32_t executing_cnt) {
923
0
    int32_t thread_per_disk = disk_compaction_slot_num(*dir);
924
0
    return need_generate_compaction_tasks(
925
0
            executing_cnt, thread_per_disk, compaction_type,
926
0
            !registry->has_compaction_task(dir, CompactionType::CUMULATIVE_COMPACTION));
927
0
}
928
929
std::vector<TabletSharedPtr> StorageEngine::_generate_compaction_tasks(
930
0
        CompactionType compaction_type, std::vector<DataDir*>& data_dirs, bool check_score) {
931
0
    _update_cumulative_compaction_policy();
932
0
    std::vector<TabletSharedPtr> tablets_compaction;
933
0
    uint32_t max_compaction_score = 0;
934
935
0
    std::random_device rd;
936
0
    std::mt19937 g(rd());
937
0
    std::shuffle(data_dirs.begin(), data_dirs.end(), g);
938
939
    // Copy _tablet_submitted_xxx_compaction map so that we don't need to hold _tablet_submitted_compaction_mutex
940
    // when traversing the data dir
941
0
    auto compaction_registry_snapshot = _compaction_submit_registry.create_snapshot();
942
0
    for (auto* data_dir : data_dirs) {
943
0
        bool need_pick_tablet = true;
944
0
        uint32_t executing_task_num =
945
0
                compaction_registry_snapshot.count_executing_cumu_and_base(data_dir);
946
0
        need_pick_tablet = has_free_compaction_slot(&compaction_registry_snapshot, data_dir,
947
0
                                                    compaction_type, executing_task_num);
948
0
        if (!need_pick_tablet && !check_score) {
949
0
            continue;
950
0
        }
951
952
        // Even if need_pick_tablet is false, we still need to call find_best_tablet_to_compaction(),
953
        // So that we can update the max_compaction_score metric.
954
0
        if (!data_dir->reach_capacity_limit(0)) {
955
0
            uint32_t disk_max_score = 0;
956
0
            auto tablets = compaction_registry_snapshot.pick_topn_tablets_for_compaction(
957
0
                    _tablet_manager.get(), data_dir, compaction_type,
958
0
                    _cumulative_compaction_policies, &disk_max_score);
959
0
            int concurrent_num =
960
0
                    get_concurrent_per_disk(disk_max_score, disk_compaction_slot_num(*data_dir));
961
0
            need_pick_tablet = need_generate_compaction_tasks(
962
0
                    executing_task_num, concurrent_num, compaction_type,
963
0
                    !compaction_registry_snapshot.has_compaction_task(
964
0
                            data_dir, CompactionType::CUMULATIVE_COMPACTION));
965
0
            for (const auto& tablet : tablets) {
966
0
                if (tablet != nullptr) {
967
0
                    if (need_pick_tablet) {
968
0
                        tablets_compaction.emplace_back(tablet);
969
0
                    }
970
0
                    max_compaction_score = std::max(max_compaction_score, disk_max_score);
971
0
                }
972
0
            }
973
0
        }
974
0
    }
975
976
0
    if (max_compaction_score > 0) {
977
0
        if (compaction_type == CompactionType::BASE_COMPACTION) {
978
0
            DorisMetrics::instance()->tablet_base_max_compaction_score->set_value(
979
0
                    max_compaction_score);
980
0
        } else {
981
0
            DorisMetrics::instance()->tablet_cumulative_max_compaction_score->set_value(
982
0
                    max_compaction_score);
983
0
        }
984
0
    }
985
0
    return tablets_compaction;
986
0
}
987
988
0
void StorageEngine::_update_cumulative_compaction_policy() {
989
0
    if (_cumulative_compaction_policies.empty()) {
990
0
        _cumulative_compaction_policies[CUMULATIVE_SIZE_BASED_POLICY] =
991
0
                CumulativeCompactionPolicyFactory::create_cumulative_compaction_policy(
992
0
                        CUMULATIVE_SIZE_BASED_POLICY);
993
0
        _cumulative_compaction_policies[CUMULATIVE_TIME_SERIES_POLICY] =
994
0
                CumulativeCompactionPolicyFactory::create_cumulative_compaction_policy(
995
0
                        CUMULATIVE_TIME_SERIES_POLICY);
996
0
    }
997
0
}
998
999
void StorageEngine::_pop_tablet_from_submitted_compaction(TabletSharedPtr tablet,
1000
2
                                                          CompactionType compaction_type) {
1001
2
    _compaction_submit_registry.remove(tablet, compaction_type, [this]() {
1002
2
        std::unique_lock<std::mutex> lock(_compaction_producer_sleep_mutex);
1003
2
        _wakeup_producer_flag = 1;
1004
2
        _compaction_producer_sleep_cv.notify_one();
1005
2
    });
1006
2
}
1007
1008
Status StorageEngine::_submit_compaction_task(TabletSharedPtr tablet,
1009
10
                                              CompactionType compaction_type, bool force) {
1010
10
    if (tablet->tablet_meta()->tablet_schema()->enable_single_replica_compaction() &&
1011
10
        should_fetch_from_peer(tablet->tablet_id())) {
1012
0
        VLOG_CRITICAL << "start to submit single replica compaction task for tablet: "
1013
0
                      << tablet->tablet_id();
1014
0
        Status st = _submit_single_replica_compaction_task(tablet, compaction_type);
1015
0
        if (!st.ok()) {
1016
0
            LOG(WARNING) << "failed to submit single replica compaction task for tablet: "
1017
0
                         << tablet->tablet_id() << ", err: " << st;
1018
0
        }
1019
1020
0
        return Status::OK();
1021
0
    }
1022
10
    bool already_exist = _compaction_submit_registry.insert(tablet, compaction_type);
1023
10
    if (already_exist) {
1024
0
        return Status::AlreadyExist<false>(
1025
0
                "compaction task has already been submitted, tablet_id={}, compaction_type={}.",
1026
0
                tablet->tablet_id(), compaction_type);
1027
0
    }
1028
10
    tablet->compaction_stage = CompactionStage::PENDING;
1029
10
    std::shared_ptr<CompactionMixin> compaction;
1030
10
    int64_t permits = 0;
1031
10
    Status st = Tablet::prepare_compaction_and_calculate_permits(compaction_type, tablet,
1032
10
                                                                 compaction, permits);
1033
10
    if (st.ok() && permits > 0) {
1034
10
        if (!force) {
1035
10
            _permit_limiter.request(permits);
1036
10
        }
1037
10
        std::unique_ptr<ThreadPool>& thread_pool =
1038
10
                (compaction_type == CompactionType::CUMULATIVE_COMPACTION)
1039
10
                        ? _cumu_compaction_thread_pool
1040
10
                        : _base_compaction_thread_pool;
1041
10
        VLOG_CRITICAL << "compaction thread pool. type: "
1042
0
                      << (compaction_type == CompactionType::CUMULATIVE_COMPACTION ? "CUMU"
1043
0
                                                                                   : "BASE")
1044
0
                      << ", num_threads: " << thread_pool->num_threads()
1045
0
                      << ", num_threads_pending_start: " << thread_pool->num_threads_pending_start()
1046
0
                      << ", num_active_threads: " << thread_pool->num_active_threads()
1047
0
                      << ", max_threads: " << thread_pool->max_threads()
1048
0
                      << ", min_threads: " << thread_pool->min_threads()
1049
0
                      << ", num_total_queued_tasks: " << thread_pool->get_queue_size();
1050
10
        auto st = thread_pool->submit_func([tablet, compaction = std::move(compaction),
1051
10
                                            compaction_type, permits, force, this]() {
1052
2
            bool is_large_task = true;
1053
2
            Defer defer {[&]() {
1054
2
                DBUG_EXECUTE_IF("StorageEngine._submit_compaction_task.sleep", { sleep(5); })
1055
2
                if (!force) {
1056
2
                    _permit_limiter.release(permits);
1057
2
                }
1058
2
                _pop_tablet_from_submitted_compaction(tablet, compaction_type);
1059
2
                tablet->compaction_stage = CompactionStage::NOT_SCHEDULED;
1060
2
                if (compaction_type == CompactionType::CUMULATIVE_COMPACTION) {
1061
2
                    std::lock_guard<std::mutex> lock(_cumu_compaction_delay_mtx);
1062
2
                    _cumu_compaction_thread_pool_used_threads--;
1063
2
                    if (!is_large_task) {
1064
0
                        _cumu_compaction_thread_pool_small_tasks_running--;
1065
0
                    }
1066
2
                }
1067
2
            }};
1068
2
            do {
1069
2
                if (compaction->compaction_type() == ReaderType::READER_CUMULATIVE_COMPACTION) {
1070
2
                    std::lock_guard<std::mutex> lock(_cumu_compaction_delay_mtx);
1071
2
                    _cumu_compaction_thread_pool_used_threads++;
1072
2
                    if (config::large_cumu_compaction_task_min_thread_num > 1 &&
1073
2
                        _cumu_compaction_thread_pool->max_threads() >=
1074
0
                                config::large_cumu_compaction_task_min_thread_num) {
1075
                        // Determine if this is a large task based on configured thresholds
1076
0
                        is_large_task =
1077
0
                                (compaction->calc_input_rowsets_total_size() >
1078
0
                                         config::large_cumu_compaction_task_bytes_threshold ||
1079
0
                                 compaction->calc_input_rowsets_row_num() >
1080
0
                                         config::large_cumu_compaction_task_row_num_threshold);
1081
1082
                        // Small task. No delay needed
1083
0
                        if (!is_large_task) {
1084
0
                            _cumu_compaction_thread_pool_small_tasks_running++;
1085
0
                            break;
1086
0
                        }
1087
                        // Deal with large task
1088
0
                        if (_should_delay_large_task()) {
1089
0
                            LOG_WARNING(
1090
0
                                    "failed to do CumulativeCompaction, cumu thread pool is "
1091
0
                                    "intensive, delay large task.")
1092
0
                                    .tag("tablet_id", tablet->tablet_id())
1093
0
                                    .tag("input_rows", compaction->calc_input_rowsets_row_num())
1094
0
                                    .tag("input_rowsets_total_size",
1095
0
                                         compaction->calc_input_rowsets_total_size())
1096
0
                                    .tag("config::large_cumu_compaction_task_bytes_threshold",
1097
0
                                         config::large_cumu_compaction_task_bytes_threshold)
1098
0
                                    .tag("config::large_cumu_compaction_task_row_num_threshold",
1099
0
                                         config::large_cumu_compaction_task_row_num_threshold)
1100
0
                                    .tag("remaining threads",
1101
0
                                         _cumu_compaction_thread_pool_used_threads)
1102
0
                                    .tag("small_tasks_running",
1103
0
                                         _cumu_compaction_thread_pool_small_tasks_running);
1104
                            // Delay this task and sleep 5s for this tablet
1105
0
                            long now = duration_cast<std::chrono::milliseconds>(
1106
0
                                               std::chrono::system_clock::now().time_since_epoch())
1107
0
                                               .count();
1108
0
                            tablet->set_last_cumu_compaction_failure_time(now);
1109
0
                            return;
1110
0
                        }
1111
0
                    }
1112
2
                }
1113
2
            } while (false);
1114
2
            if (!tablet->can_do_compaction(tablet->data_dir()->path_hash(), compaction_type)) {
1115
0
                LOG(INFO) << "Tablet state has been changed, no need to begin this compaction "
1116
0
                             "task, tablet_id="
1117
0
                          << tablet->tablet_id() << ", tablet_state=" << tablet->tablet_state();
1118
0
                return;
1119
0
            }
1120
2
            tablet->compaction_stage = CompactionStage::EXECUTING;
1121
2
            TEST_SYNC_POINT_RETURN_WITH_VOID("olap_server::execute_compaction");
1122
0
            tablet->execute_compaction(*compaction);
1123
0
        });
1124
10
        if (!st.ok()) {
1125
0
            if (!force) {
1126
0
                _permit_limiter.release(permits);
1127
0
            }
1128
0
            _pop_tablet_from_submitted_compaction(tablet, compaction_type);
1129
0
            tablet->compaction_stage = CompactionStage::NOT_SCHEDULED;
1130
0
            return Status::InternalError(
1131
0
                    "failed to submit compaction task to thread pool, "
1132
0
                    "tablet_id={}, compaction_type={}.",
1133
0
                    tablet->tablet_id(), compaction_type);
1134
0
        }
1135
10
        return Status::OK();
1136
10
    } else {
1137
0
        _pop_tablet_from_submitted_compaction(tablet, compaction_type);
1138
0
        tablet->compaction_stage = CompactionStage::NOT_SCHEDULED;
1139
0
        if (!st.ok()) {
1140
0
            return Status::InternalError(
1141
0
                    "failed to prepare compaction task and calculate permits, "
1142
0
                    "tablet_id={}, compaction_type={}, "
1143
0
                    "permit={}, current_permit={}, status={}",
1144
0
                    tablet->tablet_id(), compaction_type, permits, _permit_limiter.usage(),
1145
0
                    st.to_string());
1146
0
        }
1147
0
        return st;
1148
0
    }
1149
10
}
1150
1151
Status StorageEngine::submit_compaction_task(TabletSharedPtr tablet, CompactionType compaction_type,
1152
0
                                             bool force, bool eager) {
1153
0
    if (!eager) {
1154
0
        DCHECK(compaction_type == CompactionType::BASE_COMPACTION ||
1155
0
               compaction_type == CompactionType::CUMULATIVE_COMPACTION);
1156
0
        auto compaction_registry_snapshot = _compaction_submit_registry.create_snapshot();
1157
0
        auto stores = get_stores();
1158
1159
0
        bool is_busy = std::none_of(
1160
0
                stores.begin(), stores.end(),
1161
0
                [&compaction_registry_snapshot, compaction_type](auto* data_dir) {
1162
0
                    return has_free_compaction_slot(
1163
0
                            &compaction_registry_snapshot, data_dir, compaction_type,
1164
0
                            compaction_registry_snapshot.count_executing_cumu_and_base(data_dir));
1165
0
                });
1166
0
        if (is_busy) {
1167
0
            LOG_EVERY_N(WARNING, 100)
1168
0
                    << "Too busy to submit a compaction task, tablet=" << tablet->get_table_id();
1169
0
            return Status::OK();
1170
0
        }
1171
0
    }
1172
0
    _update_cumulative_compaction_policy();
1173
    // alter table tableName set ("compaction_policy"="time_series")
1174
    // if atler table's compaction  policy, we need to modify tablet compaction policy shared ptr
1175
0
    if (tablet->get_cumulative_compaction_policy() == nullptr ||
1176
0
        tablet->get_cumulative_compaction_policy()->name() !=
1177
0
                tablet->tablet_meta()->compaction_policy()) {
1178
0
        tablet->set_cumulative_compaction_policy(
1179
0
                _cumulative_compaction_policies.at(tablet->tablet_meta()->compaction_policy()));
1180
0
    }
1181
0
    tablet->set_skip_compaction(false);
1182
0
    return _submit_compaction_task(tablet, compaction_type, force);
1183
0
}
1184
1185
Status StorageEngine::_handle_seg_compaction(std::shared_ptr<SegcompactionWorker> worker,
1186
                                             SegCompactionCandidatesSharedPtr segments,
1187
11
                                             uint64_t submission_time) {
1188
    // note: be aware that worker->_writer maybe released when the task is cancelled
1189
11
    uint64_t exec_queue_time = GetCurrentTimeMicros() - submission_time;
1190
11
    LOG(INFO) << "segcompaction thread pool queue time(ms): " << exec_queue_time / 1000;
1191
11
    worker->compact_segments(segments);
1192
    // return OK here. error will be reported via BetaRowsetWriter::_segcompaction_status
1193
11
    return Status::OK();
1194
11
}
1195
1196
Status StorageEngine::submit_seg_compaction_task(std::shared_ptr<SegcompactionWorker> worker,
1197
11
                                                 SegCompactionCandidatesSharedPtr segments) {
1198
11
    uint64_t submission_time = GetCurrentTimeMicros();
1199
11
    return _seg_compaction_thread_pool->submit_func([this, worker, segments, submission_time] {
1200
11
        static_cast<void>(_handle_seg_compaction(worker, segments, submission_time));
1201
11
    });
1202
11
}
1203
1204
0
Status StorageEngine::process_index_change_task(const TAlterInvertedIndexReq& request) {
1205
0
    auto tablet_id = request.tablet_id;
1206
0
    TabletSharedPtr tablet = _tablet_manager->get_tablet(tablet_id);
1207
0
    DBUG_EXECUTE_IF("StorageEngine::process_index_change_task_tablet_nullptr",
1208
0
                    { tablet = nullptr; })
1209
0
    if (tablet == nullptr) {
1210
0
        LOG(WARNING) << "tablet: " << tablet_id << " not exist";
1211
0
        return Status::InternalError("tablet not exist, tablet_id={}.", tablet_id);
1212
0
    }
1213
1214
0
    IndexBuilderSharedPtr index_builder = std::make_shared<IndexBuilder>(
1215
0
            *this, tablet, request.columns, request.alter_inverted_indexes, request.is_drop_op);
1216
0
    RETURN_IF_ERROR(_handle_index_change(index_builder));
1217
0
    return Status::OK();
1218
0
}
1219
1220
0
Status StorageEngine::_handle_index_change(IndexBuilderSharedPtr index_builder) {
1221
0
    RETURN_IF_ERROR(index_builder->init());
1222
0
    RETURN_IF_ERROR(index_builder->do_build_inverted_index());
1223
0
    return Status::OK();
1224
0
}
1225
1226
0
void StorageEngine::_cooldown_tasks_producer_callback() {
1227
0
    int64_t interval = config::generate_cooldown_task_interval_sec;
1228
    // the cooldown replica may be slow to upload it's meta file, so we should wait
1229
    // until it has done uploaded
1230
0
    int64_t skip_failed_interval = interval * 10;
1231
0
    do {
1232
        // these tables are ordered by priority desc
1233
0
        std::vector<TabletSharedPtr> tablets;
1234
0
        std::vector<RowsetSharedPtr> rowsets;
1235
        // TODO(luwei) : a more efficient way to get cooldown tablets
1236
0
        auto cur_time = time(nullptr);
1237
        // we should skip all the tablets which are not running and those pending to do cooldown
1238
        // also tablets once failed to do follow cooldown
1239
0
        auto skip_tablet = [this, skip_failed_interval,
1240
0
                            cur_time](const TabletSharedPtr& tablet) -> bool {
1241
0
            bool is_skip =
1242
0
                    cur_time - tablet->last_failed_follow_cooldown_time() < skip_failed_interval ||
1243
0
                    TABLET_RUNNING != tablet->tablet_state();
1244
0
            if (is_skip) {
1245
0
                return is_skip;
1246
0
            }
1247
0
            std::lock_guard<std::mutex> lock(_running_cooldown_mutex);
1248
0
            return _running_cooldown_tablets.find(tablet->tablet_id()) !=
1249
0
                   _running_cooldown_tablets.end();
1250
0
        };
1251
0
        _tablet_manager->get_cooldown_tablets(&tablets, &rowsets, std::move(skip_tablet));
1252
0
        LOG(INFO) << "cooldown producer get tablet num: " << tablets.size();
1253
0
        int max_priority = tablets.size();
1254
0
        int index = 0;
1255
0
        for (const auto& tablet : tablets) {
1256
0
            {
1257
0
                std::lock_guard<std::mutex> lock(_running_cooldown_mutex);
1258
0
                _running_cooldown_tablets.insert(tablet->tablet_id());
1259
0
            }
1260
0
            PriorityThreadPool::Task task;
1261
0
            RowsetSharedPtr rowset = std::move(rowsets[index++]);
1262
0
            task.work_function = [tablet, rowset, task_size = tablets.size(), this]() {
1263
0
                Status st = tablet->cooldown(rowset);
1264
0
                {
1265
0
                    std::lock_guard<std::mutex> lock(_running_cooldown_mutex);
1266
0
                    _running_cooldown_tablets.erase(tablet->tablet_id());
1267
0
                }
1268
0
                if (!st.ok()) {
1269
0
                    LOG(WARNING) << "failed to cooldown, tablet: " << tablet->tablet_id()
1270
0
                                 << " err: " << st;
1271
0
                } else {
1272
0
                    LOG(INFO) << "succeed to cooldown, tablet: " << tablet->tablet_id()
1273
0
                              << " cooldown progress ("
1274
0
                              << task_size - _cooldown_thread_pool->get_queue_size() << "/"
1275
0
                              << task_size << ")";
1276
0
                }
1277
0
            };
1278
0
            task.priority = max_priority--;
1279
0
            bool submited = _cooldown_thread_pool->offer(std::move(task));
1280
1281
0
            if (!submited) {
1282
0
                LOG(INFO) << "failed to submit cooldown task";
1283
0
            }
1284
0
        }
1285
0
    } while (!_stop_background_threads_latch.wait_for(std::chrono::seconds(interval)));
1286
0
}
1287
1288
0
void StorageEngine::_remove_unused_remote_files_callback() {
1289
0
    while (!_stop_background_threads_latch.wait_for(
1290
0
            std::chrono::seconds(config::remove_unused_remote_files_interval_sec))) {
1291
0
        LOG(INFO) << "begin to remove unused remote files";
1292
0
        do_remove_unused_remote_files();
1293
0
    }
1294
0
}
1295
1296
0
void StorageEngine::do_remove_unused_remote_files() {
1297
0
    auto tablets = tablet_manager()->get_all_tablet([](Tablet* t) {
1298
0
        return t->tablet_meta()->cooldown_meta_id().initialized() && t->is_used() &&
1299
0
               t->tablet_state() == TABLET_RUNNING &&
1300
0
               t->cooldown_conf_unlocked().cooldown_replica_id == t->replica_id();
1301
0
    });
1302
0
    TConfirmUnusedRemoteFilesRequest req;
1303
0
    req.__isset.confirm_list = true;
1304
    // tablet_id -> [storage_resource, unused_remote_files]
1305
0
    using unused_remote_files_buffer_t =
1306
0
            std::unordered_map<int64_t, std::pair<StorageResource, std::vector<io::FileInfo>>>;
1307
0
    unused_remote_files_buffer_t buffer;
1308
0
    int64_t num_files_in_buffer = 0;
1309
    // assume a filename is 0.1KB, buffer size should not larger than 100MB
1310
0
    constexpr int64_t max_files_in_buffer = 1000000;
1311
1312
0
    auto calc_unused_remote_files = [&req, &buffer, &num_files_in_buffer, this](Tablet* t) {
1313
0
        auto storage_resource = get_resource_by_storage_policy_id(t->storage_policy_id());
1314
0
        if (!storage_resource) {
1315
0
            LOG(WARNING) << "encounter error when remove unused remote files, tablet_id="
1316
0
                         << t->tablet_id() << " : " << storage_resource.error();
1317
0
            return;
1318
0
        }
1319
1320
        // TODO(plat1ko): Support path v1
1321
0
        if (storage_resource->path_version > 0) {
1322
0
            return;
1323
0
        }
1324
1325
0
        std::vector<io::FileInfo> files;
1326
        // FIXME(plat1ko): What if user reset resource in storage policy to another resource?
1327
        //  Maybe we should also list files in previously uploaded resources.
1328
0
        bool exists = true;
1329
0
        auto st = storage_resource->fs->list(storage_resource->remote_tablet_path(t->tablet_id()),
1330
0
                                             true, &files, &exists);
1331
0
        if (!st.ok()) {
1332
0
            LOG(WARNING) << "encounter error when remove unused remote files, tablet_id="
1333
0
                         << t->tablet_id() << " : " << st;
1334
0
            return;
1335
0
        }
1336
0
        if (!exists || files.empty()) {
1337
0
            return;
1338
0
        }
1339
        // get all cooldowned rowsets
1340
0
        RowsetIdUnorderedSet cooldowned_rowsets;
1341
0
        UniqueId cooldown_meta_id;
1342
0
        {
1343
0
            std::shared_lock rlock(t->get_header_lock());
1344
0
            for (auto&& rs_meta : t->tablet_meta()->all_rs_metas()) {
1345
0
                if (!rs_meta->is_local()) {
1346
0
                    cooldowned_rowsets.insert(rs_meta->rowset_id());
1347
0
                }
1348
0
            }
1349
0
            if (cooldowned_rowsets.empty()) {
1350
0
                return;
1351
0
            }
1352
0
            cooldown_meta_id = t->tablet_meta()->cooldown_meta_id();
1353
0
        }
1354
0
        auto [cooldown_term, cooldown_replica_id] = t->cooldown_conf();
1355
0
        if (cooldown_replica_id != t->replica_id()) {
1356
0
            return;
1357
0
        }
1358
        // {cooldown_replica_id}.{cooldown_term}.meta
1359
0
        std::string remote_meta_path =
1360
0
                cooldown_tablet_meta_filename(cooldown_replica_id, cooldown_term);
1361
        // filter out the paths that should be reserved
1362
0
        auto filter = [&, this](io::FileInfo& info) {
1363
0
            std::string_view filename = info.file_name;
1364
0
            if (filename.ends_with(".meta")) {
1365
0
                return filename == remote_meta_path;
1366
0
            }
1367
0
            auto rowset_id = extract_rowset_id(filename);
1368
0
            if (rowset_id.hi == 0) {
1369
0
                return false;
1370
0
            }
1371
0
            return cooldowned_rowsets.contains(rowset_id) ||
1372
0
                   pending_remote_rowsets().contains(rowset_id);
1373
0
        };
1374
0
        files.erase(std::remove_if(files.begin(), files.end(), std::move(filter)), files.end());
1375
0
        if (files.empty()) {
1376
0
            return;
1377
0
        }
1378
0
        files.shrink_to_fit();
1379
0
        num_files_in_buffer += files.size();
1380
0
        buffer.insert({t->tablet_id(), {*storage_resource, std::move(files)}});
1381
0
        auto& info = req.confirm_list.emplace_back();
1382
0
        info.__set_tablet_id(t->tablet_id());
1383
0
        info.__set_cooldown_replica_id(cooldown_replica_id);
1384
0
        info.__set_cooldown_meta_id(cooldown_meta_id.to_thrift());
1385
0
    };
1386
1387
0
    auto confirm_and_remove_files = [&buffer, &req, &num_files_in_buffer]() {
1388
0
        TConfirmUnusedRemoteFilesResult result;
1389
0
        LOG(INFO) << "begin to confirm unused remote files. num_tablets=" << buffer.size()
1390
0
                  << " num_files=" << num_files_in_buffer;
1391
0
        auto st = MasterServerClient::instance()->confirm_unused_remote_files(req, &result);
1392
0
        if (!st.ok()) {
1393
0
            LOG(WARNING) << st;
1394
0
            return;
1395
0
        }
1396
0
        for (auto id : result.confirmed_tablets) {
1397
0
            if (auto it = buffer.find(id); LIKELY(it != buffer.end())) {
1398
0
                auto& storage_resource = it->second.first;
1399
0
                auto& files = it->second.second;
1400
0
                std::vector<io::Path> paths;
1401
0
                paths.reserve(files.size());
1402
                // delete unused files
1403
0
                LOG(INFO) << "delete unused files. root_path=" << storage_resource.fs->root_path()
1404
0
                          << " tablet_id=" << id;
1405
0
                io::Path dir = storage_resource.remote_tablet_path(id);
1406
0
                for (auto& file : files) {
1407
0
                    auto file_path = dir / file.file_name;
1408
0
                    LOG(INFO) << "delete unused file: " << file_path.native();
1409
0
                    paths.push_back(std::move(file_path));
1410
0
                }
1411
0
                st = storage_resource.fs->batch_delete(paths);
1412
0
                if (!st.ok()) {
1413
0
                    LOG(WARNING) << "failed to delete unused files, tablet_id=" << id << " : "
1414
0
                                 << st;
1415
0
                }
1416
0
                buffer.erase(it);
1417
0
            }
1418
0
        }
1419
0
    };
1420
1421
    // batch confirm to reduce FE's overhead
1422
0
    auto next_confirm_time = std::chrono::steady_clock::now() +
1423
0
                             std::chrono::seconds(config::confirm_unused_remote_files_interval_sec);
1424
0
    for (auto& t : tablets) {
1425
0
        if (t.use_count() <= 1 // this means tablet has been dropped
1426
0
            || t->cooldown_conf_unlocked().cooldown_replica_id != t->replica_id() ||
1427
0
            t->tablet_state() != TABLET_RUNNING) {
1428
0
            continue;
1429
0
        }
1430
0
        calc_unused_remote_files(t.get());
1431
0
        if (num_files_in_buffer > 0 && (num_files_in_buffer > max_files_in_buffer ||
1432
0
                                        std::chrono::steady_clock::now() > next_confirm_time)) {
1433
0
            confirm_and_remove_files();
1434
0
            buffer.clear();
1435
0
            req.confirm_list.clear();
1436
0
            num_files_in_buffer = 0;
1437
0
            next_confirm_time =
1438
0
                    std::chrono::steady_clock::now() +
1439
0
                    std::chrono::seconds(config::confirm_unused_remote_files_interval_sec);
1440
0
        }
1441
0
    }
1442
0
    if (num_files_in_buffer > 0) {
1443
0
        confirm_and_remove_files();
1444
0
    }
1445
0
}
1446
1447
0
void StorageEngine::_cold_data_compaction_producer_callback() {
1448
0
    while (!_stop_background_threads_latch.wait_for(
1449
0
            std::chrono::seconds(config::cold_data_compaction_interval_sec))) {
1450
0
        if (config::disable_auto_compaction ||
1451
0
            GlobalMemoryArbitrator::is_exceed_soft_mem_limit(GB_EXCHANGE_BYTE)) {
1452
0
            continue;
1453
0
        }
1454
1455
0
        std::unordered_set<int64_t> copied_tablet_submitted;
1456
0
        {
1457
0
            std::lock_guard lock(_cold_compaction_tablet_submitted_mtx);
1458
0
            copied_tablet_submitted = _cold_compaction_tablet_submitted;
1459
0
        }
1460
0
        int n = config::cold_data_compaction_thread_num - copied_tablet_submitted.size();
1461
0
        if (n <= 0) {
1462
0
            continue;
1463
0
        }
1464
0
        auto tablets = _tablet_manager->get_all_tablet([&copied_tablet_submitted](Tablet* t) {
1465
0
            return t->tablet_meta()->cooldown_meta_id().initialized() && t->is_used() &&
1466
0
                   t->tablet_state() == TABLET_RUNNING &&
1467
0
                   !copied_tablet_submitted.contains(t->tablet_id()) &&
1468
0
                   !t->tablet_meta()->tablet_schema()->disable_auto_compaction();
1469
0
        });
1470
0
        std::vector<std::pair<TabletSharedPtr, int64_t>> tablet_to_compact;
1471
0
        tablet_to_compact.reserve(n + 1);
1472
0
        std::vector<std::pair<TabletSharedPtr, int64_t>> tablet_to_follow;
1473
0
        tablet_to_follow.reserve(n + 1);
1474
1475
0
        for (auto& t : tablets) {
1476
0
            if (t->replica_id() == t->cooldown_conf_unlocked().cooldown_replica_id) {
1477
0
                auto score = t->calc_cold_data_compaction_score();
1478
0
                if (score < 4) {
1479
0
                    continue;
1480
0
                }
1481
0
                tablet_to_compact.emplace_back(t, score);
1482
0
                if (tablet_to_compact.size() > n) {
1483
0
                    std::sort(tablet_to_compact.begin(), tablet_to_compact.end(),
1484
0
                              [](auto& a, auto& b) { return a.second > b.second; });
1485
0
                    tablet_to_compact.pop_back();
1486
0
                }
1487
0
                continue;
1488
0
            }
1489
            // else, need to follow
1490
0
            {
1491
0
                std::lock_guard lock(_running_cooldown_mutex);
1492
0
                if (_running_cooldown_tablets.contains(t->table_id())) {
1493
                    // already in cooldown queue
1494
0
                    continue;
1495
0
                }
1496
0
            }
1497
            // TODO(plat1ko): some avoidance strategy if failed to follow
1498
0
            auto score = t->calc_cold_data_compaction_score();
1499
0
            tablet_to_follow.emplace_back(t, score);
1500
1501
0
            if (tablet_to_follow.size() > n) {
1502
0
                std::sort(tablet_to_follow.begin(), tablet_to_follow.end(),
1503
0
                          [](auto& a, auto& b) { return a.second > b.second; });
1504
0
                tablet_to_follow.pop_back();
1505
0
            }
1506
0
        }
1507
1508
0
        for (auto& [tablet, score] : tablet_to_compact) {
1509
0
            LOG(INFO) << "submit cold data compaction. tablet_id=" << tablet->tablet_id()
1510
0
                      << " score=" << score;
1511
0
            static_cast<void>(_cold_data_compaction_thread_pool->submit_func(
1512
0
                    [&, t = std::move(tablet), this]() {
1513
0
                        auto compaction = std::make_shared<ColdDataCompaction>(*this, t);
1514
0
                        {
1515
0
                            std::lock_guard lock(_cold_compaction_tablet_submitted_mtx);
1516
0
                            _cold_compaction_tablet_submitted.insert(t->tablet_id());
1517
0
                        }
1518
0
                        Defer defer {[&] {
1519
0
                            std::lock_guard lock(_cold_compaction_tablet_submitted_mtx);
1520
0
                            _cold_compaction_tablet_submitted.erase(t->tablet_id());
1521
0
                        }};
1522
0
                        std::unique_lock cold_compaction_lock(t->get_cold_compaction_lock(),
1523
0
                                                              std::try_to_lock);
1524
0
                        if (!cold_compaction_lock.owns_lock()) {
1525
0
                            LOG(WARNING) << "try cold_compaction_lock failed, tablet_id="
1526
0
                                         << t->tablet_id();
1527
0
                            return;
1528
0
                        }
1529
0
                        if (t->get_cumulative_compaction_policy() == nullptr ||
1530
0
                            t->get_cumulative_compaction_policy()->name() !=
1531
0
                                    t->tablet_meta()->compaction_policy()) {
1532
0
                            t->set_cumulative_compaction_policy(_cumulative_compaction_policies.at(
1533
0
                                    t->tablet_meta()->compaction_policy()));
1534
0
                        }
1535
1536
0
                        auto st = compaction->prepare_compact();
1537
0
                        if (!st.ok()) {
1538
0
                            LOG(WARNING) << "failed to prepare cold data compaction. tablet_id="
1539
0
                                         << t->tablet_id() << " err=" << st;
1540
0
                            return;
1541
0
                        }
1542
1543
0
                        st = compaction->execute_compact();
1544
0
                        if (!st.ok()) {
1545
0
                            LOG(WARNING) << "failed to execute cold data compaction. tablet_id="
1546
0
                                         << t->tablet_id() << " err=" << st;
1547
0
                            return;
1548
0
                        }
1549
0
                    }));
1550
0
        }
1551
1552
0
        for (auto& [tablet, score] : tablet_to_follow) {
1553
0
            LOG(INFO) << "submit to follow cooldown meta. tablet_id=" << tablet->tablet_id()
1554
0
                      << " score=" << score;
1555
0
            static_cast<void>(_cold_data_compaction_thread_pool->submit_func([&,
1556
0
                                                                              t = std::move(
1557
0
                                                                                      tablet)]() {
1558
0
                {
1559
0
                    std::lock_guard lock(_cold_compaction_tablet_submitted_mtx);
1560
0
                    _cold_compaction_tablet_submitted.insert(t->tablet_id());
1561
0
                }
1562
0
                auto st = t->cooldown();
1563
0
                {
1564
0
                    std::lock_guard lock(_cold_compaction_tablet_submitted_mtx);
1565
0
                    _cold_compaction_tablet_submitted.erase(t->tablet_id());
1566
0
                }
1567
0
                if (!st.ok()) {
1568
                    // The cooldown of the replica may be relatively slow
1569
                    // resulting in a short period of time where following cannot be successful
1570
0
                    LOG_EVERY_N(WARNING, 5)
1571
0
                            << "failed to cooldown. tablet_id=" << t->tablet_id() << " err=" << st;
1572
0
                }
1573
0
            }));
1574
0
        }
1575
0
    }
1576
0
}
1577
1578
void StorageEngine::add_async_publish_task(int64_t partition_id, int64_t tablet_id,
1579
                                           int64_t publish_version, int64_t transaction_id,
1580
2.05k
                                           bool is_recovery) {
1581
2.05k
    if (!is_recovery) {
1582
2.05k
        bool exists = false;
1583
2.05k
        {
1584
2.05k
            std::shared_lock<std::shared_mutex> rlock(_async_publish_lock);
1585
2.05k
            if (auto tablet_iter = _async_publish_tasks.find(tablet_id);
1586
2.05k
                tablet_iter != _async_publish_tasks.end()) {
1587
2.05k
                if (auto iter = tablet_iter->second.find(publish_version);
1588
2.05k
                    iter != tablet_iter->second.end()) {
1589
20
                    exists = true;
1590
20
                }
1591
2.05k
            }
1592
2.05k
        }
1593
2.05k
        if (exists) {
1594
20
            return;
1595
20
        }
1596
2.03k
        TabletSharedPtr tablet = tablet_manager()->get_tablet(tablet_id);
1597
2.03k
        if (tablet == nullptr) {
1598
0
            LOG(INFO) << "tablet may be dropped when add async publish task, tablet_id: "
1599
0
                      << tablet_id;
1600
0
            return;
1601
0
        }
1602
2.03k
        PendingPublishInfoPB pending_publish_info_pb;
1603
2.03k
        pending_publish_info_pb.set_partition_id(partition_id);
1604
2.03k
        pending_publish_info_pb.set_transaction_id(transaction_id);
1605
2.03k
        static_cast<void>(TabletMetaManager::save_pending_publish_info(
1606
2.03k
                tablet->data_dir(), tablet->tablet_id(), publish_version,
1607
2.03k
                pending_publish_info_pb.SerializeAsString()));
1608
2.03k
    }
1609
2.03k
    LOG(INFO) << "add pending publish task, tablet_id: " << tablet_id
1610
2.03k
              << " version: " << publish_version << " txn_id:" << transaction_id
1611
2.03k
              << " is_recovery: " << is_recovery;
1612
2.03k
    std::unique_lock<std::shared_mutex> wlock(_async_publish_lock);
1613
2.03k
    _async_publish_tasks[tablet_id][publish_version] = {transaction_id, partition_id};
1614
2.03k
}
1615
1616
3
int64_t StorageEngine::get_pending_publish_min_version(int64_t tablet_id) {
1617
3
    std::shared_lock<std::shared_mutex> rlock(_async_publish_lock);
1618
3
    auto iter = _async_publish_tasks.find(tablet_id);
1619
3
    if (iter == _async_publish_tasks.end()) {
1620
0
        return INT64_MAX;
1621
0
    }
1622
3
    if (iter->second.empty()) {
1623
0
        return INT64_MAX;
1624
0
    }
1625
3
    return iter->second.begin()->first;
1626
3
}
1627
1628
10
void StorageEngine::_process_async_publish() {
1629
    // tablet, publish_version
1630
10
    std::vector<std::pair<TabletSharedPtr, int64_t>> need_removed_tasks;
1631
10
    {
1632
10
        std::unique_lock<std::shared_mutex> wlock(_async_publish_lock);
1633
10
        for (auto tablet_iter = _async_publish_tasks.begin();
1634
20
             tablet_iter != _async_publish_tasks.end();) {
1635
10
            if (tablet_iter->second.empty()) {
1636
1
                tablet_iter = _async_publish_tasks.erase(tablet_iter);
1637
1
                continue;
1638
1
            }
1639
9
            int64_t tablet_id = tablet_iter->first;
1640
9
            TabletSharedPtr tablet = tablet_manager()->get_tablet(tablet_id);
1641
9
            if (!tablet) {
1642
1
                LOG(WARNING) << "tablet does not exist when async publush, tablet_id: "
1643
1
                             << tablet_id;
1644
1
                tablet_iter = _async_publish_tasks.erase(tablet_iter);
1645
1
                continue;
1646
1
            }
1647
1648
8
            auto task_iter = tablet_iter->second.begin();
1649
8
            int64_t version = task_iter->first;
1650
8
            int64_t transaction_id = task_iter->second.first;
1651
8
            int64_t partition_id = task_iter->second.second;
1652
8
            int64_t max_version = tablet->max_version().second;
1653
1654
8
            if (version <= max_version) {
1655
6
                need_removed_tasks.emplace_back(tablet, version);
1656
6
                tablet_iter->second.erase(task_iter);
1657
6
                tablet_iter++;
1658
6
                continue;
1659
6
            }
1660
2
            if (version != max_version + 1) {
1661
                // Keep only the most recent versions
1662
31
                while (tablet_iter->second.size() > config::max_tablet_version_num) {
1663
30
                    need_removed_tasks.emplace_back(tablet, version);
1664
30
                    task_iter = tablet_iter->second.erase(task_iter);
1665
30
                    version = task_iter->first;
1666
30
                }
1667
1
                tablet_iter++;
1668
1
                continue;
1669
1
            }
1670
1671
1
            auto async_publish_task = std::make_shared<AsyncTabletPublishTask>(
1672
1
                    *this, tablet, partition_id, transaction_id, version);
1673
1
            static_cast<void>(_tablet_publish_txn_thread_pool->submit_func(
1674
1
                    [=]() { async_publish_task->handle(); }));
1675
1
            tablet_iter->second.erase(task_iter);
1676
1
            need_removed_tasks.emplace_back(tablet, version);
1677
1
            tablet_iter++;
1678
1
        }
1679
10
    }
1680
37
    for (auto& [tablet, publish_version] : need_removed_tasks) {
1681
37
        static_cast<void>(TabletMetaManager::remove_pending_publish_info(
1682
37
                tablet->data_dir(), tablet->tablet_id(), publish_version));
1683
37
    }
1684
10
}
1685
1686
0
void StorageEngine::_async_publish_callback() {
1687
0
    while (!_stop_background_threads_latch.wait_for(std::chrono::milliseconds(30))) {
1688
0
        _process_async_publish();
1689
0
    }
1690
0
}
1691
1692
0
void StorageEngine::_check_tablet_delete_bitmap_score_callback() {
1693
0
    LOG(INFO) << "try to start check tablet delete bitmap score!";
1694
0
    while (!_stop_background_threads_latch.wait_for(
1695
0
            std::chrono::seconds(config::check_tablet_delete_bitmap_interval_seconds))) {
1696
0
        if (!config::enable_check_tablet_delete_bitmap_score) {
1697
0
            return;
1698
0
        }
1699
0
        uint64_t max_delete_bitmap_score = 0;
1700
0
        uint64_t max_base_rowset_delete_bitmap_score = 0;
1701
0
        std::vector<CloudTabletSPtr> tablets;
1702
0
        _tablet_manager.get()->get_topn_tablet_delete_bitmap_score(
1703
0
                &max_delete_bitmap_score, &max_base_rowset_delete_bitmap_score);
1704
0
        if (max_delete_bitmap_score > 0) {
1705
0
            _tablet_max_delete_bitmap_score_metrics->set_value(max_delete_bitmap_score);
1706
0
        }
1707
0
        if (max_base_rowset_delete_bitmap_score > 0) {
1708
0
            _tablet_max_base_rowset_delete_bitmap_score_metrics->set_value(
1709
0
                    max_base_rowset_delete_bitmap_score);
1710
0
        }
1711
0
    }
1712
0
}
1713
1714
} // namespace doris