Coverage Report

Created: 2026-05-28 14:57

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