Coverage Report

Created: 2026-08-04 11:20

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