Coverage Report

Created: 2026-04-16 20:39

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/storage/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 "storage/storage_engine.h"
19
20
// IWYU pragma: no_include <bthread/errno.h>
21
#include <fmt/format.h>
22
#include <gen_cpp/AgentService_types.h>
23
#include <gen_cpp/FrontendService.h>
24
#include <gen_cpp/Types_types.h>
25
#include <glog/logging.h>
26
#include <rapidjson/document.h>
27
#include <rapidjson/encodings.h>
28
#include <rapidjson/prettywriter.h>
29
#include <rapidjson/stringbuffer.h>
30
#include <sys/resource.h>
31
#include <thrift/protocol/TDebugProtocol.h>
32
33
#include <algorithm>
34
#include <boost/algorithm/string/case_conv.hpp>
35
#include <boost/container/detail/std_fwd.hpp>
36
#include <cassert>
37
#include <cerrno> // IWYU pragma: keep
38
#include <chrono>
39
#include <cstdlib>
40
#include <cstring>
41
#include <filesystem>
42
#include <iterator>
43
#include <memory>
44
#include <mutex>
45
#include <ostream>
46
#include <set>
47
#include <thread>
48
#include <unordered_set>
49
#include <utility>
50
51
#include "agent/task_worker_pool.h"
52
#include "cloud/cloud_storage_engine.h"
53
#include "common/config.h"
54
#include "common/logging.h"
55
#include "common/metrics/doris_metrics.h"
56
#include "common/metrics/metrics.h"
57
#include "common/status.h"
58
#include "core/assert_cast.h"
59
#include "io/fs/local_file_system.h"
60
#include "load/memtable/memtable_flush_executor.h"
61
#include "load/stream_load/stream_load_recorder.h"
62
#include "runtime/exec_env.h"
63
#include "storage/binlog.h"
64
#include "storage/compaction/single_replica_compaction.h"
65
#include "storage/data_dir.h"
66
#include "storage/id_manager.h"
67
#include "storage/olap_common.h"
68
#include "storage/olap_define.h"
69
#include "storage/rowset/rowset_fwd.h"
70
#include "storage/rowset/rowset_meta.h"
71
#include "storage/rowset/rowset_meta_manager.h"
72
#include "storage/rowset/unique_rowset_id_generator.h"
73
#include "storage/snapshot/snapshot_manager.h"
74
#include "storage/tablet/tablet_manager.h"
75
#include "storage/tablet/tablet_meta.h"
76
#include "storage/tablet/tablet_meta_manager.h"
77
#include "storage/txn/txn_manager.h"
78
#include "util/client_cache.h"
79
#include "util/mem_info.h"
80
#include "util/stopwatch.hpp"
81
#include "util/thread.h"
82
#include "util/threadpool.h"
83
#include "util/thrift_rpc_helper.h"
84
#include "util/uid_util.h"
85
#include "util/work_thread_pool.hpp"
86
87
using std::filesystem::directory_iterator;
88
using std::filesystem::path;
89
using std::map;
90
using std::set;
91
using std::string;
92
using std::stringstream;
93
using std::vector;
94
95
namespace doris {
96
using namespace ErrorCode;
97
extern void get_round_robin_stores(int64_t curr_index, const std::vector<DirInfo>& dir_infos,
98
                                   std::vector<DataDir*>& stores);
99
DEFINE_GAUGE_METRIC_PROTOTYPE_2ARG(unused_rowsets_count, MetricUnit::ROWSETS);
100
bvar::Status<int64_t> g_max_rowsets_with_useless_delete_bitmap(
101
        "max_rowsets_with_useless_delete_bitmap", 0);
102
bvar::Status<int64_t> g_max_rowsets_with_useless_delete_bitmap_version(
103
        "max_rowsets_with_useless_delete_bitmap_version", 0);
104
105
namespace {
106
bvar::Adder<uint64_t> unused_rowsets_counter("ununsed_rowsets_counter");
107
};
108
109
BaseStorageEngine::BaseStorageEngine(Type type, const UniqueId& backend_uid)
110
502
        : _type(type),
111
502
          _rowset_id_generator(std::make_unique<UniqueRowsetIdGenerator>(backend_uid)),
112
502
          _stop_background_threads_latch(1) {
113
502
    _memory_limitation_bytes_for_schema_change = static_cast<int64_t>(
114
502
            static_cast<double>(MemInfo::soft_mem_limit()) * config::schema_change_mem_limit_frac);
115
502
    _tablet_max_delete_bitmap_score_metrics =
116
502
            std::make_shared<bvar::Status<size_t>>("tablet_max", "delete_bitmap_score", 0);
117
502
    _tablet_max_base_rowset_delete_bitmap_score_metrics = std::make_shared<bvar::Status<size_t>>(
118
502
            "tablet_max_base_rowset", "delete_bitmap_score", 0);
119
502
}
120
121
502
BaseStorageEngine::~BaseStorageEngine() = default;
122
123
12.0k
RowsetId BaseStorageEngine::next_rowset_id() {
124
12.0k
    return _rowset_id_generator->next_id();
125
12.0k
}
126
127
47
StorageEngine& BaseStorageEngine::to_local() {
128
47
    CHECK_EQ(_type, Type::LOCAL);
129
47
    return *static_cast<StorageEngine*>(this);
130
47
}
131
132
0
CloudStorageEngine& BaseStorageEngine::to_cloud() {
133
0
    CHECK_EQ(_type, Type::CLOUD);
134
0
    return *static_cast<CloudStorageEngine*>(this);
135
0
}
136
137
8
int64_t BaseStorageEngine::memory_limitation_bytes_per_thread_for_schema_change() const {
138
8
    return std::max(_memory_limitation_bytes_for_schema_change / config::alter_tablet_worker_count,
139
8
                    config::memory_limitation_per_thread_for_schema_change_bytes);
140
8
}
141
142
0
void BaseStorageEngine::_start_adaptive_thread_controller() {
143
0
    if (!config::enable_adaptive_flush_threads) {
144
0
        return;
145
0
    }
146
147
0
    auto* system_metrics = DorisMetrics::instance()->system_metrics();
148
0
    auto* s3_upload_pool = ExecEnv::GetInstance()->s3_file_upload_thread_pool();
149
150
0
    _adaptive_thread_controller.init(system_metrics, s3_upload_pool);
151
152
0
    if (_memtable_flush_executor) {
153
0
        auto* flush_pool = _memtable_flush_executor->flush_pool();
154
0
        auto* high_prio_pool = _memtable_flush_executor->high_prio_flush_pool();
155
0
        _adaptive_thread_controller.add("flush", {flush_pool, high_prio_pool},
156
0
                                        AdaptiveThreadPoolController::make_flush_adjust_func(
157
0
                                                &_adaptive_thread_controller, flush_pool),
158
0
                                        config::max_flush_thread_num_per_cpu,
159
0
                                        config::min_flush_thread_num_per_cpu);
160
0
    }
161
0
}
162
163
38
Status BaseStorageEngine::init_stream_load_recorder(const std::string& stream_load_record_path) {
164
38
    LOG(INFO) << "stream load record path: " << stream_load_record_path;
165
    // init stream load record rocksdb
166
38
    _stream_load_recorder = StreamLoadRecorder::create_shared(stream_load_record_path);
167
38
    if (_stream_load_recorder == nullptr) {
168
0
        RETURN_NOT_OK_STATUS_WITH_WARN(
169
0
                Status::MemoryAllocFailed("allocate memory for StreamLoadRecorder failed"),
170
0
                "new StreamLoadRecorder failed");
171
0
    }
172
38
    auto st = _stream_load_recorder->init();
173
38
    if (!st.ok()) {
174
0
        RETURN_NOT_OK_STATUS_WITH_WARN(
175
0
                Status::IOError("open StreamLoadRecorder rocksdb failed, path={}",
176
0
                                stream_load_record_path),
177
0
                "init StreamLoadRecorder failed");
178
0
    }
179
38
    return Status::OK();
180
38
}
181
182
0
void CompactionSubmitRegistry::jsonfy_compaction_status(std::string* result) {
183
0
    rapidjson::Document root;
184
0
    root.SetObject();
185
186
0
    auto add_node = [&root](const std::string& name, const Registry& registry) {
187
0
        rapidjson::Value compaction_name;
188
0
        compaction_name.SetString(name.c_str(), cast_set<uint32_t>(name.length()),
189
0
                                  root.GetAllocator());
190
0
        rapidjson::Document path_obj;
191
0
        path_obj.SetObject();
192
0
        for (const auto& it : registry) {
193
0
            const auto& dir = it.first->path();
194
0
            rapidjson::Value path_key;
195
0
            path_key.SetString(dir.c_str(), cast_set<uint32_t>(dir.length()), root.GetAllocator());
196
197
0
            rapidjson::Document arr;
198
0
            arr.SetArray();
199
200
0
            for (const auto& tablet : it.second) {
201
0
                rapidjson::Value tablet_id;
202
0
                auto tablet_id_str = std::to_string(tablet->tablet_id());
203
0
                tablet_id.SetString(tablet_id_str.c_str(),
204
0
                                    cast_set<uint32_t>(tablet_id_str.length()),
205
0
                                    root.GetAllocator());
206
0
                arr.PushBack(tablet_id, root.GetAllocator());
207
0
            }
208
0
            path_obj.AddMember(path_key, arr, root.GetAllocator());
209
0
        }
210
0
        root.AddMember(compaction_name, path_obj, root.GetAllocator());
211
0
    };
212
213
0
    std::unique_lock<std::mutex> l(_tablet_submitted_compaction_mutex);
214
0
    add_node("BaseCompaction", _tablet_submitted_base_compaction);
215
0
    add_node("CumulativeCompaction", _tablet_submitted_cumu_compaction);
216
0
    add_node("FullCompaction", _tablet_submitted_full_compaction);
217
218
0
    rapidjson::StringBuffer str_buf;
219
0
    rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(str_buf);
220
0
    root.Accept(writer);
221
0
    *result = std::string(str_buf.GetString());
222
0
}
223
224
38
static Status _validate_options(const EngineOptions& options) {
225
38
    if (options.store_paths.empty()) {
226
0
        return Status::InternalError("store paths is empty");
227
0
    }
228
38
    return Status::OK();
229
38
}
230
231
38
Status StorageEngine::open() {
232
38
    RETURN_IF_ERROR(_validate_options(_options));
233
38
    LOG(INFO) << "starting backend using uid:" << _options.backend_uid.to_string();
234
38
    RETURN_NOT_OK_STATUS_WITH_WARN(_open(), "open engine failed");
235
38
    LOG(INFO) << "success to init storage engine.";
236
38
    return Status::OK();
237
38
}
238
239
StorageEngine::StorageEngine(const EngineOptions& options)
240
343
        : BaseStorageEngine(Type::LOCAL, options.backend_uid),
241
343
          _options(options),
242
343
          _available_storage_medium_type_count(0),
243
343
          _is_all_cluster_id_exist(true),
244
343
          _stopped(false),
245
343
          _tablet_manager(new TabletManager(*this, config::tablet_map_shard_size)),
246
343
          _txn_manager(new TxnManager(*this, config::txn_map_shard_size, config::txn_shard_size)),
247
343
          _default_rowset_type(BETA_ROWSET),
248
343
          _create_tablet_idx_lru_cache(
249
343
                  new CreateTabletRRIdxCache(config::partition_disk_index_lru_size)),
250
343
          _snapshot_mgr(std::make_unique<SnapshotManager>(*this)) {
251
343
    REGISTER_HOOK_METRIC(unused_rowsets_count, [this]() {
252
        // std::lock_guard<std::mutex> lock(_gc_mutex);
253
343
        return _unused_rowsets.size();
254
343
    });
255
256
343
    _broken_paths = options.broken_paths;
257
343
}
258
259
343
StorageEngine::~StorageEngine() {
260
343
    stop();
261
343
}
262
263
38
static Status load_data_dirs(const std::vector<DataDir*>& data_dirs) {
264
38
    std::unique_ptr<ThreadPool> pool;
265
266
38
    int num_threads = config::load_data_dirs_threads;
267
38
    if (num_threads <= 0) {
268
38
        num_threads = cast_set<int>(data_dirs.size());
269
38
    }
270
271
38
    auto st = ThreadPoolBuilder("load_data_dir")
272
38
                      .set_min_threads(num_threads)
273
38
                      .set_max_threads(num_threads)
274
38
                      .build(&pool);
275
38
    CHECK(st.ok()) << st;
276
277
38
    std::mutex result_mtx;
278
38
    Status result;
279
280
45
    for (auto* data_dir : data_dirs) {
281
45
        st = pool->submit_func([&, data_dir] {
282
45
            SCOPED_INIT_THREAD_CONTEXT();
283
45
            {
284
45
                std::lock_guard lock(result_mtx);
285
45
                if (!result.ok()) { // Some data dir has failed
286
0
                    return;
287
0
                }
288
45
            }
289
290
45
            auto st = data_dir->load();
291
45
            if (!st.ok()) {
292
0
                LOG(WARNING) << "error occured when init load tables. res=" << st
293
0
                             << ", data dir=" << data_dir->path();
294
0
                std::lock_guard lock(result_mtx);
295
0
                result = std::move(st);
296
0
            }
297
45
        });
298
299
45
        if (!st.ok()) {
300
0
            return st;
301
0
        }
302
45
    }
303
304
38
    pool->wait();
305
306
38
    return result;
307
38
}
308
309
38
Status StorageEngine::_open() {
310
    // init store_map
311
38
    RETURN_NOT_OK_STATUS_WITH_WARN(_init_store_map(), "_init_store_map failed");
312
313
38
    _effective_cluster_id = config::cluster_id;
314
38
    RETURN_NOT_OK_STATUS_WITH_WARN(_check_all_root_path_cluster_id(), "fail to check cluster id");
315
316
38
    _update_storage_medium_type_count();
317
318
38
    RETURN_NOT_OK_STATUS_WITH_WARN(_check_file_descriptor_number(), "check fd number failed");
319
320
38
    auto dirs = get_stores();
321
38
    RETURN_IF_ERROR(load_data_dirs(dirs));
322
323
38
    _disk_num = cast_set<int>(dirs.size());
324
38
    _memtable_flush_executor = std::make_unique<MemTableFlushExecutor>();
325
38
    _memtable_flush_executor->init(_disk_num);
326
327
38
    _calc_delete_bitmap_executor = std::make_unique<CalcDeleteBitmapExecutor>();
328
38
    _calc_delete_bitmap_executor->init(config::calc_delete_bitmap_max_thread);
329
330
38
    _calc_delete_bitmap_executor_for_load = std::make_unique<CalcDeleteBitmapExecutor>();
331
38
    _calc_delete_bitmap_executor_for_load->init(
332
38
            config::calc_delete_bitmap_for_load_max_thread > 0
333
38
                    ? config::calc_delete_bitmap_for_load_max_thread
334
38
                    : std::max(1, CpuInfo::num_cores() / 2));
335
336
38
    _parse_default_rowset_type();
337
338
38
    return Status::OK();
339
38
}
340
341
38
Status StorageEngine::_init_store_map() {
342
38
    std::vector<std::thread> threads;
343
38
    std::mutex error_msg_lock;
344
38
    std::string error_msg;
345
45
    for (auto& path : _options.store_paths) {
346
45
        auto store = std::make_unique<DataDir>(*this, path.path, path.capacity_bytes,
347
45
                                               path.storage_medium);
348
45
        threads.emplace_back([store = store.get(), &error_msg_lock, &error_msg]() {
349
45
            SCOPED_INIT_THREAD_CONTEXT();
350
45
            auto st = store->init();
351
45
            if (!st.ok()) {
352
0
                {
353
0
                    std::lock_guard<std::mutex> l(error_msg_lock);
354
0
                    error_msg.append(st.to_string() + ";");
355
0
                }
356
0
                LOG(WARNING) << "Store load failed, status=" << st.to_string()
357
0
                             << ", path=" << store->path();
358
0
            }
359
45
        });
360
45
        _store_map.emplace(store->path(), std::move(store));
361
45
    }
362
45
    for (auto& thread : threads) {
363
45
        thread.join();
364
45
    }
365
366
    // All store paths MUST init successfully
367
38
    if (!error_msg.empty()) {
368
0
        return Status::InternalError("init path failed, error={}", error_msg);
369
0
    }
370
371
38
    RETURN_NOT_OK_STATUS_WITH_WARN(init_stream_load_recorder(_options.store_paths[0].path),
372
38
                                   "init StreamLoadRecorder failed");
373
374
38
    return Status::OK();
375
38
}
376
377
38
void StorageEngine::_update_storage_medium_type_count() {
378
38
    set<TStorageMedium::type> available_storage_medium_types;
379
380
38
    std::lock_guard<std::mutex> l(_store_lock);
381
45
    for (auto& it : _store_map) {
382
45
        if (it.second->is_used()) {
383
45
            available_storage_medium_types.insert(it.second->storage_medium());
384
45
        }
385
45
    }
386
387
38
    _available_storage_medium_type_count =
388
38
            cast_set<uint32_t>(available_storage_medium_types.size());
389
38
}
390
391
38
Status StorageEngine::_judge_and_update_effective_cluster_id(int32_t cluster_id) {
392
38
    if (cluster_id == -1 && _effective_cluster_id == -1) {
393
        // maybe this is a new cluster, cluster id will get from heartbeat message
394
38
        return Status::OK();
395
38
    } else if (cluster_id != -1 && _effective_cluster_id == -1) {
396
0
        _effective_cluster_id = cluster_id;
397
0
        return Status::OK();
398
0
    } else if (cluster_id == -1 && _effective_cluster_id != -1) {
399
        // _effective_cluster_id is the right effective cluster id
400
0
        return Status::OK();
401
0
    } else {
402
0
        if (cluster_id != _effective_cluster_id) {
403
0
            RETURN_NOT_OK_STATUS_WITH_WARN(
404
0
                    Status::Corruption("multiple cluster ids is not equal. one={}, other={}",
405
0
                                       _effective_cluster_id, cluster_id),
406
0
                    "cluster id not equal");
407
0
        }
408
0
    }
409
410
0
    return Status::OK();
411
38
}
412
413
50
std::vector<DataDir*> StorageEngine::get_stores(bool include_unused) {
414
50
    std::vector<DataDir*> stores;
415
50
    stores.reserve(_store_map.size());
416
417
50
    std::lock_guard<std::mutex> l(_store_lock);
418
50
    if (include_unused) {
419
4
        for (auto&& [_, store] : _store_map) {
420
3
            stores.push_back(store.get());
421
3
        }
422
46
    } else {
423
46
        for (auto&& [_, store] : _store_map) {
424
45
            if (store->is_used()) {
425
45
                stores.push_back(store.get());
426
45
            }
427
45
        }
428
46
    }
429
50
    return stores;
430
50
}
431
432
Status StorageEngine::get_all_data_dir_info(std::vector<DataDirInfo>* data_dir_infos,
433
0
                                            bool need_update) {
434
0
    Status res = Status::OK();
435
0
    data_dir_infos->clear();
436
437
0
    MonotonicStopWatch timer;
438
0
    timer.start();
439
440
    // 1. update available capacity of each data dir
441
    // get all root path info and construct a path map.
442
    // path -> DataDirInfo
443
0
    std::map<std::string, DataDirInfo> path_map;
444
0
    {
445
0
        std::lock_guard<std::mutex> l(_store_lock);
446
0
        for (auto& it : _store_map) {
447
0
            if (need_update) {
448
0
                RETURN_IF_ERROR(it.second->update_capacity());
449
0
            }
450
0
            path_map.emplace(it.first, it.second->get_dir_info());
451
0
        }
452
0
    }
453
454
    // 2. get total tablets' size of each data dir
455
0
    size_t tablet_count = 0;
456
0
    _tablet_manager->update_root_path_info(&path_map, &tablet_count);
457
458
    // 3. update metrics in DataDir
459
0
    for (auto& path : path_map) {
460
0
        std::lock_guard<std::mutex> l(_store_lock);
461
0
        auto data_dir = _store_map.find(path.first);
462
0
        DCHECK(data_dir != _store_map.end());
463
0
        data_dir->second->update_local_data_size(path.second.local_used_capacity);
464
0
        data_dir->second->update_remote_data_size(path.second.remote_used_capacity);
465
0
    }
466
467
    // add path info to data_dir_infos
468
0
    for (auto& entry : path_map) {
469
0
        data_dir_infos->emplace_back(entry.second);
470
0
    }
471
472
0
    timer.stop();
473
0
    LOG(INFO) << "get root path info cost: " << timer.elapsed_time() / 1000000
474
0
              << " ms. tablet counter: " << tablet_count;
475
476
0
    return res;
477
0
}
478
479
0
int64_t StorageEngine::get_file_or_directory_size(const std::string& file_path) {
480
0
    if (!std::filesystem::exists(file_path)) {
481
0
        return 0;
482
0
    }
483
0
    if (!std::filesystem::is_directory(file_path)) {
484
0
        return std::filesystem::file_size(file_path);
485
0
    }
486
0
    int64_t sum_size = 0;
487
0
    for (const auto& it : std::filesystem::directory_iterator(file_path)) {
488
0
        sum_size += get_file_or_directory_size(it.path());
489
0
    }
490
0
    return sum_size;
491
0
}
492
493
0
void StorageEngine::_start_disk_stat_monitor() {
494
0
    for (auto& it : _store_map) {
495
0
        it.second->health_check();
496
0
    }
497
498
0
    _update_storage_medium_type_count();
499
500
0
    _exit_if_too_many_disks_are_failed();
501
0
}
502
503
// TODO(lingbin): Should be in EnvPosix?
504
38
Status StorageEngine::_check_file_descriptor_number() {
505
38
    struct rlimit l;
506
38
    int ret = getrlimit(RLIMIT_NOFILE, &l);
507
38
    if (ret != 0) {
508
0
        LOG(WARNING) << "call getrlimit() failed. errno=" << strerror(errno)
509
0
                     << ", use default configuration instead.";
510
0
        return Status::OK();
511
0
    }
512
38
    if (getenv("SKIP_CHECK_ULIMIT") == nullptr) {
513
38
        LOG(INFO) << "will check 'ulimit' value.";
514
38
    } else if (std::string(getenv("SKIP_CHECK_ULIMIT")) == "true") {
515
0
        LOG(INFO) << "the 'ulimit' value check is skipped"
516
0
                  << ", the SKIP_CHECK_ULIMIT env value is " << getenv("SKIP_CHECK_ULIMIT");
517
0
        return Status::OK();
518
0
    } else {
519
0
        LOG(INFO) << "the SKIP_CHECK_ULIMIT env value is " << getenv("SKIP_CHECK_ULIMIT")
520
0
                  << ", will check ulimit value.";
521
0
    }
522
38
    if (l.rlim_cur < config::min_file_descriptor_number) {
523
0
        LOG(ERROR) << "File descriptor number is less than " << config::min_file_descriptor_number
524
0
                   << ". Please use (ulimit -n) to set a value equal or greater than "
525
0
                   << config::min_file_descriptor_number;
526
0
        return Status::Error<ErrorCode::EXCEEDED_LIMIT>(
527
0
                "file descriptors limit {} is small than {}", l.rlim_cur,
528
0
                config::min_file_descriptor_number);
529
0
    }
530
38
    return Status::OK();
531
38
}
532
533
38
Status StorageEngine::_check_all_root_path_cluster_id() {
534
38
    int32_t cluster_id = -1;
535
45
    for (auto& it : _store_map) {
536
45
        int32_t tmp_cluster_id = it.second->cluster_id();
537
45
        if (it.second->cluster_id_incomplete()) {
538
45
            _is_all_cluster_id_exist = false;
539
45
        } else if (tmp_cluster_id == cluster_id) {
540
            // both have right cluster id, do nothing
541
0
        } else if (cluster_id == -1) {
542
0
            cluster_id = tmp_cluster_id;
543
0
        } else {
544
0
            RETURN_NOT_OK_STATUS_WITH_WARN(
545
0
                    Status::Corruption("multiple cluster ids is not equal. one={}, other={}",
546
0
                                       cluster_id, tmp_cluster_id),
547
0
                    "cluster id not equal");
548
0
        }
549
45
    }
550
551
    // judge and get effective cluster id
552
38
    RETURN_IF_ERROR(_judge_and_update_effective_cluster_id(cluster_id));
553
554
    // write cluster id into cluster_id_path if get effective cluster id success
555
38
    if (_effective_cluster_id != -1 && !_is_all_cluster_id_exist) {
556
0
        RETURN_IF_ERROR(set_cluster_id(_effective_cluster_id));
557
0
    }
558
559
38
    return Status::OK();
560
38
}
561
562
0
Status StorageEngine::set_cluster_id(int32_t cluster_id) {
563
0
    std::lock_guard<std::mutex> l(_store_lock);
564
0
    for (auto& it : _store_map) {
565
0
        RETURN_IF_ERROR(it.second->set_cluster_id(cluster_id));
566
0
    }
567
0
    _effective_cluster_id = cluster_id;
568
0
    _is_all_cluster_id_exist = true;
569
0
    return Status::OK();
570
0
}
571
572
int StorageEngine::_get_and_set_next_disk_index(int64_t partition_id,
573
73
                                                TStorageMedium::type storage_medium) {
574
73
    auto key = CreateTabletRRIdxCache::get_key(partition_id, storage_medium);
575
73
    int curr_index = _create_tablet_idx_lru_cache->get_index(key);
576
    // -1, lru can't find key
577
73
    if (curr_index == -1) {
578
27
        curr_index = std::max(0, _last_use_index[storage_medium] + 1);
579
27
    }
580
73
    _last_use_index[storage_medium] = curr_index;
581
73
    _create_tablet_idx_lru_cache->set_index(key, std::max(0, curr_index + 1));
582
73
    return curr_index;
583
73
}
584
585
void StorageEngine::_get_candidate_stores(TStorageMedium::type storage_medium,
586
73
                                          std::vector<DirInfo>& dir_infos) {
587
73
    std::vector<double> usages;
588
74
    for (auto& it : _store_map) {
589
74
        DataDir* data_dir = it.second.get();
590
74
        if (data_dir->is_used()) {
591
74
            if ((_available_storage_medium_type_count == 1 ||
592
74
                 data_dir->storage_medium() == storage_medium) &&
593
74
                !data_dir->reach_capacity_limit(0)) {
594
74
                double usage = data_dir->get_usage(0);
595
74
                DirInfo dir_info;
596
74
                dir_info.data_dir = data_dir;
597
74
                dir_info.usage = usage;
598
74
                dir_info.available_level = 0;
599
74
                usages.push_back(usage);
600
74
                dir_infos.push_back(dir_info);
601
74
            }
602
74
        }
603
74
    }
604
605
73
    if (dir_infos.size() <= 1) {
606
72
        return;
607
72
    }
608
609
1
    std::sort(usages.begin(), usages.end());
610
1
    if (usages.back() < 0.7) {
611
1
        return;
612
1
    }
613
614
0
    std::vector<double> level_min_usages;
615
0
    level_min_usages.push_back(usages[0]);
616
0
    for (auto usage : usages) {
617
        // usage < 0.7 consider as one level, give a small skew
618
0
        if (usage < 0.7 - (config::high_disk_avail_level_diff_usages / 2.0)) {
619
0
            continue;
620
0
        }
621
622
        // at high usages,  default 15% is one level
623
        // for example: there disk usages are:   0.66,  0.72,  0.83
624
        // then level_min_usages = [0.66, 0.83], divide disks into 2 levels:  [0.66, 0.72], [0.83]
625
0
        if (usage >= level_min_usages.back() + config::high_disk_avail_level_diff_usages) {
626
0
            level_min_usages.push_back(usage);
627
0
        }
628
0
    }
629
0
    for (auto& dir_info : dir_infos) {
630
0
        double usage = dir_info.usage;
631
0
        for (size_t i = 1; i < level_min_usages.size() && usage >= level_min_usages[i]; i++) {
632
0
            dir_info.available_level++;
633
0
        }
634
635
        // when usage is too high, no matter consider balance now,
636
        // make it a higher level.
637
        // for example, two disks and usages are: 0.85 and 0.92, then let tablets fall on the first disk.
638
        // by default, storage_flood_stage_usage_percent = 90
639
0
        if (usage > config::storage_flood_stage_usage_percent / 100.0) {
640
0
            dir_info.available_level++;
641
0
        }
642
0
    }
643
0
}
644
645
std::vector<DataDir*> StorageEngine::get_stores_for_create_tablet(
646
73
        int64_t partition_id, TStorageMedium::type storage_medium) {
647
73
    std::vector<DirInfo> dir_infos;
648
73
    int curr_index = 0;
649
73
    std::vector<DataDir*> stores;
650
73
    {
651
73
        std::lock_guard<std::mutex> l(_store_lock);
652
73
        curr_index = _get_and_set_next_disk_index(partition_id, storage_medium);
653
73
        _get_candidate_stores(storage_medium, dir_infos);
654
73
    }
655
656
73
    std::sort(dir_infos.begin(), dir_infos.end());
657
73
    get_round_robin_stores(curr_index, dir_infos, stores);
658
659
73
    return stores;
660
73
}
661
662
// maintain in stores LOW,MID,HIGH level round robin
663
void get_round_robin_stores(int64_t curr_index, const std::vector<DirInfo>& dir_infos,
664
73
                            std::vector<DataDir*>& stores) {
665
146
    for (size_t i = 0; i < dir_infos.size();) {
666
73
        size_t end = i + 1;
667
74
        while (end < dir_infos.size() &&
668
74
               dir_infos[i].available_level == dir_infos[end].available_level) {
669
1
            end++;
670
1
        }
671
        // data dirs [i, end) have the same tablet size, round robin range [i, end)
672
73
        size_t count = end - i;
673
147
        for (size_t k = 0; k < count; k++) {
674
74
            size_t index = i + ((k + curr_index) % count);
675
74
            stores.push_back(dir_infos[index].data_dir);
676
74
        }
677
73
        i = end;
678
73
    }
679
73
}
680
681
4
DataDir* StorageEngine::get_store(const std::string& path) {
682
    // _store_map is unchanged, no need to lock
683
4
    auto it = _store_map.find(path);
684
4
    if (it == _store_map.end()) {
685
0
        return nullptr;
686
0
    }
687
4
    return it->second.get();
688
4
}
689
690
0
static bool too_many_disks_are_failed(uint32_t unused_num, uint32_t total_num) {
691
0
    return ((total_num == 0) ||
692
0
            (unused_num * 100 / total_num > config::max_percentage_of_error_disk));
693
0
}
694
695
0
void StorageEngine::_exit_if_too_many_disks_are_failed() {
696
0
    uint32_t unused_root_path_num = 0;
697
0
    uint32_t total_root_path_num = 0;
698
699
0
    {
700
        // TODO(yingchun): _store_map is only updated in main and ~StorageEngine, maybe we can remove it?
701
0
        std::lock_guard<std::mutex> l(_store_lock);
702
0
        if (_store_map.empty()) {
703
0
            return;
704
0
        }
705
706
0
        for (auto& it : _store_map) {
707
0
            ++total_root_path_num;
708
0
            if (it.second->is_used()) {
709
0
                continue;
710
0
            }
711
0
            ++unused_root_path_num;
712
0
        }
713
0
    }
714
715
0
    if (too_many_disks_are_failed(unused_root_path_num, total_root_path_num)) {
716
0
        LOG(FATAL) << "meet too many error disks, process exit. "
717
0
                   << "max_ratio_allowed=" << config::max_percentage_of_error_disk << "%"
718
0
                   << ", error_disk_count=" << unused_root_path_num
719
0
                   << ", total_disk_count=" << total_root_path_num;
720
0
        exit(0);
721
0
    }
722
0
}
723
724
343
void StorageEngine::stop() {
725
343
    if (_stopped) {
726
0
        LOG(WARNING) << "Storage engine is stopped twice.";
727
0
        return;
728
0
    }
729
    // trigger the waiting threads
730
343
    notify_listeners();
731
732
343
    {
733
343
        std::lock_guard<std::mutex> l(_store_lock);
734
343
        for (auto& store_pair : _store_map) {
735
45
            store_pair.second->stop_bg_worker();
736
45
        }
737
343
    }
738
739
343
    _stop_background_threads_latch.count_down();
740
343
#define THREAD_JOIN(thread) \
741
3.77k
    if (thread) {           \
742
3
        thread->join();     \
743
3
    }
744
745
343
    THREAD_JOIN(_compaction_tasks_producer_thread);
746
343
    THREAD_JOIN(_update_replica_infos_thread);
747
343
    THREAD_JOIN(_unused_rowset_monitor_thread);
748
343
    THREAD_JOIN(_garbage_sweeper_thread);
749
343
    THREAD_JOIN(_disk_stat_monitor_thread);
750
343
    THREAD_JOIN(_cache_clean_thread);
751
343
    THREAD_JOIN(_tablet_checkpoint_tasks_producer_thread);
752
343
    THREAD_JOIN(_async_publish_thread);
753
343
    THREAD_JOIN(_cold_data_compaction_producer_thread);
754
343
    THREAD_JOIN(_cooldown_tasks_producer_thread);
755
343
    THREAD_JOIN(_check_delete_bitmap_score_thread);
756
343
#undef THREAD_JOIN
757
758
343
#define THREADS_JOIN(threads)            \
759
343
    for (const auto& thread : threads) { \
760
0
        if (thread) {                    \
761
0
            thread->join();              \
762
0
        }                                \
763
0
    }
764
765
343
    THREADS_JOIN(_path_gc_threads);
766
343
#undef THREADS_JOIN
767
768
343
    if (_base_compaction_thread_pool) {
769
6
        _base_compaction_thread_pool->shutdown();
770
6
    }
771
343
    if (_cumu_compaction_thread_pool) {
772
7
        _cumu_compaction_thread_pool->shutdown();
773
7
    }
774
343
    if (_single_replica_compaction_thread_pool) {
775
0
        _single_replica_compaction_thread_pool->shutdown();
776
0
    }
777
778
343
    if (_seg_compaction_thread_pool) {
779
11
        _seg_compaction_thread_pool->shutdown();
780
11
    }
781
343
    if (_tablet_meta_checkpoint_thread_pool) {
782
0
        _tablet_meta_checkpoint_thread_pool->shutdown();
783
0
    }
784
343
    if (_cold_data_compaction_thread_pool) {
785
0
        _cold_data_compaction_thread_pool->shutdown();
786
0
    }
787
788
343
    if (_cooldown_thread_pool) {
789
0
        _cooldown_thread_pool->shutdown();
790
0
    }
791
792
343
    _adaptive_thread_controller.stop();
793
343
    _memtable_flush_executor.reset(nullptr);
794
343
    _calc_delete_bitmap_executor.reset(nullptr);
795
343
    _calc_delete_bitmap_executor_for_load.reset();
796
797
343
    _stopped = true;
798
343
    LOG(INFO) << "Storage engine is stopped.";
799
343
}
800
801
0
void StorageEngine::clear_transaction_task(const TTransactionId transaction_id) {
802
    // clear transaction task may not contains partitions ids, we should get partition id from txn manager.
803
0
    std::vector<int64_t> partition_ids;
804
0
    _txn_manager->get_partition_ids(transaction_id, &partition_ids);
805
0
    clear_transaction_task(transaction_id, partition_ids);
806
0
}
807
808
void StorageEngine::clear_transaction_task(const TTransactionId transaction_id,
809
0
                                           const std::vector<TPartitionId>& partition_ids) {
810
0
    LOG(INFO) << "begin to clear transaction task. transaction_id=" << transaction_id;
811
812
0
    for (const TPartitionId& partition_id : partition_ids) {
813
0
        std::map<TabletInfo, RowsetSharedPtr> tablet_infos;
814
0
        _txn_manager->get_txn_related_tablets(transaction_id, partition_id, &tablet_infos);
815
816
        // each tablet
817
0
        for (auto& tablet_info : tablet_infos) {
818
            // should use tablet uid to ensure clean txn correctly
819
0
            TabletSharedPtr tablet = _tablet_manager->get_tablet(tablet_info.first.tablet_id,
820
0
                                                                 tablet_info.first.tablet_uid);
821
            // The tablet may be dropped or altered, leave a INFO log and go on process other tablet
822
0
            if (tablet == nullptr) {
823
0
                LOG(INFO) << "tablet is no longer exist. tablet_id=" << tablet_info.first.tablet_id
824
0
                          << ", tablet_uid=" << tablet_info.first.tablet_uid;
825
0
                continue;
826
0
            }
827
0
            Status s = _txn_manager->delete_txn(partition_id, tablet, transaction_id);
828
0
            if (!s.ok()) {
829
0
                LOG(WARNING) << "failed to clear transaction. txn_id=" << transaction_id
830
0
                             << ", partition_id=" << partition_id
831
0
                             << ", tablet_id=" << tablet_info.first.tablet_id
832
0
                             << ", status=" << s.to_string();
833
0
            }
834
0
        }
835
0
    }
836
0
    LOG(INFO) << "finish to clear transaction task. transaction_id=" << transaction_id;
837
0
}
838
839
0
Status StorageEngine::start_trash_sweep(double* usage, bool ignore_guard) {
840
0
    Status res = Status::OK();
841
842
0
    std::unique_lock<std::mutex> l(_trash_sweep_lock, std::defer_lock);
843
0
    if (!l.try_lock()) {
844
0
        LOG(INFO) << "trash and snapshot sweep is running.";
845
0
        if (ignore_guard) {
846
0
            _need_clean_trash.store(true, std::memory_order_relaxed);
847
0
        }
848
0
        return res;
849
0
    }
850
851
0
    LOG(INFO) << "start trash and snapshot sweep. is_clean=" << ignore_guard;
852
853
0
    const int32_t snapshot_expire = config::snapshot_expire_time_sec;
854
0
    const int32_t trash_expire = config::trash_file_expire_time_sec;
855
    // the guard space should be lower than storage_flood_stage_usage_percent,
856
    // so here we multiply 0.9
857
    // if ignore_guard is true, set guard_space to 0.
858
0
    const double guard_space =
859
0
            ignore_guard ? 0 : config::storage_flood_stage_usage_percent / 100.0 * 0.9;
860
0
    std::vector<DataDirInfo> data_dir_infos;
861
0
    RETURN_NOT_OK_STATUS_WITH_WARN(get_all_data_dir_info(&data_dir_infos, false),
862
0
                                   "failed to get root path stat info when sweep trash.")
863
0
    std::sort(data_dir_infos.begin(), data_dir_infos.end(), DataDirInfoLessAvailability());
864
865
0
    time_t now = time(nullptr); //获取UTC时间
866
0
    tm local_tm_now;
867
0
    local_tm_now.tm_isdst = 0;
868
0
    if (localtime_r(&now, &local_tm_now) == nullptr) {
869
0
        return Status::Error<OS_ERROR>("fail to localtime_r time. time={}", now);
870
0
    }
871
0
    const time_t local_now = mktime(&local_tm_now); //得到当地日历时间
872
873
0
    double tmp_usage = 0.0;
874
0
    for (DataDirInfo& info : data_dir_infos) {
875
0
        LOG(INFO) << "Start to sweep path " << info.path;
876
0
        if (!info.is_used) {
877
0
            continue;
878
0
        }
879
880
0
        double curr_usage =
881
0
                (double)(info.disk_capacity - info.available) / (double)info.disk_capacity;
882
0
        tmp_usage = std::max(tmp_usage, curr_usage);
883
884
0
        Status curr_res = Status::OK();
885
0
        auto snapshot_path = fmt::format("{}/{}", info.path, SNAPSHOT_PREFIX);
886
0
        curr_res = _do_sweep(snapshot_path, local_now, snapshot_expire);
887
0
        if (!curr_res.ok()) {
888
0
            LOG(WARNING) << "failed to sweep snapshot. path=" << snapshot_path
889
0
                         << ", err_code=" << curr_res;
890
0
            res = curr_res;
891
0
        }
892
893
0
        auto trash_path = fmt::format("{}/{}", info.path, TRASH_PREFIX);
894
0
        curr_res = _do_sweep(trash_path, local_now, curr_usage > guard_space ? 0 : trash_expire);
895
0
        if (!curr_res.ok()) {
896
0
            LOG(WARNING) << "failed to sweep trash. path=" << trash_path
897
0
                         << ", err_code=" << curr_res;
898
0
            res = curr_res;
899
0
        }
900
0
    }
901
902
0
    if (usage != nullptr) {
903
0
        *usage = tmp_usage; // update usage
904
0
    }
905
906
    // clear expire incremental rowset, move deleted tablet to trash
907
0
    RETURN_IF_ERROR(_tablet_manager->start_trash_sweep());
908
909
    // clean rubbish transactions
910
0
    _clean_unused_txns();
911
912
    // clean unused rowset metas in OlapMeta
913
0
    _clean_unused_rowset_metas();
914
915
    // clean unused binlog metas in OlapMeta
916
0
    _clean_unused_binlog_metas();
917
918
    // cleand unused delete bitmap for deleted tablet
919
0
    _clean_unused_delete_bitmap();
920
921
    // cleand unused pending publish info for deleted tablet
922
0
    _clean_unused_pending_publish_info();
923
924
    // clean unused partial update info for finished txns
925
0
    _clean_unused_partial_update_info();
926
927
    // clean unused rowsets in remote storage backends
928
0
    for (auto data_dir : get_stores()) {
929
0
        data_dir->perform_remote_rowset_gc();
930
0
        data_dir->perform_remote_tablet_gc();
931
0
        data_dir->update_trash_capacity();
932
0
    }
933
934
0
    return res;
935
0
}
936
937
0
void StorageEngine::_clean_unused_rowset_metas() {
938
0
    std::vector<RowsetMetaSharedPtr> invalid_rowset_metas;
939
0
    auto clean_rowset_func = [this, &invalid_rowset_metas](TabletUid tablet_uid, RowsetId rowset_id,
940
0
                                                           std::string_view meta_str) -> bool {
941
        // return false will break meta iterator, return true to skip this error
942
0
        RowsetMetaSharedPtr rowset_meta(new RowsetMeta());
943
0
        bool parsed = rowset_meta->init(meta_str);
944
0
        if (!parsed) {
945
0
            LOG(WARNING) << "parse rowset meta string failed for rowset_id:" << rowset_id;
946
0
            invalid_rowset_metas.push_back(rowset_meta);
947
0
            return true;
948
0
        }
949
0
        if (rowset_meta->tablet_uid() != tablet_uid) {
950
0
            LOG(WARNING) << "tablet uid is not equal, skip the rowset"
951
0
                         << ", rowset_id=" << rowset_meta->rowset_id()
952
0
                         << ", in_put_tablet_uid=" << tablet_uid
953
0
                         << ", tablet_uid in rowset meta=" << rowset_meta->tablet_uid();
954
0
            invalid_rowset_metas.push_back(rowset_meta);
955
0
            return true;
956
0
        }
957
958
0
        TabletSharedPtr tablet = _tablet_manager->get_tablet(rowset_meta->tablet_id());
959
0
        if (tablet == nullptr) {
960
            // tablet may be dropped
961
            // TODO(cmy): this is better to be a VLOG, because drop table is a very common case.
962
            // leave it as INFO log for observation. Maybe change it in future.
963
0
            LOG(INFO) << "failed to find tablet " << rowset_meta->tablet_id()
964
0
                      << " for rowset: " << rowset_meta->rowset_id() << ", tablet may be dropped";
965
0
            invalid_rowset_metas.push_back(rowset_meta);
966
0
            return true;
967
0
        }
968
0
        if (tablet->tablet_uid() != rowset_meta->tablet_uid()) {
969
            // In this case, we get the tablet using the tablet id recorded in the rowset meta.
970
            // but the uid in the tablet is different from the one recorded in the rowset meta.
971
            // How this happened:
972
            // Replica1 of Tablet A exists on BE1. Because of the clone task, a new replica2 is createed on BE2,
973
            // and then replica1 deleted from BE1. After some time, we created replica again on BE1,
974
            // which will creates a new tablet with the same id but a different uid.
975
            // And in the historical version, when we deleted the replica, we did not delete the corresponding rowset meta,
976
            // thus causing the original rowset meta to remain(with same tablet id but different uid).
977
0
            LOG(WARNING) << "rowset's tablet uid " << rowset_meta->tablet_uid()
978
0
                         << " does not equal to tablet uid: " << tablet->tablet_uid();
979
0
            invalid_rowset_metas.push_back(rowset_meta);
980
0
            return true;
981
0
        }
982
0
        if (rowset_meta->rowset_state() == RowsetStatePB::VISIBLE &&
983
0
            (!tablet->rowset_meta_is_useful(rowset_meta)) &&
984
0
            !check_rowset_id_in_unused_rowsets(rowset_id)) {
985
0
            LOG(INFO) << "rowset meta is not used any more, remove it. rowset_id="
986
0
                      << rowset_meta->rowset_id();
987
0
            invalid_rowset_metas.push_back(rowset_meta);
988
0
        }
989
0
        return true;
990
0
    };
991
0
    auto data_dirs = get_stores();
992
0
    for (auto data_dir : data_dirs) {
993
0
        static_cast<void>(
994
0
                RowsetMetaManager::traverse_rowset_metas(data_dir->get_meta(), clean_rowset_func));
995
        // 1. delete delete_bitmap
996
0
        std::set<int64_t> tablets_to_save_meta;
997
0
        for (auto& rowset_meta : invalid_rowset_metas) {
998
0
            TabletSharedPtr tablet = _tablet_manager->get_tablet(rowset_meta->tablet_id());
999
0
            if (tablet && tablet->tablet_meta()->enable_unique_key_merge_on_write()) {
1000
0
                tablet->tablet_meta()->remove_rowset_delete_bitmap(rowset_meta->rowset_id(),
1001
0
                                                                   rowset_meta->version());
1002
0
                tablets_to_save_meta.emplace(tablet->tablet_id());
1003
0
            }
1004
0
        }
1005
0
        for (const auto& tablet_id : tablets_to_save_meta) {
1006
0
            auto tablet = _tablet_manager->get_tablet(tablet_id);
1007
0
            if (tablet) {
1008
0
                std::shared_lock rlock(tablet->get_header_lock());
1009
0
                tablet->save_meta();
1010
0
            }
1011
0
        }
1012
        // 2. delete rowset meta
1013
0
        for (auto& rowset_meta : invalid_rowset_metas) {
1014
0
            static_cast<void>(RowsetMetaManager::remove(
1015
0
                    data_dir->get_meta(), rowset_meta->tablet_uid(), rowset_meta->rowset_id()));
1016
0
        }
1017
0
        LOG(INFO) << "remove " << invalid_rowset_metas.size()
1018
0
                  << " invalid rowset meta from dir: " << data_dir->path();
1019
0
        invalid_rowset_metas.clear();
1020
0
    }
1021
0
}
1022
1023
0
void StorageEngine::_clean_unused_binlog_metas() {
1024
0
    std::vector<std::string> unused_binlog_key_suffixes;
1025
0
    auto unused_binlog_collector = [this, &unused_binlog_key_suffixes](std::string_view key,
1026
0
                                                                       std::string_view value,
1027
0
                                                                       bool need_check) -> bool {
1028
0
        if (need_check) {
1029
0
            BinlogMetaEntryPB binlog_meta_pb;
1030
0
            if (UNLIKELY(!binlog_meta_pb.ParseFromArray(value.data(),
1031
0
                                                        cast_set<int>(value.size())))) {
1032
0
                LOG(WARNING) << "parse rowset meta string failed for binlog meta key: " << key;
1033
0
            } else if (_tablet_manager->get_tablet(binlog_meta_pb.tablet_id()) == nullptr) {
1034
0
                LOG(INFO) << "failed to find tablet " << binlog_meta_pb.tablet_id()
1035
0
                          << " for binlog rowset: " << binlog_meta_pb.rowset_id()
1036
0
                          << ", tablet may be dropped";
1037
0
            } else {
1038
0
                return false;
1039
0
            }
1040
0
        }
1041
1042
0
        unused_binlog_key_suffixes.emplace_back(key.substr(kBinlogMetaPrefix.size()));
1043
0
        return true;
1044
0
    };
1045
0
    auto data_dirs = get_stores();
1046
0
    for (auto data_dir : data_dirs) {
1047
0
        static_cast<void>(RowsetMetaManager::traverse_binlog_metas(data_dir->get_meta(),
1048
0
                                                                   unused_binlog_collector));
1049
0
        for (const auto& suffix : unused_binlog_key_suffixes) {
1050
0
            static_cast<void>(RowsetMetaManager::remove_binlog(data_dir->get_meta(), suffix));
1051
0
        }
1052
0
        LOG(INFO) << "remove " << unused_binlog_key_suffixes.size()
1053
0
                  << " invalid binlog meta from dir: " << data_dir->path();
1054
0
        unused_binlog_key_suffixes.clear();
1055
0
    }
1056
0
}
1057
1058
0
void StorageEngine::_clean_unused_delete_bitmap() {
1059
0
    std::unordered_set<int64_t> removed_tablets;
1060
0
    auto clean_delete_bitmap_func = [this, &removed_tablets](int64_t tablet_id, int64_t version,
1061
0
                                                             std::string_view val) -> bool {
1062
0
        TabletSharedPtr tablet = _tablet_manager->get_tablet(tablet_id);
1063
0
        if (tablet == nullptr) {
1064
0
            if (removed_tablets.insert(tablet_id).second) {
1065
0
                LOG(INFO) << "clean ununsed delete bitmap for deleted tablet, tablet_id: "
1066
0
                          << tablet_id;
1067
0
            }
1068
0
        }
1069
0
        return true;
1070
0
    };
1071
0
    auto data_dirs = get_stores();
1072
0
    for (auto data_dir : data_dirs) {
1073
0
        static_cast<void>(TabletMetaManager::traverse_delete_bitmap(data_dir->get_meta(),
1074
0
                                                                    clean_delete_bitmap_func));
1075
0
        for (auto id : removed_tablets) {
1076
0
            static_cast<void>(
1077
0
                    TabletMetaManager::remove_old_version_delete_bitmap(data_dir, id, INT64_MAX));
1078
0
        }
1079
0
        LOG(INFO) << "removed invalid delete bitmap from dir: " << data_dir->path()
1080
0
                  << ", deleted tablets size: " << removed_tablets.size();
1081
0
        removed_tablets.clear();
1082
0
    }
1083
0
}
1084
1085
0
void StorageEngine::_clean_unused_pending_publish_info() {
1086
0
    std::vector<std::pair<int64_t, int64_t>> removed_infos;
1087
0
    auto clean_pending_publish_info_func = [this, &removed_infos](int64_t tablet_id,
1088
0
                                                                  int64_t publish_version,
1089
0
                                                                  std::string_view info) -> bool {
1090
0
        TabletSharedPtr tablet = _tablet_manager->get_tablet(tablet_id);
1091
0
        if (tablet == nullptr) {
1092
0
            removed_infos.emplace_back(tablet_id, publish_version);
1093
0
        }
1094
0
        return true;
1095
0
    };
1096
0
    auto data_dirs = get_stores();
1097
0
    for (auto data_dir : data_dirs) {
1098
0
        static_cast<void>(TabletMetaManager::traverse_pending_publish(
1099
0
                data_dir->get_meta(), clean_pending_publish_info_func));
1100
0
        for (auto& [tablet_id, publish_version] : removed_infos) {
1101
0
            static_cast<void>(TabletMetaManager::remove_pending_publish_info(data_dir, tablet_id,
1102
0
                                                                             publish_version));
1103
0
        }
1104
0
        LOG(INFO) << "removed invalid pending publish info from dir: " << data_dir->path()
1105
0
                  << ", deleted pending publish info size: " << removed_infos.size();
1106
0
        removed_infos.clear();
1107
0
    }
1108
0
}
1109
1110
0
void StorageEngine::_clean_unused_partial_update_info() {
1111
0
    std::vector<std::tuple<int64_t, int64_t, int64_t>> remove_infos;
1112
0
    auto unused_partial_update_info_collector =
1113
0
            [this, &remove_infos](int64_t tablet_id, int64_t partition_id, int64_t txn_id,
1114
0
                                  std::string_view value) -> bool {
1115
0
        TabletSharedPtr tablet = _tablet_manager->get_tablet(tablet_id);
1116
0
        if (tablet == nullptr) {
1117
0
            remove_infos.emplace_back(tablet_id, partition_id, txn_id);
1118
0
            return true;
1119
0
        }
1120
0
        TxnState txn_state =
1121
0
                _txn_manager->get_txn_state(partition_id, txn_id, tablet_id, tablet->tablet_uid());
1122
0
        if (txn_state == TxnState::NOT_FOUND || txn_state == TxnState::ABORTED ||
1123
0
            txn_state == TxnState::DELETED) {
1124
0
            remove_infos.emplace_back(tablet_id, partition_id, txn_id);
1125
0
            return true;
1126
0
        }
1127
0
        return true;
1128
0
    };
1129
0
    auto data_dirs = get_stores();
1130
0
    for (auto* data_dir : data_dirs) {
1131
0
        static_cast<void>(RowsetMetaManager::traverse_partial_update_info(
1132
0
                data_dir->get_meta(), unused_partial_update_info_collector));
1133
0
        static_cast<void>(
1134
0
                RowsetMetaManager::remove_partial_update_infos(data_dir->get_meta(), remove_infos));
1135
0
    }
1136
0
}
1137
1138
0
void StorageEngine::gc_binlogs(const std::unordered_map<int64_t, int64_t>& gc_tablet_infos) {
1139
0
    for (auto [tablet_id, version] : gc_tablet_infos) {
1140
0
        LOG(INFO) << fmt::format("start to gc binlogs for tablet_id: {}, version: {}", tablet_id,
1141
0
                                 version);
1142
1143
0
        TabletSharedPtr tablet = _tablet_manager->get_tablet(tablet_id);
1144
0
        if (tablet == nullptr) {
1145
0
            LOG(WARNING) << fmt::format("tablet_id: {} not found", tablet_id);
1146
0
            continue;
1147
0
        }
1148
0
        tablet->gc_binlogs(version);
1149
0
    }
1150
0
}
1151
1152
0
void StorageEngine::_clean_unused_txns() {
1153
0
    std::set<TabletInfo> tablet_infos;
1154
0
    _txn_manager->get_all_related_tablets(&tablet_infos);
1155
0
    for (auto& tablet_info : tablet_infos) {
1156
0
        TabletSharedPtr tablet =
1157
0
                _tablet_manager->get_tablet(tablet_info.tablet_id, tablet_info.tablet_uid, true);
1158
0
        if (tablet == nullptr) {
1159
            // TODO(ygl) :  should check if tablet still in meta, it's a improvement
1160
            // case 1: tablet still in meta, just remove from memory
1161
            // case 2: tablet not in meta store, remove rowset from meta
1162
            // currently just remove them from memory
1163
            // nullptr to indicate not remove them from meta store
1164
0
            _txn_manager->force_rollback_tablet_related_txns(nullptr, tablet_info.tablet_id,
1165
0
                                                             tablet_info.tablet_uid);
1166
0
        }
1167
0
    }
1168
0
}
1169
1170
Status StorageEngine::_do_sweep(const std::string& scan_root, const time_t& local_now,
1171
0
                                const int32_t expire) {
1172
0
    Status res = Status::OK();
1173
0
    bool exists = true;
1174
0
    RETURN_IF_ERROR(io::global_local_filesystem()->exists(scan_root, &exists));
1175
0
    if (!exists) {
1176
        // dir not existed. no need to sweep trash.
1177
0
        return res;
1178
0
    }
1179
1180
0
    int curr_sweep_batch_size = 0;
1181
0
    try {
1182
        // Sort pathes by name, that is by delete time.
1183
0
        std::vector<path> sorted_pathes;
1184
0
        std::copy(directory_iterator(scan_root), directory_iterator(),
1185
0
                  std::back_inserter(sorted_pathes));
1186
0
        std::sort(sorted_pathes.begin(), sorted_pathes.end());
1187
0
        for (const auto& sorted_path : sorted_pathes) {
1188
0
            string dir_name = sorted_path.filename().string();
1189
0
            string str_time = dir_name.substr(0, dir_name.find('.'));
1190
0
            tm local_tm_create;
1191
0
            local_tm_create.tm_isdst = 0;
1192
0
            if (strptime(str_time.c_str(), "%Y%m%d%H%M%S", &local_tm_create) == nullptr) {
1193
0
                res = Status::Error<OS_ERROR>("fail to strptime time. time={}", str_time);
1194
0
                continue;
1195
0
            }
1196
1197
0
            int32_t actual_expire = expire;
1198
            // try get timeout in dir name, the old snapshot dir does not contain timeout
1199
            // eg: 20190818221123.3.86400, the 86400 is timeout, in second
1200
0
            size_t pos = dir_name.find('.', str_time.size() + 1);
1201
0
            if (pos != string::npos) {
1202
0
                actual_expire = std::stoi(dir_name.substr(pos + 1));
1203
0
            }
1204
0
            VLOG_TRACE << "get actual expire time " << actual_expire << " of dir: " << dir_name;
1205
1206
0
            string path_name = sorted_path.string();
1207
0
            if (difftime(local_now, mktime(&local_tm_create)) >= actual_expire) {
1208
0
                res = io::global_local_filesystem()->delete_directory(path_name);
1209
0
                LOG(INFO) << "do sweep delete directory " << path_name << " local_now " << local_now
1210
0
                          << "actual_expire " << actual_expire << " res " << res;
1211
0
                if (!res.ok()) {
1212
0
                    continue;
1213
0
                }
1214
1215
0
                curr_sweep_batch_size++;
1216
0
                if (config::garbage_sweep_batch_size > 0 &&
1217
0
                    curr_sweep_batch_size >= config::garbage_sweep_batch_size) {
1218
0
                    curr_sweep_batch_size = 0;
1219
0
                    std::this_thread::sleep_for(std::chrono::milliseconds(1));
1220
0
                }
1221
0
            } else {
1222
                // Because files are ordered by filename, i.e. by create time, so all the left files are not expired.
1223
0
                break;
1224
0
            }
1225
0
        }
1226
0
    } catch (...) {
1227
0
        res = Status::Error<IO_ERROR>("Exception occur when scan directory. path_desc={}",
1228
0
                                      scan_root);
1229
0
    }
1230
1231
0
    return res;
1232
0
}
1233
1234
// invalid rowset type config will return ALPHA_ROWSET for system to run smoothly
1235
38
void StorageEngine::_parse_default_rowset_type() {
1236
38
    std::string default_rowset_type_config = config::default_rowset_type;
1237
38
    boost::to_upper(default_rowset_type_config);
1238
38
    if (default_rowset_type_config == "BETA") {
1239
38
        _default_rowset_type = BETA_ROWSET;
1240
38
    } else if (default_rowset_type_config == "ALPHA") {
1241
0
        _default_rowset_type = ALPHA_ROWSET;
1242
0
        LOG(WARNING) << "default_rowset_type in be.conf should be set to beta, alpha is not "
1243
0
                        "supported any more";
1244
0
    } else {
1245
0
        LOG(FATAL) << "unknown value " << default_rowset_type_config
1246
0
                   << " in default_rowset_type in be.conf";
1247
0
    }
1248
38
}
1249
1250
0
void StorageEngine::start_delete_unused_rowset() {
1251
0
    DBUG_EXECUTE_IF("StorageEngine::start_delete_unused_rowset.block", DBUG_BLOCK);
1252
0
    LOG(INFO) << "start to delete unused rowset, size: " << _unused_rowsets.size()
1253
0
              << ", unused delete bitmap size: " << _unused_delete_bitmap.size();
1254
0
    std::vector<RowsetSharedPtr> unused_rowsets_copy;
1255
0
    unused_rowsets_copy.reserve(_unused_rowsets.size());
1256
0
    auto due_to_use_count = 0;
1257
0
    auto due_to_not_delete_file = 0;
1258
0
    auto due_to_delayed_expired_ts = 0;
1259
0
    std::set<int64_t> tablets_to_save_meta;
1260
0
    {
1261
0
        std::lock_guard<std::mutex> lock(_gc_mutex);
1262
0
        for (auto it = _unused_rowsets.begin(); it != _unused_rowsets.end();) {
1263
0
            auto&& rs = it->second;
1264
0
            if (rs.use_count() == 1 && rs->need_delete_file()) {
1265
                // remote rowset data will be reclaimed by `remove_unused_remote_files`
1266
0
                if (rs->is_local()) {
1267
0
                    unused_rowsets_copy.push_back(std::move(rs));
1268
0
                }
1269
0
                it = _unused_rowsets.erase(it);
1270
0
            } else {
1271
0
                if (rs.use_count() != 1) {
1272
0
                    ++due_to_use_count;
1273
0
                } else if (!rs->need_delete_file()) {
1274
0
                    ++due_to_not_delete_file;
1275
0
                } else {
1276
0
                    ++due_to_delayed_expired_ts;
1277
0
                }
1278
0
                ++it;
1279
0
            }
1280
0
        }
1281
        // check remove delete bitmaps
1282
0
        for (auto it = _unused_delete_bitmap.begin(); it != _unused_delete_bitmap.end();) {
1283
0
            auto tablet_id = std::get<0>(*it);
1284
0
            auto tablet = _tablet_manager->get_tablet(tablet_id);
1285
0
            if (tablet == nullptr) {
1286
0
                it = _unused_delete_bitmap.erase(it);
1287
0
                continue;
1288
0
            }
1289
0
            auto& rowset_ids = std::get<1>(*it);
1290
0
            auto& key_ranges = std::get<2>(*it);
1291
0
            bool find_unused_rowset = false;
1292
0
            for (const auto& rowset_id : rowset_ids) {
1293
0
                if (_unused_rowsets.find(rowset_id) != _unused_rowsets.end()) {
1294
0
                    VLOG_DEBUG << "can not remove pre rowset delete bitmap because rowset is in use"
1295
0
                               << ", tablet_id=" << tablet_id
1296
0
                               << ", rowset_id=" << rowset_id.to_string();
1297
0
                    find_unused_rowset = true;
1298
0
                    break;
1299
0
                }
1300
0
            }
1301
0
            if (find_unused_rowset) {
1302
0
                ++it;
1303
0
                continue;
1304
0
            }
1305
0
            tablet->tablet_meta()->delete_bitmap().remove(key_ranges);
1306
0
            tablets_to_save_meta.emplace(tablet_id);
1307
0
            it = _unused_delete_bitmap.erase(it);
1308
0
        }
1309
0
    }
1310
0
    LOG(INFO) << "collected " << unused_rowsets_copy.size() << " unused rowsets to remove, skipped "
1311
0
              << due_to_use_count << " rowsets due to use count > 1, skipped "
1312
0
              << due_to_not_delete_file << " rowsets due to don't need to delete file, skipped "
1313
0
              << due_to_delayed_expired_ts << " rowsets due to delayed expired timestamp. left "
1314
0
              << _unused_delete_bitmap.size() << " unused delete bitmap.";
1315
0
    for (auto&& rs : unused_rowsets_copy) {
1316
0
        VLOG_NOTICE << "start to remove rowset:" << rs->rowset_id()
1317
0
                    << ", version:" << rs->version();
1318
        // delete delete_bitmap of unused rowsets
1319
0
        if (auto tablet = _tablet_manager->get_tablet(rs->rowset_meta()->tablet_id());
1320
0
            tablet && tablet->enable_unique_key_merge_on_write()) {
1321
0
            tablet->tablet_meta()->remove_rowset_delete_bitmap(rs->rowset_id(), rs->version());
1322
0
            tablets_to_save_meta.emplace(tablet->tablet_id());
1323
0
        }
1324
0
        Status status = rs->remove();
1325
0
        unused_rowsets_counter << -1;
1326
0
        VLOG_NOTICE << "remove rowset:" << rs->rowset_id() << " finished. status:" << status;
1327
0
    }
1328
0
    for (const auto& tablet_id : tablets_to_save_meta) {
1329
0
        auto tablet = _tablet_manager->get_tablet(tablet_id);
1330
0
        if (tablet) {
1331
0
            std::shared_lock rlock(tablet->get_header_lock());
1332
0
            tablet->save_meta();
1333
0
        }
1334
0
    }
1335
0
    LOG(INFO) << "removed all collected unused rowsets";
1336
0
}
1337
1338
64
void StorageEngine::add_unused_rowset(RowsetSharedPtr rowset) {
1339
64
    if (rowset == nullptr) {
1340
5
        return;
1341
5
    }
1342
59
    VLOG_NOTICE << "add unused rowset, rowset id:" << rowset->rowset_id()
1343
39
                << ", version:" << rowset->version();
1344
59
    std::lock_guard<std::mutex> lock(_gc_mutex);
1345
59
    auto it = _unused_rowsets.find(rowset->rowset_id());
1346
59
    if (it == _unused_rowsets.end()) {
1347
59
        rowset->set_need_delete_file();
1348
59
        rowset->close();
1349
59
        _unused_rowsets[rowset->rowset_id()] = std::move(rowset);
1350
59
        unused_rowsets_counter << 1;
1351
59
    }
1352
59
}
1353
1354
void StorageEngine::add_unused_delete_bitmap_key_ranges(int64_t tablet_id,
1355
                                                        const std::vector<RowsetId>& rowsets,
1356
0
                                                        const DeleteBitmapKeyRanges& key_ranges) {
1357
0
    VLOG_NOTICE << "add unused delete bitmap key ranges, tablet id:" << tablet_id;
1358
0
    std::lock_guard<std::mutex> lock(_gc_mutex);
1359
0
    _unused_delete_bitmap.push_back(std::make_tuple(tablet_id, rowsets, key_ranges));
1360
0
}
1361
1362
// TODO(zc): refactor this funciton
1363
73
Status StorageEngine::create_tablet(const TCreateTabletReq& request, RuntimeProfile* profile) {
1364
    // Get all available stores, use ref_root_path if the caller specified
1365
73
    std::vector<DataDir*> stores;
1366
73
    {
1367
73
        SCOPED_TIMER(ADD_TIMER(profile, "GetStores"));
1368
73
        stores = get_stores_for_create_tablet(request.partition_id, request.storage_medium);
1369
73
    }
1370
73
    if (stores.empty()) {
1371
0
        return Status::Error<CE_CMD_PARAMS_ERROR>(
1372
0
                "there is no available disk that can be used to create tablet.");
1373
0
    }
1374
73
    return _tablet_manager->create_tablet(request, stores, profile);
1375
73
}
1376
1377
Result<BaseTabletSPtr> StorageEngine::get_tablet(int64_t tablet_id, SyncRowsetStats* sync_stats,
1378
30
                                                 bool force_use_only_cached, bool cache_on_miss) {
1379
30
    BaseTabletSPtr tablet;
1380
30
    std::string err;
1381
30
    tablet = _tablet_manager->get_tablet(tablet_id, true, &err);
1382
30
    if (tablet == nullptr) {
1383
1
        return unexpected(
1384
1
                Status::InternalError("failed to get tablet: {}, reason: {}", tablet_id, err));
1385
1
    }
1386
29
    return tablet;
1387
30
}
1388
1389
Status StorageEngine::get_tablet_meta(int64_t tablet_id, TabletMetaSharedPtr* tablet_meta,
1390
0
                                      bool force_use_only_cached) {
1391
0
    if (tablet_meta == nullptr) {
1392
0
        return Status::InvalidArgument("tablet_meta output is null");
1393
0
    }
1394
1395
0
    auto res = get_tablet(tablet_id, nullptr, force_use_only_cached, true);
1396
0
    if (!res.has_value()) {
1397
0
        return res.error();
1398
0
    }
1399
1400
0
    *tablet_meta = res.value()->tablet_meta();
1401
0
    return Status::OK();
1402
0
}
1403
1404
Status StorageEngine::obtain_shard_path(TStorageMedium::type storage_medium, int64_t path_hash,
1405
                                        std::string* shard_path, DataDir** store,
1406
0
                                        int64_t partition_id) {
1407
0
    LOG(INFO) << "begin to process obtain root path. storage_medium=" << storage_medium;
1408
1409
0
    if (shard_path == nullptr) {
1410
0
        return Status::Error<CE_CMD_PARAMS_ERROR>(
1411
0
                "invalid output parameter which is null pointer.");
1412
0
    }
1413
1414
0
    auto stores = get_stores_for_create_tablet(partition_id, storage_medium);
1415
0
    if (stores.empty()) {
1416
0
        return Status::Error<NO_AVAILABLE_ROOT_PATH>(
1417
0
                "no available disk can be used to create tablet.");
1418
0
    }
1419
1420
0
    *store = nullptr;
1421
0
    if (path_hash != -1) {
1422
0
        for (auto data_dir : stores) {
1423
0
            if (data_dir->path_hash() == path_hash) {
1424
0
                *store = data_dir;
1425
0
                break;
1426
0
            }
1427
0
        }
1428
0
    }
1429
0
    if (*store == nullptr) {
1430
0
        *store = stores[0];
1431
0
    }
1432
1433
0
    uint64_t shard = (*store)->get_shard();
1434
1435
0
    std::stringstream root_path_stream;
1436
0
    root_path_stream << (*store)->path() << "/" << DATA_PREFIX << "/" << shard;
1437
0
    *shard_path = root_path_stream.str();
1438
1439
0
    LOG(INFO) << "success to process obtain root path. path=" << *shard_path;
1440
0
    return Status::OK();
1441
0
}
1442
1443
Status StorageEngine::load_header(const string& shard_path, const TCloneReq& request,
1444
0
                                  bool restore) {
1445
0
    LOG(INFO) << "begin to process load headers."
1446
0
              << "tablet_id=" << request.tablet_id << ", schema_hash=" << request.schema_hash;
1447
0
    Status res = Status::OK();
1448
1449
0
    DataDir* store = nullptr;
1450
0
    {
1451
        // TODO(zc)
1452
0
        try {
1453
0
            auto store_path =
1454
0
                    std::filesystem::path(shard_path).parent_path().parent_path().string();
1455
0
            store = get_store(store_path);
1456
0
            if (store == nullptr) {
1457
0
                return Status::Error<INVALID_ROOT_PATH>("invalid shard path, path={}", shard_path);
1458
0
            }
1459
0
        } catch (...) {
1460
0
            return Status::Error<INVALID_ROOT_PATH>("invalid shard path, path={}", shard_path);
1461
0
        }
1462
0
    }
1463
1464
0
    std::stringstream schema_hash_path_stream;
1465
0
    schema_hash_path_stream << shard_path << "/" << request.tablet_id << "/" << request.schema_hash;
1466
    // not surely, reload and restore tablet action call this api
1467
    // reset tablet uid here
1468
1469
0
    string header_path = TabletMeta::construct_header_file_path(schema_hash_path_stream.str(),
1470
0
                                                                request.tablet_id);
1471
0
    res = _tablet_manager->load_tablet_from_dir(store, request.tablet_id, request.schema_hash,
1472
0
                                                schema_hash_path_stream.str(), false, restore);
1473
0
    if (!res.ok()) {
1474
0
        LOG(WARNING) << "fail to process load headers. res=" << res;
1475
0
        return res;
1476
0
    }
1477
1478
0
    LOG(INFO) << "success to process load headers.";
1479
0
    return res;
1480
0
}
1481
1482
1
void BaseStorageEngine::register_report_listener(ReportWorker* listener) {
1483
1
    std::lock_guard<std::mutex> l(_report_mtx);
1484
1
    if (std::find(_report_listeners.begin(), _report_listeners.end(), listener) !=
1485
1
        _report_listeners.end()) [[unlikely]] {
1486
0
        return;
1487
0
    }
1488
1
    _report_listeners.push_back(listener);
1489
1
}
1490
1491
1
void BaseStorageEngine::deregister_report_listener(ReportWorker* listener) {
1492
1
    std::lock_guard<std::mutex> l(_report_mtx);
1493
1
    if (auto it = std::find(_report_listeners.begin(), _report_listeners.end(), listener);
1494
1
        it != _report_listeners.end()) {
1495
1
        _report_listeners.erase(it);
1496
1
    }
1497
1
}
1498
1499
343
void BaseStorageEngine::notify_listeners() {
1500
343
    std::lock_guard<std::mutex> l(_report_mtx);
1501
343
    for (auto& listener : _report_listeners) {
1502
0
        listener->notify();
1503
0
    }
1504
343
}
1505
1506
1
bool BaseStorageEngine::notify_listener(std::string_view name) {
1507
1
    bool found = false;
1508
1
    std::lock_guard<std::mutex> l(_report_mtx);
1509
1
    for (auto& listener : _report_listeners) {
1510
1
        if (listener->name() == name) {
1511
1
            listener->notify();
1512
1
            found = true;
1513
1
        }
1514
1
    }
1515
1
    return found;
1516
1
}
1517
1518
0
void BaseStorageEngine::_evict_quring_rowset_thread_callback() {
1519
0
    int32_t interval = config::quering_rowsets_evict_interval;
1520
0
    do {
1521
0
        _evict_querying_rowset();
1522
0
        interval = config::quering_rowsets_evict_interval;
1523
0
        if (interval <= 0) {
1524
0
            LOG(WARNING) << "quering_rowsets_evict_interval config is illegal: " << interval
1525
0
                         << ", force set to 1";
1526
0
            interval = 1;
1527
0
        }
1528
0
    } while (!_stop_background_threads_latch.wait_for(std::chrono::seconds(interval)));
1529
0
}
1530
1531
// check whether any unused rowsets's id equal to rowset_id
1532
87
bool StorageEngine::check_rowset_id_in_unused_rowsets(const RowsetId& rowset_id) {
1533
87
    std::lock_guard<std::mutex> lock(_gc_mutex);
1534
87
    return _unused_rowsets.contains(rowset_id);
1535
87
}
1536
1537
60
PendingRowsetGuard StorageEngine::add_pending_rowset(const RowsetWriterContext& ctx) {
1538
60
    if (ctx.is_local_rowset()) {
1539
60
        return _pending_local_rowsets.add(ctx.rowset_id);
1540
60
    }
1541
0
    return _pending_remote_rowsets.add(ctx.rowset_id);
1542
60
}
1543
1544
bool StorageEngine::get_peer_replica_info(int64_t tablet_id, TReplicaInfo* replica,
1545
0
                                          std::string* token) {
1546
0
    TabletSharedPtr tablet = _tablet_manager->get_tablet(tablet_id);
1547
0
    if (tablet == nullptr) {
1548
0
        LOG(WARNING) << "tablet is no longer exist: tablet_id=" << tablet_id;
1549
0
        return false;
1550
0
    }
1551
0
    std::unique_lock<std::mutex> lock(_peer_replica_infos_mutex);
1552
0
    if (_peer_replica_infos.contains(tablet_id) &&
1553
0
        _peer_replica_infos[tablet_id].replica_id != tablet->replica_id()) {
1554
0
        *replica = _peer_replica_infos[tablet_id];
1555
0
        *token = _token;
1556
0
        return true;
1557
0
    }
1558
0
    return false;
1559
0
}
1560
1561
0
bool StorageEngine::get_peers_replica_backends(int64_t tablet_id, std::vector<TBackend>* backends) {
1562
0
    TabletSharedPtr tablet = _tablet_manager->get_tablet(tablet_id);
1563
0
    if (tablet == nullptr) {
1564
0
        LOG(WARNING) << "tablet is no longer exist: tablet_id=" << tablet_id;
1565
0
        return false;
1566
0
    }
1567
0
    int64_t cur_time = UnixMillis();
1568
0
    if (cur_time - _last_get_peers_replica_backends_time_ms < 10000) {
1569
0
        LOG_WARNING("failed to get peers replica backens.")
1570
0
                .tag("tablet_id", tablet_id)
1571
0
                .tag("last time", _last_get_peers_replica_backends_time_ms)
1572
0
                .tag("cur time", cur_time);
1573
0
        return false;
1574
0
    }
1575
0
    LOG_INFO("start get peers replica backends info.").tag("tablet id", tablet_id);
1576
0
    ClusterInfo* cluster_info = ExecEnv::GetInstance()->cluster_info();
1577
0
    if (cluster_info == nullptr) {
1578
0
        LOG(WARNING) << "Have not get FE Master heartbeat yet";
1579
0
        return false;
1580
0
    }
1581
0
    TNetworkAddress master_addr = cluster_info->master_fe_addr;
1582
0
    if (master_addr.hostname.empty() || master_addr.port == 0) {
1583
0
        LOG(WARNING) << "Have not get FE Master heartbeat yet";
1584
0
        return false;
1585
0
    }
1586
0
    TGetTabletReplicaInfosRequest request;
1587
0
    TGetTabletReplicaInfosResult result;
1588
0
    request.tablet_ids.emplace_back(tablet_id);
1589
0
    Status rpc_st = ThriftRpcHelper::rpc<FrontendServiceClient>(
1590
0
            master_addr.hostname, master_addr.port,
1591
0
            [&request, &result](FrontendServiceConnection& client) {
1592
0
                client->getTabletReplicaInfos(result, request);
1593
0
            });
1594
1595
0
    if (!rpc_st.ok()) {
1596
0
        LOG(WARNING) << "Failed to get tablet replica infos, encounter rpc failure, "
1597
0
                        "tablet id: "
1598
0
                     << tablet_id;
1599
0
        return false;
1600
0
    }
1601
0
    std::unique_lock<std::mutex> lock(_peer_replica_infos_mutex);
1602
0
    if (result.tablet_replica_infos.contains(tablet_id)) {
1603
0
        std::vector<TReplicaInfo> reps = result.tablet_replica_infos[tablet_id];
1604
0
        if (reps.empty()) [[unlikely]] {
1605
0
            VLOG_DEBUG << "get_peers_replica_backends reps is empty, maybe this tablet is in "
1606
0
                          "schema change. Go to FE to see more info. Tablet id: "
1607
0
                       << tablet_id;
1608
0
        }
1609
0
        for (const auto& rep : reps) {
1610
0
            if (rep.replica_id != tablet->replica_id()) {
1611
0
                TBackend backend;
1612
0
                backend.__set_host(rep.host);
1613
0
                backend.__set_be_port(rep.be_port);
1614
0
                backend.__set_http_port(rep.http_port);
1615
0
                backend.__set_brpc_port(rep.brpc_port);
1616
0
                if (rep.__isset.is_alive) {
1617
0
                    backend.__set_is_alive(rep.is_alive);
1618
0
                }
1619
0
                if (rep.__isset.backend_id) {
1620
0
                    backend.__set_id(rep.backend_id);
1621
0
                }
1622
0
                backends->emplace_back(backend);
1623
0
                std::stringstream backend_string;
1624
0
                backend.printTo(backend_string);
1625
0
                LOG_INFO("get 1 peer replica backend info.")
1626
0
                        .tag("tablet id", tablet_id)
1627
0
                        .tag("backend info", backend_string.str());
1628
0
            }
1629
0
        }
1630
0
        _last_get_peers_replica_backends_time_ms = UnixMillis();
1631
0
        LOG_INFO("succeed get peers replica backends info.")
1632
0
                .tag("tablet id", tablet_id)
1633
0
                .tag("replica num", backends->size());
1634
0
        return true;
1635
0
    }
1636
0
    return false;
1637
0
}
1638
1639
10
bool StorageEngine::should_fetch_from_peer(int64_t tablet_id) {
1640
10
#ifdef BE_TEST
1641
10
    if (tablet_id % 2 == 0) {
1642
8
        return true;
1643
8
    }
1644
2
    return false;
1645
0
#endif
1646
0
    TabletSharedPtr tablet = _tablet_manager->get_tablet(tablet_id);
1647
0
    if (tablet == nullptr) {
1648
0
        LOG(WARNING) << "tablet is no longer exist: tablet_id=" << tablet_id;
1649
0
        return false;
1650
0
    }
1651
0
    std::unique_lock<std::mutex> lock(_peer_replica_infos_mutex);
1652
0
    if (_peer_replica_infos.contains(tablet_id)) {
1653
0
        return _peer_replica_infos[tablet_id].replica_id != tablet->replica_id();
1654
0
    }
1655
0
    return false;
1656
0
}
1657
1658
// Return json:
1659
// {
1660
//   "CumulativeCompaction": {
1661
//          "/home/disk1" : [10001, 10002],
1662
//          "/home/disk2" : [10003]
1663
//   },
1664
//   "BaseCompaction": {
1665
//          "/home/disk1" : [10001, 10002],
1666
//          "/home/disk2" : [10003]
1667
//   }
1668
// }
1669
0
void StorageEngine::get_compaction_status_json(std::string* result) {
1670
0
    _compaction_submit_registry.jsonfy_compaction_status(result);
1671
0
}
1672
1673
0
void BaseStorageEngine::add_quering_rowset(RowsetSharedPtr rs) {
1674
0
    std::lock_guard<std::mutex> lock(_quering_rowsets_mutex);
1675
0
    _querying_rowsets.emplace(rs->rowset_id(), rs);
1676
0
}
1677
1678
0
RowsetSharedPtr BaseStorageEngine::get_quering_rowset(RowsetId rs_id) {
1679
0
    std::lock_guard<std::mutex> lock(_quering_rowsets_mutex);
1680
0
    auto it = _querying_rowsets.find(rs_id);
1681
0
    if (it != _querying_rowsets.end()) {
1682
0
        return it->second;
1683
0
    }
1684
0
    return nullptr;
1685
0
}
1686
1687
0
void BaseStorageEngine::_evict_querying_rowset() {
1688
0
    {
1689
0
        std::lock_guard<std::mutex> lock(_quering_rowsets_mutex);
1690
0
        for (auto it = _querying_rowsets.begin(); it != _querying_rowsets.end();) {
1691
0
            uint64_t now = UnixSeconds();
1692
            // We delay the GC time of this rowset since it's maybe still needed, see #20732
1693
0
            if (now > it->second->delayed_expired_timestamp()) {
1694
0
                it = _querying_rowsets.erase(it);
1695
0
            } else {
1696
0
                ++it;
1697
0
            }
1698
0
        }
1699
0
    }
1700
1701
0
    uint64_t now = UnixSeconds();
1702
0
    ExecEnv::GetInstance()->get_id_manager()->gc_expired_id_file_map(now);
1703
0
}
1704
1705
3
bool BaseStorageEngine::_should_delay_large_task() {
1706
3
    DCHECK_GE(_cumu_compaction_thread_pool->max_threads(),
1707
3
              _cumu_compaction_thread_pool_used_threads);
1708
3
    DCHECK_GE(_cumu_compaction_thread_pool_small_tasks_running, 0);
1709
    // Case 1: Multiple threads available => accept large task
1710
3
    if (_cumu_compaction_thread_pool->max_threads() - _cumu_compaction_thread_pool_used_threads >
1711
3
        0) {
1712
1
        return false; // No delay needed
1713
1
    }
1714
    // Case 2: Only one thread left => accept large task only if another small task is already running
1715
2
    if (_cumu_compaction_thread_pool_small_tasks_running > 0) {
1716
1
        return false; // No delay needed
1717
1
    }
1718
    // Case 3: Only one thread left, this is a large task, and no small tasks are running
1719
    // Delay this task to reserve capacity for potential small tasks
1720
1
    return true; // Delay this large task
1721
2
}
1722
1723
5
bool StorageEngine::add_broken_path(std::string path) {
1724
5
    std::lock_guard<std::mutex> lock(_broken_paths_mutex);
1725
5
    auto success = _broken_paths.emplace(path).second;
1726
5
    if (success) {
1727
4
        static_cast<void>(_persist_broken_paths());
1728
4
    }
1729
5
    return success;
1730
5
}
1731
1732
3
bool StorageEngine::remove_broken_path(std::string path) {
1733
3
    std::lock_guard<std::mutex> lock(_broken_paths_mutex);
1734
3
    auto count = _broken_paths.erase(path);
1735
3
    if (count > 0) {
1736
3
        static_cast<void>(_persist_broken_paths());
1737
3
    }
1738
3
    return count > 0;
1739
3
}
1740
1741
7
Status StorageEngine::_persist_broken_paths() {
1742
7
    std::string config_value;
1743
7
    for (const std::string& path : _broken_paths) {
1744
6
        config_value += path + ";";
1745
6
    }
1746
1747
7
    if (config_value.length() > 0) {
1748
5
        auto st = config::set_config("broken_storage_path", config_value, true);
1749
5
        LOG(INFO) << "persist broken_storage_path " << config_value << st;
1750
5
        return st;
1751
5
    }
1752
1753
2
    return Status::OK();
1754
7
}
1755
1756
0
Status StorageEngine::submit_clone_task(Tablet* tablet, int64_t version) {
1757
0
    std::vector<TBackend> backends;
1758
0
    if (!get_peers_replica_backends(tablet->tablet_id(), &backends)) {
1759
0
        return Status::Error<ErrorCode::INTERNAL_ERROR, false>(
1760
0
                "get_peers_replica_backends failed.");
1761
0
    }
1762
0
    TAgentTaskRequest task;
1763
0
    TCloneReq req;
1764
0
    req.__set_tablet_id(tablet->tablet_id());
1765
0
    req.__set_schema_hash(tablet->schema_hash());
1766
0
    req.__set_src_backends(backends);
1767
0
    req.__set_version(version);
1768
0
    req.__set_replica_id(tablet->replica_id());
1769
0
    req.__set_partition_id(tablet->partition_id());
1770
0
    req.__set_table_id(tablet->table_id());
1771
0
    task.__set_task_type(TTaskType::CLONE);
1772
0
    task.__set_clone_req(req);
1773
0
    task.__set_priority(TPriority::HIGH);
1774
0
    task.__set_signature(tablet->tablet_id());
1775
0
    LOG_INFO("BE start to submit missing rowset clone task.")
1776
0
            .tag("tablet_id", tablet->tablet_id())
1777
0
            .tag("version", version)
1778
0
            .tag("replica_id", tablet->replica_id())
1779
0
            .tag("partition_id", tablet->partition_id())
1780
0
            .tag("table_id", tablet->table_id());
1781
0
    RETURN_IF_ERROR(assert_cast<PriorTaskWorkerPool*>(workers->at(TTaskType::CLONE).get())
1782
0
                            ->submit_high_prior_and_cancel_low(task));
1783
0
    return Status::OK();
1784
0
}
1785
1786
73
int CreateTabletRRIdxCache::get_index(const std::string& key) {
1787
73
    auto* lru_handle = lookup(key);
1788
73
    if (lru_handle) {
1789
46
        Defer release([cache = this, lru_handle] { cache->release(lru_handle); });
1790
46
        auto* value = (CacheValue*)LRUCachePolicy::value(lru_handle);
1791
46
        VLOG_DEBUG << "use create tablet idx cache key=" << key << " value=" << value->idx;
1792
46
        return value->idx;
1793
46
    }
1794
27
    return -1;
1795
73
}
1796
1797
73
void CreateTabletRRIdxCache::set_index(const std::string& key, int next_idx) {
1798
73
    assert(next_idx >= 0);
1799
73
    auto* value = new CacheValue;
1800
73
    value->idx = next_idx;
1801
73
    auto* lru_handle = insert(key, value, 1, sizeof(int), CachePriority::NORMAL);
1802
73
    release(lru_handle);
1803
73
}
1804
} // namespace doris