Coverage Report

Created: 2026-04-01 18:33

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