Coverage Report

Created: 2026-08-06 19:50

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/storage/data_dir.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/data_dir.h"
19
20
#include <fmt/core.h>
21
#include <fmt/format.h>
22
#include <gen_cpp/FrontendService_types.h>
23
#include <gen_cpp/Types_types.h>
24
#include <gen_cpp/olap_file.pb.h>
25
26
#include <atomic>
27
#include <cstdio>
28
// IWYU pragma: no_include <bits/chrono.h>
29
#include <chrono> // IWYU pragma: keep
30
#include <cstddef>
31
#include <filesystem>
32
#include <map>
33
#include <memory>
34
#include <new>
35
#include <optional>
36
#include <roaring/roaring.hh>
37
#include <set>
38
#include <sstream>
39
#include <string>
40
#include <thread>
41
#include <utility>
42
43
#include "common/cast_set.h"
44
#include "common/config.h"
45
#include "common/logging.h"
46
#include "common/metrics/doris_metrics.h"
47
#include "io/fs/file_reader.h"
48
#include "io/fs/file_writer.h"
49
#include "io/fs/local_file_system.h"
50
#include "io/fs/path.h"
51
#include "service/backend_options.h"
52
#include "storage/delete/delete_handler.h"
53
#include "storage/olap_common.h"
54
#include "storage/olap_define.h"
55
#include "storage/olap_meta.h"
56
#include "storage/rowset/beta_rowset.h"
57
#include "storage/rowset/pending_rowset_helper.h"
58
#include "storage/rowset/rowset.h"
59
#include "storage/rowset/rowset_id_generator.h"
60
#include "storage/rowset/rowset_meta.h"
61
#include "storage/rowset/rowset_meta_manager.h"
62
#include "storage/storage_engine.h"
63
#include "storage/storage_policy.h"
64
#include "storage/tablet/tablet.h"
65
#include "storage/tablet/tablet_manager.h"
66
#include "storage/tablet/tablet_meta_manager.h"
67
#include "storage/txn/txn_manager.h"
68
#include "storage/utils.h" // for check_dir_existed
69
#include "util/string_util.h"
70
#include "util/uid_util.h"
71
72
namespace doris {
73
using namespace ErrorCode;
74
75
namespace {
76
77
219
Status read_cluster_id(const std::string& cluster_id_path, int32_t* cluster_id) {
78
219
    bool exists = false;
79
219
    RETURN_IF_ERROR(io::global_local_filesystem()->exists(cluster_id_path, &exists));
80
219
    *cluster_id = -1;
81
219
    if (exists) {
82
6
        io::FileReaderSPtr reader;
83
6
        RETURN_IF_ERROR(io::global_local_filesystem()->open_file(cluster_id_path, &reader));
84
6
        size_t fsize = reader->size();
85
6
        if (fsize > 0) {
86
6
            std::string content;
87
6
            content.resize(fsize, '\0');
88
6
            size_t bytes_read = 0;
89
6
            RETURN_IF_ERROR(reader->read_at(0, {content.data(), fsize}, &bytes_read));
90
6
            DCHECK_EQ(fsize, bytes_read);
91
6
            *cluster_id = std::stoi(content);
92
6
        }
93
6
    }
94
219
    return Status::OK();
95
219
}
96
97
2
Status _write_cluster_id_to_path(const std::string& path, int32_t cluster_id) {
98
2
    bool exists = false;
99
2
    RETURN_IF_ERROR(io::global_local_filesystem()->exists(path, &exists));
100
2
    if (!exists) {
101
2
        io::FileWriterPtr file_writer;
102
2
        RETURN_IF_ERROR(io::global_local_filesystem()->create_file(path, &file_writer));
103
2
        RETURN_IF_ERROR(file_writer->append(std::to_string(cluster_id)));
104
2
        RETURN_IF_ERROR(file_writer->close());
105
2
    }
106
2
    return Status::OK();
107
2
}
108
109
} // namespace
110
111
DEFINE_GAUGE_METRIC_PROTOTYPE_2ARG(disks_total_capacity, MetricUnit::BYTES);
112
DEFINE_GAUGE_METRIC_PROTOTYPE_2ARG(disks_avail_capacity, MetricUnit::BYTES);
113
DEFINE_GAUGE_METRIC_PROTOTYPE_2ARG(disks_local_used_capacity, MetricUnit::BYTES);
114
DEFINE_GAUGE_METRIC_PROTOTYPE_2ARG(disks_remote_used_capacity, MetricUnit::BYTES);
115
DEFINE_GAUGE_METRIC_PROTOTYPE_2ARG(disks_trash_used_capacity, MetricUnit::BYTES);
116
DEFINE_GAUGE_METRIC_PROTOTYPE_2ARG(disks_state, MetricUnit::BYTES);
117
DEFINE_GAUGE_METRIC_PROTOTYPE_2ARG(disks_compaction_score, MetricUnit::NOUNIT);
118
DEFINE_GAUGE_METRIC_PROTOTYPE_2ARG(disks_compaction_num, MetricUnit::NOUNIT);
119
120
DataDir::DataDir(StorageEngine& engine, const std::string& path, int64_t capacity_bytes,
121
                 TStorageMedium::type storage_medium)
122
408
        : _engine(engine),
123
408
          _path(path),
124
408
          _available_bytes(0),
125
408
          _disk_capacity_bytes(0),
126
408
          _trash_used_bytes(0),
127
408
          _storage_medium(storage_medium),
128
408
          _is_used(false),
129
408
          _cluster_id(-1),
130
408
          _to_be_deleted(false) {
131
408
    _data_dir_metric_entity = DorisMetrics::instance()->metric_registry()->register_entity(
132
408
            std::string("data_dir.") + path, {{"path", path}});
133
408
    INT_GAUGE_METRIC_REGISTER(_data_dir_metric_entity, disks_total_capacity);
134
408
    INT_GAUGE_METRIC_REGISTER(_data_dir_metric_entity, disks_avail_capacity);
135
408
    INT_GAUGE_METRIC_REGISTER(_data_dir_metric_entity, disks_local_used_capacity);
136
408
    INT_GAUGE_METRIC_REGISTER(_data_dir_metric_entity, disks_remote_used_capacity);
137
408
    INT_GAUGE_METRIC_REGISTER(_data_dir_metric_entity, disks_trash_used_capacity);
138
408
    INT_GAUGE_METRIC_REGISTER(_data_dir_metric_entity, disks_state);
139
408
    INT_GAUGE_METRIC_REGISTER(_data_dir_metric_entity, disks_compaction_score);
140
408
    INT_GAUGE_METRIC_REGISTER(_data_dir_metric_entity, disks_compaction_num);
141
408
}
142
143
403
DataDir::~DataDir() {
144
403
    DorisMetrics::instance()->metric_registry()->deregister_entity(_data_dir_metric_entity);
145
403
    delete _meta;
146
403
}
147
148
219
Status DataDir::init(bool init_meta) {
149
219
    bool exists = false;
150
219
    RETURN_IF_ERROR(io::global_local_filesystem()->exists(_path, &exists));
151
219
    if (!exists) {
152
0
        RETURN_NOT_OK_STATUS_WITH_WARN(Status::IOError("opendir failed, path={}", _path),
153
0
                                       "check file exist failed");
154
0
    }
155
156
219
    RETURN_NOT_OK_STATUS_WITH_WARN(update_capacity(), "update_capacity failed");
157
219
    RETURN_NOT_OK_STATUS_WITH_WARN(_init_cluster_id(), "_init_cluster_id failed");
158
219
    RETURN_NOT_OK_STATUS_WITH_WARN(_init_capacity_and_create_shards(),
159
219
                                   "_init_capacity_and_create_shards failed");
160
219
    if (init_meta) {
161
219
        RETURN_NOT_OK_STATUS_WITH_WARN(_init_meta(), "_init_meta failed");
162
219
    }
163
164
219
    _is_used = true;
165
219
    return Status::OK();
166
219
}
167
168
79
void DataDir::stop_bg_worker() {
169
79
    _stop_bg_worker = true;
170
79
}
171
172
219
Status DataDir::_init_cluster_id() {
173
219
    auto cluster_id_path = fmt::format("{}/{}", _path, CLUSTER_ID_PREFIX);
174
219
    RETURN_IF_ERROR(read_cluster_id(cluster_id_path, &_cluster_id));
175
219
    if (_cluster_id == -1) {
176
213
        _cluster_id_incomplete = true;
177
213
    }
178
219
    return Status::OK();
179
219
}
180
181
219
Status DataDir::_init_capacity_and_create_shards() {
182
219
    RETURN_IF_ERROR(io::global_local_filesystem()->get_space_info(_path, &_disk_capacity_bytes,
183
219
                                                                  &_available_bytes));
184
219
    auto data_path = fmt::format("{}/{}", _path, DATA_PREFIX);
185
219
    bool exists = false;
186
219
    RETURN_IF_ERROR(io::global_local_filesystem()->exists(data_path, &exists));
187
219
    if (!exists) {
188
213
        RETURN_IF_ERROR(io::global_local_filesystem()->create_directory(data_path));
189
213
    }
190
224k
    for (int i = 0; i < MAX_SHARD_NUM; ++i) {
191
224k
        auto shard_path = fmt::format("{}/{}", data_path, i);
192
224k
        RETURN_IF_ERROR(io::global_local_filesystem()->exists(shard_path, &exists));
193
224k
        if (!exists) {
194
218k
            RETURN_IF_ERROR(io::global_local_filesystem()->create_directory(shard_path));
195
218k
        }
196
224k
    }
197
198
219
    return Status::OK();
199
219
}
200
201
220
Status DataDir::_init_meta() {
202
    // init path hash
203
220
    _path_hash = hash_of_path(BackendOptions::get_localhost(), _path);
204
220
    LOG(INFO) << "path: " << _path << ", hash: " << _path_hash;
205
206
    // init meta
207
220
    _meta = new (std::nothrow) OlapMeta(_path);
208
220
    if (_meta == nullptr) {
209
0
        RETURN_NOT_OK_STATUS_WITH_WARN(
210
0
                Status::MemoryAllocFailed("allocate memory for OlapMeta failed"),
211
0
                "new OlapMeta failed");
212
0
    }
213
220
    Status res = _meta->init();
214
220
    if (!res.ok()) {
215
0
        RETURN_NOT_OK_STATUS_WITH_WARN(Status::IOError("open rocksdb failed, path={}", _path),
216
0
                                       "init OlapMeta failed");
217
0
    }
218
220
    return Status::OK();
219
220
}
220
221
2
Status DataDir::set_cluster_id(int32_t cluster_id) {
222
2
    if (_cluster_id != -1 && _cluster_id != cluster_id) {
223
0
        LOG(ERROR) << "going to set cluster id to already assigned store, cluster_id="
224
0
                   << _cluster_id << ", new_cluster_id=" << cluster_id;
225
0
        return Status::InternalError("going to set cluster id to already assigned store");
226
0
    }
227
2
    if (!_cluster_id_incomplete) {
228
0
        return Status::OK();
229
0
    }
230
2
    auto cluster_id_path = fmt::format("{}/{}", _path, CLUSTER_ID_PREFIX);
231
2
    return _write_cluster_id_to_path(cluster_id_path, cluster_id);
232
2
}
233
234
2.18k
void DataDir::health_check() {
235
    // check disk
236
2.18k
    if (_is_used) {
237
2.18k
        Status res = _read_and_write_test_file();
238
2.18k
        if (!res && res.is<IO_ERROR>()) {
239
0
            LOG(WARNING) << "store read/write test file occur IO Error. path=" << _path
240
0
                         << ", err: " << res;
241
0
            _engine.add_broken_path(_path);
242
0
            _is_used = !res.is<IO_ERROR>();
243
0
        }
244
2.18k
    }
245
2.18k
    disks_state->set_value(_is_used ? 1 : 0);
246
2.18k
}
247
248
2.18k
Status DataDir::_read_and_write_test_file() {
249
2.18k
    auto test_file = fmt::format("{}/{}", _path, kTestFilePath);
250
2.18k
    return read_write_test_file(test_file);
251
2.18k
}
252
253
286k
void DataDir::register_tablet(Tablet* tablet) {
254
286k
    TabletInfo tablet_info(tablet->tablet_id(), tablet->tablet_uid());
255
256
286k
    std::lock_guard<std::mutex> l(_mutex);
257
286k
    _tablet_set.emplace(std::move(tablet_info));
258
286k
}
259
260
5.94k
void DataDir::deregister_tablet(Tablet* tablet) {
261
5.94k
    TabletInfo tablet_info(tablet->tablet_id(), tablet->tablet_uid());
262
263
5.94k
    std::lock_guard<std::mutex> l(_mutex);
264
5.94k
    _tablet_set.erase(tablet_info);
265
5.94k
}
266
267
0
void DataDir::clear_tablets(std::vector<TabletInfo>* tablet_infos) {
268
0
    std::lock_guard<std::mutex> l(_mutex);
269
270
0
    tablet_infos->insert(tablet_infos->end(), _tablet_set.begin(), _tablet_set.end());
271
0
    _tablet_set.clear();
272
0
}
273
274
0
std::string DataDir::get_absolute_shard_path(int64_t shard_id) {
275
0
    return fmt::format("{}/{}/{}", _path, DATA_PREFIX, shard_id);
276
0
}
277
278
std::string DataDir::get_absolute_tablet_path(int64_t shard_id, int64_t tablet_id,
279
0
                                              int32_t schema_hash) {
280
0
    return fmt::format("{}/{}/{}", get_absolute_shard_path(shard_id), tablet_id, schema_hash);
281
0
}
282
283
0
void DataDir::find_tablet_in_trash(int64_t tablet_id, std::vector<std::string>* paths) {
284
    // path: /root_path/trash/time_label/tablet_id/schema_hash
285
0
    auto trash_path = fmt::format("{}/{}", _path, TRASH_PREFIX);
286
0
    bool exists = true;
287
0
    std::vector<io::FileInfo> sub_dirs;
288
0
    Status st = io::global_local_filesystem()->list(trash_path, false, &sub_dirs, &exists);
289
0
    if (!st) {
290
0
        return;
291
0
    }
292
293
0
    for (auto& sub_dir : sub_dirs) {
294
        // sub dir is time_label
295
0
        if (sub_dir.is_file) {
296
0
            continue;
297
0
        }
298
0
        auto sub_path = fmt::format("{}/{}", trash_path, sub_dir.file_name);
299
0
        auto tablet_path = fmt::format("{}/{}", sub_path, tablet_id);
300
0
        st = io::global_local_filesystem()->exists(tablet_path, &exists);
301
0
        if (st && exists) {
302
0
            paths->emplace_back(std::move(tablet_path));
303
0
        }
304
0
    }
305
0
}
306
307
std::string DataDir::get_root_path_from_schema_hash_path_in_trash(
308
0
        const std::string& schema_hash_dir_in_trash) {
309
0
    return io::Path(schema_hash_dir_in_trash)
310
0
            .parent_path()
311
0
            .parent_path()
312
0
            .parent_path()
313
0
            .parent_path()
314
0
            .string();
315
0
}
316
317
84
Status DataDir::_check_incompatible_old_format_tablet() {
318
84
    auto check_incompatible_old_func = [](int64_t tablet_id, int32_t schema_hash,
319
84
                                          std::string_view value) -> bool {
320
        // if strict check incompatible old format, then log fatal
321
0
        if (config::storage_strict_check_incompatible_old_format) {
322
0
            throw Exception(Status::FatalError(
323
0
                    "There are incompatible old format metas, current version does not support and "
324
0
                    "it may lead to data missing!!! tablet_id = {} schema_hash = {}",
325
0
                    tablet_id, schema_hash));
326
0
        } else {
327
0
            LOG(WARNING)
328
0
                    << "There are incompatible old format metas, current version does not support "
329
0
                    << "and it may lead to data missing!!! "
330
0
                    << "tablet_id = " << tablet_id << " schema_hash = " << schema_hash;
331
0
        }
332
0
        return false;
333
0
    };
334
335
    // seek old header prefix. when check_incompatible_old_func is called, it has old format in olap_meta
336
84
    Status check_incompatible_old_status = TabletMetaManager::traverse_headers(
337
84
            _meta, check_incompatible_old_func, OLD_HEADER_PREFIX);
338
84
    if (!check_incompatible_old_status) {
339
0
        LOG(WARNING) << "check incompatible old format meta fails, it may lead to data missing!!! "
340
0
                     << _path;
341
84
    } else {
342
84
        LOG(INFO) << "successfully check incompatible old format meta " << _path;
343
84
    }
344
84
    return check_incompatible_old_status;
345
84
}
346
347
// TODO(ygl): deal with rowsets and tablets when load failed
348
84
Status DataDir::load() {
349
84
    LOG(INFO) << "start to load tablets from " << _path;
350
351
    // load rowset meta from meta env and create rowset
352
    // COMMITTED: add to txn manager
353
    // VISIBLE: add to tablet
354
    // if one rowset load failed, then the total data dir will not be loaded
355
356
    // necessarily check incompatible old format. when there are old metas, it may load to data missing
357
84
    RETURN_IF_ERROR(_check_incompatible_old_format_tablet());
358
359
84
    std::vector<RowsetMetaSharedPtr> dir_rowset_metas;
360
84
    LOG(INFO) << "begin loading rowset from meta";
361
84
    auto load_rowset_func = [&dir_rowset_metas, this](TabletUid tablet_uid, RowsetId rowset_id,
362
1.61k
                                                      std::string_view meta_str) -> bool {
363
1.61k
        RowsetMetaSharedPtr rowset_meta(new RowsetMeta());
364
1.61k
        bool parsed = rowset_meta->init(meta_str);
365
1.61k
        if (!parsed) {
366
0
            LOG(WARNING) << "parse rowset meta string failed for rowset_id:" << rowset_id;
367
            // return false will break meta iterator, return true to skip this error
368
0
            return true;
369
0
        }
370
371
1.61k
        if (rowset_meta->has_delete_predicate()) {
372
            // copy the delete sub pred v1 to check then
373
35
            auto orig_delete_sub_pred = rowset_meta->delete_predicate().sub_predicates();
374
35
            auto* delete_pred = rowset_meta->mutable_delete_pred_pb();
375
376
35
            if ((!delete_pred->sub_predicates().empty() &&
377
35
                 delete_pred->sub_predicates_v2().empty()) ||
378
35
                (!delete_pred->in_predicates().empty() &&
379
35
                 delete_pred->in_predicates()[0].has_column_unique_id())) {
380
                // convert pred and write only when delete sub pred v2 is not set or there is in list pred to be set column uid
381
0
                RETURN_IF_ERROR(DeleteHandler::convert_to_sub_pred_v2(
382
0
                        delete_pred, rowset_meta->tablet_schema()));
383
0
                LOG(INFO) << fmt::format(
384
0
                        "convert rowset with old delete pred: rowset_id={}, tablet_id={}",
385
0
                        rowset_id.to_string(), tablet_uid.to_string());
386
0
                CHECK_EQ(orig_delete_sub_pred.size(), delete_pred->sub_predicates().size())
387
0
                        << "inconsistent sub predicate v1 after conversion";
388
0
                for (int i = 0; i < orig_delete_sub_pred.size(); ++i) {
389
0
                    CHECK_STREQ(orig_delete_sub_pred.Get(i).c_str(),
390
0
                                delete_pred->sub_predicates().Get(i).c_str())
391
0
                            << "inconsistent sub predicate v1 after conversion";
392
0
                }
393
0
                std::string result;
394
0
                rowset_meta->serialize(&result);
395
0
                std::string key =
396
0
                        ROWSET_PREFIX + tablet_uid.to_string() + "_" + rowset_id.to_string();
397
0
                RETURN_IF_ERROR(_meta->put(META_COLUMN_FAMILY_INDEX, key, result));
398
0
            }
399
35
        }
400
401
1.61k
        if (rowset_meta->partition_id() == 0) {
402
0
            LOG(WARNING) << "rs tablet=" << rowset_meta->tablet_id() << " rowset_id=" << rowset_id
403
0
                         << " load from meta but partition id eq 0";
404
0
        }
405
406
1.61k
        dir_rowset_metas.push_back(rowset_meta);
407
1.61k
        return true;
408
1.61k
    };
409
84
    MonotonicStopWatch rs_timer;
410
84
    rs_timer.start();
411
84
    Status load_rowset_status = RowsetMetaManager::traverse_rowset_metas(_meta, load_rowset_func);
412
84
    rs_timer.stop();
413
84
    if (!load_rowset_status) {
414
0
        LOG(WARNING) << "errors when load rowset meta from meta env, skip this data dir:" << _path;
415
84
    } else {
416
84
        LOG(INFO) << "load rowset from meta finished, cost: "
417
84
                  << rs_timer.elapsed_time_milliseconds() << " ms, data dir: " << _path;
418
84
    }
419
420
    // load tablet
421
    // create tablet from tablet meta and add it to tablet mgr
422
84
    LOG(INFO) << "begin loading tablet from meta";
423
84
    std::set<int64_t> tablet_ids;
424
84
    std::set<int64_t> failed_tablet_ids;
425
84
    auto load_tablet_func = [this, &tablet_ids, &failed_tablet_ids](
426
84
                                    int64_t tablet_id, int32_t schema_hash,
427
278k
                                    std::string_view value) -> bool {
428
278k
        Status status = _engine.tablet_manager()->load_tablet_from_meta(
429
278k
                this, tablet_id, schema_hash, value, false, false, false, false);
430
278k
        if (!status.ok() && !status.is<TABLE_ALREADY_DELETED_ERROR>() &&
431
278k
            !status.is<ENGINE_INSERT_OLD_TABLET>()) {
432
            // load_tablet_from_meta() may return Status::Error<TABLE_ALREADY_DELETED_ERROR>()
433
            // which means the tablet status is DELETED
434
            // This may happen when the tablet was just deleted before the BE restarted,
435
            // but it has not been cleared from rocksdb. At this time, restarting the BE
436
            // will read the tablet in the DELETE state from rocksdb. These tablets have been
437
            // added to the garbage collection queue and will be automatically deleted afterwards.
438
            // Therefore, we believe that this situation is not a failure.
439
440
            // Besides, load_tablet_from_meta() may return Status::Error<ENGINE_INSERT_OLD_TABLET>()
441
            // when BE is restarting and the older tablet have been added to the
442
            // garbage collection queue but not deleted yet.
443
            // In this case, since the data_dirs are parallel loaded, a later loaded tablet
444
            // may be older than previously loaded one, which should not be acknowledged as a
445
            // failure.
446
0
            LOG(WARNING) << "load tablet from header failed. status:" << status
447
0
                         << ", tablet=" << tablet_id << "." << schema_hash;
448
0
            failed_tablet_ids.insert(tablet_id);
449
278k
        } else {
450
278k
            tablet_ids.insert(tablet_id);
451
278k
        }
452
278k
        return true;
453
278k
    };
454
84
    MonotonicStopWatch tablet_timer;
455
84
    tablet_timer.start();
456
84
    Status load_tablet_status = TabletMetaManager::traverse_headers(_meta, load_tablet_func);
457
84
    tablet_timer.stop();
458
84
    if (!failed_tablet_ids.empty()) {
459
0
        LOG(WARNING) << "load tablets from header failed"
460
0
                     << ", loaded tablet: " << tablet_ids.size()
461
0
                     << ", error tablet: " << failed_tablet_ids.size() << ", path: " << _path;
462
0
        if (!config::ignore_load_tablet_failure) {
463
0
            throw Exception(Status::FatalError(
464
0
                    "load tablets encounter failure. stop BE process. path: {}", _path));
465
0
        }
466
0
    }
467
84
    if (!load_tablet_status) {
468
0
        LOG(WARNING) << "there is failure when loading tablet headers"
469
0
                     << ", loaded tablet: " << tablet_ids.size()
470
0
                     << ", error tablet: " << failed_tablet_ids.size() << ", path: " << _path;
471
84
    } else {
472
84
        LOG(INFO) << "load tablet from meta finished"
473
84
                  << ", loaded tablet: " << tablet_ids.size()
474
84
                  << ", error tablet: " << failed_tablet_ids.size()
475
84
                  << ", cost: " << tablet_timer.elapsed_time_milliseconds()
476
84
                  << " ms, path: " << _path;
477
84
    }
478
479
278k
    for (int64_t tablet_id : tablet_ids) {
480
278k
        TabletSharedPtr tablet = _engine.tablet_manager()->get_tablet(tablet_id);
481
278k
        if (tablet && tablet->set_tablet_schema_into_rowset_meta()) {
482
0
            RETURN_IF_ERROR(TabletMetaManager::save(this, tablet->tablet_id(),
483
0
                                                    tablet->schema_hash(), tablet->tablet_meta()));
484
0
        }
485
278k
    }
486
487
84
    auto load_pending_publish_info_func = [&engine = _engine](int64_t tablet_id,
488
84
                                                              int64_t publish_version,
489
84
                                                              std::string_view info) {
490
0
        PendingPublishInfoPB pending_publish_info_pb;
491
0
        bool parsed =
492
0
                pending_publish_info_pb.ParseFromArray(info.data(), cast_set<int>(info.size()));
493
0
        if (!parsed) {
494
0
            LOG(WARNING) << "parse pending publish info failed, tablet_id: " << tablet_id
495
0
                         << " publish_version: " << publish_version;
496
0
        }
497
0
        engine.add_async_publish_task(pending_publish_info_pb.partition_id(), tablet_id,
498
0
                                      publish_version, pending_publish_info_pb.transaction_id(),
499
0
                                      true, pending_publish_info_pb.commit_tso());
500
0
        return true;
501
0
    };
502
84
    MonotonicStopWatch pending_publish_timer;
503
84
    pending_publish_timer.start();
504
84
    RETURN_IF_ERROR(
505
84
            TabletMetaManager::traverse_pending_publish(_meta, load_pending_publish_info_func));
506
84
    pending_publish_timer.stop();
507
84
    LOG(INFO) << "load pending publish task from meta finished, cost: "
508
84
              << pending_publish_timer.elapsed_time_milliseconds() << " ms, data dir: " << _path;
509
510
84
    int64_t rowset_partition_id_eq_0_num = 0;
511
1.61k
    for (auto rowset_meta : dir_rowset_metas) {
512
1.61k
        if (rowset_meta->partition_id() == 0) {
513
0
            ++rowset_partition_id_eq_0_num;
514
0
        }
515
1.61k
    }
516
84
    if (rowset_partition_id_eq_0_num > config::ignore_invalid_partition_id_rowset_num) {
517
0
        throw Exception(Status::FatalError(
518
0
                "rowset partition id eq 0 is {} bigger than config {}, be exit, plz check be.INFO",
519
0
                rowset_partition_id_eq_0_num, config::ignore_invalid_partition_id_rowset_num));
520
0
    }
521
522
    // Row binlog rowset is now a normal rowset under its own binlog tablet, loaded above.
523
    // Index them by txn id so each base rowset can re-attach its paired binlog rowset on recovery.
524
84
    std::map<int64_t, RowsetMetaSharedPtr> txn_id_to_row_binlog_meta;
525
1.61k
    for (auto&& rowset_meta : dir_rowset_metas) {
526
1.61k
        if (rowset_meta->is_row_binlog()) {
527
94
            txn_id_to_row_binlog_meta[rowset_meta->txn_id()] = rowset_meta;
528
94
        }
529
1.61k
    }
530
531
    // traverse rowset
532
    // 1. add committed rowset to txn map
533
    // 2. add visible rowset to tablet
534
    // ignore any errors when load tablet or rowset, because fe will repair them after report
535
84
    int64_t invalid_rowset_counter = 0;
536
1.61k
    for (auto&& rowset_meta : dir_rowset_metas) {
537
1.61k
        TabletSharedPtr tablet = _engine.tablet_manager()->get_tablet(rowset_meta->tablet_id());
538
        // tablet maybe dropped, but not drop related rowset meta
539
1.61k
        if (tablet == nullptr) {
540
0
            VLOG_NOTICE << "could not find tablet id: " << rowset_meta->tablet_id()
541
0
                        << ", schema hash: " << rowset_meta->tablet_schema_hash()
542
0
                        << ", for rowset: " << rowset_meta->rowset_id() << ", skip this rowset";
543
0
            ++invalid_rowset_counter;
544
0
            continue;
545
0
        }
546
547
1.61k
        if (rowset_meta->partition_id() == 0) {
548
0
            LOG(WARNING) << "skip tablet_id=" << tablet->tablet_id()
549
0
                         << " rowset: " << rowset_meta->rowset_id()
550
0
                         << " txn: " << rowset_meta->txn_id();
551
0
            continue;
552
0
        }
553
554
        // Committed row binlog rowset is recovered with base rowset.
555
1.61k
        if (rowset_meta->is_row_binlog() &&
556
1.61k
            rowset_meta->rowset_state() == RowsetStatePB::COMMITTED) {
557
0
            continue;
558
0
        }
559
560
1.61k
        RowBinlogTxnInfo attach_row_binlog;
561
1.61k
        if (auto it = txn_id_to_row_binlog_meta.find(rowset_meta->txn_id());
562
1.61k
            it != txn_id_to_row_binlog_meta.end()) {
563
188
            const RowsetMetaSharedPtr& attach_row_binlog_rowset_meta = it->second;
564
188
            DCHECK_EQ(attach_row_binlog_rowset_meta->rowset_state(), rowset_meta->rowset_state());
565
188
            TabletSharedPtr binlog_tablet = _engine.tablet_manager()->get_tablet(
566
188
                    attach_row_binlog_rowset_meta->tablet_id());
567
188
            if (binlog_tablet == nullptr) {
568
0
                LOG(WARNING) << "could not find binlog tablet: "
569
0
                             << attach_row_binlog_rowset_meta->tablet_id()
570
0
                             << " for binlog<row> rowset: "
571
0
                             << attach_row_binlog_rowset_meta->rowset_id();
572
0
                ++invalid_rowset_counter;
573
0
                continue;
574
0
            }
575
188
            if (!attach_row_binlog_rowset_meta->tablet_schema()) {
576
0
                attach_row_binlog_rowset_meta->set_tablet_schema(binlog_tablet->tablet_schema());
577
0
            }
578
188
            Status attach_create_status = binlog_tablet->create_rowset(
579
188
                    attach_row_binlog_rowset_meta, &attach_row_binlog.rowset);
580
188
            if (!attach_create_status.ok()) {
581
0
                LOG(WARNING) << "could not create rowset from binlog<row> rowset meta: "
582
0
                             << " rowset_id: " << attach_row_binlog_rowset_meta->rowset_id()
583
0
                             << " rowset_type: " << attach_row_binlog_rowset_meta->rowset_type()
584
0
                             << " rowset_state: " << attach_row_binlog_rowset_meta->rowset_state();
585
0
                ++invalid_rowset_counter;
586
0
                continue;
587
0
            }
588
188
            attach_row_binlog.tablet = std::move(binlog_tablet);
589
188
        }
590
591
1.61k
        RowsetSharedPtr rowset;
592
1.61k
        Status create_status = tablet->create_rowset(rowset_meta, &rowset);
593
1.61k
        if (!create_status) {
594
0
            LOG(WARNING) << "could not create rowset from rowsetmeta: "
595
0
                         << " rowset_id: " << rowset_meta->rowset_id()
596
0
                         << " rowset_type: " << rowset_meta->rowset_type()
597
0
                         << " rowset_state: " << rowset_meta->rowset_state();
598
0
            continue;
599
0
        }
600
601
1.61k
        std::optional<BinlogFormatPB> binlog_format = std::nullopt;
602
1.61k
        std::optional<RowsetMetaPB> attach_row_binlog_rowset_meta;
603
1.61k
        if (attach_row_binlog.rowset != nullptr) {
604
188
            binlog_format = BinlogFormatPB::ROW;
605
188
            attach_row_binlog_rowset_meta =
606
188
                    attach_row_binlog.rowset->rowset_meta()->get_rowset_pb();
607
188
        }
608
609
1.61k
        std::string attach_binlog_rowset_id =
610
1.61k
                attach_row_binlog.rowset != nullptr
611
1.61k
                        ? attach_row_binlog.rowset->rowset_id().to_string()
612
1.61k
                        : "0";
613
614
1.61k
        if (rowset_meta->rowset_state() == RowsetStatePB::COMMITTED &&
615
1.61k
            rowset_meta->tablet_uid() == tablet->tablet_uid()) {
616
157
            if (!rowset_meta->tablet_schema()) {
617
0
                rowset_meta->set_tablet_schema(tablet->tablet_schema());
618
0
                RETURN_IF_ERROR(RowsetMetaManager::save(_meta, rowset_meta->tablet_uid(),
619
0
                                                        rowset_meta->rowset_id(),
620
0
                                                        rowset_meta->get_rowset_pb(), binlog_format,
621
0
                                                        attach_row_binlog_rowset_meta));
622
0
            }
623
157
            std::vector<RowsetId> rowset_ids {rowset_meta->rowset_id()};
624
157
            if (attach_row_binlog.rowset != nullptr) {
625
0
                rowset_ids.emplace_back(attach_row_binlog.rowset->rowset_id());
626
0
            }
627
157
            Status commit_txn_status = _engine.txn_manager()->commit_txn(
628
157
                    _meta, rowset_meta->partition_id(), rowset_meta->txn_id(),
629
157
                    rowset_meta->tablet_id(), rowset_meta->tablet_uid(), rowset_meta->load_id(),
630
157
                    rowset, _engine.pending_local_rowsets().add(rowset_ids), true, nullptr,
631
157
                    attach_row_binlog);
632
157
            if (commit_txn_status || commit_txn_status.is<PUSH_TRANSACTION_ALREADY_EXIST>()) {
633
157
                LOG(INFO) << "successfully to add committed rowset: " << rowset_meta->rowset_id()
634
157
                          << " to tablet: " << rowset_meta->tablet_id()
635
157
                          << " schema hash: " << rowset_meta->tablet_schema_hash()
636
157
                          << " for txn: " << rowset_meta->txn_id()
637
157
                          << ", binlog<row> rowset: " << attach_binlog_rowset_id;
638
639
157
            } else if (commit_txn_status.is<ErrorCode::INTERNAL_ERROR>()) {
640
0
                LOG(WARNING) << "failed to add committed rowset: " << rowset_meta->rowset_id()
641
0
                             << " to tablet: " << rowset_meta->tablet_id()
642
0
                             << " for txn: " << rowset_meta->txn_id()
643
0
                             << " error: " << commit_txn_status
644
0
                             << ", binlog<row> rowset: " << attach_binlog_rowset_id;
645
0
                return commit_txn_status;
646
0
            } else {
647
0
                LOG(WARNING) << "failed to add committed rowset: " << rowset_meta->rowset_id()
648
0
                             << " to tablet: " << rowset_meta->tablet_id()
649
0
                             << " for txn: " << rowset_meta->txn_id()
650
0
                             << " error: " << commit_txn_status
651
0
                             << ", binlog<row> rowset: " << attach_binlog_rowset_id;
652
0
            }
653
1.45k
        } else if (rowset_meta->rowset_state() == RowsetStatePB::VISIBLE &&
654
1.45k
                   rowset_meta->tablet_uid() == tablet->tablet_uid()) {
655
1.45k
            if (!rowset_meta->tablet_schema()) {
656
0
                rowset_meta->set_tablet_schema(tablet->tablet_schema());
657
0
                RETURN_IF_ERROR(RowsetMetaManager::save(_meta, rowset_meta->tablet_uid(),
658
0
                                                        rowset_meta->rowset_id(),
659
0
                                                        rowset_meta->get_rowset_pb(), binlog_format,
660
0
                                                        attach_row_binlog_rowset_meta));
661
0
            }
662
1.45k
            Status publish_status = tablet->add_rowset(rowset);
663
1.45k
            if (!publish_status && !publish_status.is<PUSH_VERSION_ALREADY_EXIST>()) {
664
0
                LOG(WARNING) << "add visible rowset to tablet failed rowset_id:"
665
0
                             << rowset->rowset_id() << " tablet id: " << rowset_meta->tablet_id()
666
0
                             << " txn id:" << rowset_meta->txn_id()
667
0
                             << " start_version: " << rowset_meta->version().first
668
0
                             << " end_version: " << rowset_meta->version().second
669
0
                             << ", binlog<row> rowset: " << attach_binlog_rowset_id;
670
0
            }
671
1.45k
        } else {
672
0
            LOG(WARNING) << "find invalid rowset: " << rowset_meta->rowset_id()
673
0
                         << " with tablet id: " << rowset_meta->tablet_id()
674
0
                         << " tablet uid: " << rowset_meta->tablet_uid()
675
0
                         << " schema hash: " << rowset_meta->tablet_schema_hash()
676
0
                         << " txn: " << rowset_meta->txn_id()
677
0
                         << " current valid tablet uid: " << tablet->tablet_uid()
678
0
                         << ", binlog<row> rowset: " << attach_binlog_rowset_id;
679
0
            ++invalid_rowset_counter;
680
0
        }
681
1.61k
    }
682
683
84
    int64_t dbm_cnt {0};
684
84
    int64_t unknown_dbm_cnt {0};
685
84
    auto load_delete_bitmap_func = [this, &dbm_cnt, &unknown_dbm_cnt](int64_t tablet_id,
686
84
                                                                      int64_t version,
687
84
                                                                      std::string_view val) {
688
59
        TabletSharedPtr tablet = _engine.tablet_manager()->get_tablet(tablet_id);
689
59
        if (!tablet) {
690
0
            return true;
691
0
        }
692
59
        RowsetIdUnorderedSet rowset_ids;
693
260
        for (const auto& [_, rowset_meta] : tablet->tablet_meta()->all_rs_metas()) {
694
260
            rowset_ids.insert(rowset_meta->rowset_id());
695
260
        }
696
697
59
        DeleteBitmapPB delete_bitmap_pb;
698
59
        delete_bitmap_pb.ParseFromArray(val.data(), cast_set<int>(val.size()));
699
59
        int rst_ids_size = delete_bitmap_pb.rowset_ids_size();
700
59
        int seg_ids_size = delete_bitmap_pb.segment_ids_size();
701
59
        int seg_maps_size = delete_bitmap_pb.segment_delete_bitmaps_size();
702
59
        CHECK(rst_ids_size == seg_ids_size && seg_ids_size == seg_maps_size);
703
704
207
        for (int i = 0; i < rst_ids_size; ++i) {
705
148
            RowsetId rst_id;
706
148
            rst_id.init(delete_bitmap_pb.rowset_ids(i));
707
            // only process rowsets in current tablet meta.
708
148
            if (rowset_ids.find(rst_id) == rowset_ids.end()) {
709
1
                ++unknown_dbm_cnt;
710
1
                continue;
711
1
            }
712
147
            ++dbm_cnt;
713
147
            auto seg_id = delete_bitmap_pb.segment_ids(i);
714
147
            auto iter = tablet->tablet_meta()->delete_bitmap().delete_bitmap.find(
715
147
                    {rst_id, seg_id, version});
716
            // This version of delete bitmap already exists
717
147
            if (iter != tablet->tablet_meta()->delete_bitmap().delete_bitmap.end()) {
718
0
                continue;
719
0
            }
720
147
            auto bitmap = delete_bitmap_pb.segment_delete_bitmaps(i).data();
721
722
147
            tablet->tablet_meta()->delete_bitmap().delete_bitmap[{rst_id, seg_id, version}] =
723
147
                    roaring::Roaring::read(bitmap);
724
147
            VLOG_ROW << "successfully to add delete_bitmap, tablet_id=" << tablet->tablet_id()
725
0
                     << ", rowset_id=" << rst_id << ", seg_id=" << seg_id
726
0
                     << ", version=" << version;
727
147
        }
728
59
        return true;
729
59
    };
730
84
    MonotonicStopWatch dbm_timer;
731
84
    dbm_timer.start();
732
84
    RETURN_IF_ERROR(TabletMetaManager::traverse_delete_bitmap(_meta, load_delete_bitmap_func));
733
84
    dbm_timer.stop();
734
735
84
    LOG(INFO) << "load delete bitmap from meta finished, cost: "
736
84
              << dbm_timer.elapsed_time_milliseconds() << " ms, data dir: " << _path;
737
738
    // At startup, we only count these invalid rowset, but do not actually delete it.
739
    // The actual delete operation is in StorageEngine::_clean_unused_rowset_metas,
740
    // which is cleaned up uniformly by the background cleanup thread.
741
84
    LOG(INFO) << "finish to load tablets from " << _path
742
84
              << ", total rowset meta: " << dir_rowset_metas.size()
743
84
              << ", invalid rowset num: " << invalid_rowset_counter
744
84
              << ", visible/stale rowsets' delete bitmap count: " << dbm_cnt
745
84
              << ", invalid rowsets' delete bitmap count: " << unknown_dbm_cnt;
746
747
84
    return Status::OK();
748
84
}
749
750
// gc unused local tablet dir
751
283k
void DataDir::_perform_tablet_gc(const std::string& tablet_schema_hash_path, int16_t shard_id) {
752
283k
    if (_stop_bg_worker) {
753
0
        return;
754
0
    }
755
756
283k
    TTabletId tablet_id = -1;
757
283k
    TSchemaHash schema_hash = -1;
758
283k
    bool is_valid = TabletManager::get_tablet_id_and_schema_hash_from_path(
759
283k
            tablet_schema_hash_path, &tablet_id, &schema_hash);
760
283k
    if (!is_valid || tablet_id < 1 || schema_hash < 1) [[unlikely]] {
761
0
        LOG(WARNING) << "[path gc] unknown path: " << tablet_schema_hash_path;
762
0
        return;
763
0
    }
764
765
283k
    auto tablet = _engine.tablet_manager()->get_tablet(tablet_id);
766
283k
    if (!tablet || tablet->data_dir() != this) {
767
420
        if (tablet) {
768
0
            LOG(INFO) << "The tablet in path " << tablet_schema_hash_path
769
0
                      << " is not same with the running one: " << tablet->tablet_path()
770
0
                      << ", might be the old tablet after migration, try to move it to trash";
771
0
        }
772
420
        _engine.tablet_manager()->try_delete_unused_tablet_path(this, tablet_id, schema_hash,
773
420
                                                                tablet_schema_hash_path, shard_id);
774
420
        return;
775
420
    }
776
777
283k
    _perform_rowset_gc(tablet_schema_hash_path);
778
283k
}
779
780
// gc unused local rowsets under tablet dir
781
283k
void DataDir::_perform_rowset_gc(const std::string& tablet_schema_hash_path) {
782
283k
    if (_stop_bg_worker) {
783
0
        return;
784
0
    }
785
786
283k
    TTabletId tablet_id = -1;
787
283k
    TSchemaHash schema_hash = -1;
788
283k
    bool is_valid = doris::TabletManager::get_tablet_id_and_schema_hash_from_path(
789
283k
            tablet_schema_hash_path, &tablet_id, &schema_hash);
790
283k
    if (!is_valid || tablet_id < 1 || schema_hash < 1) [[unlikely]] {
791
0
        LOG(WARNING) << "[path gc] unknown path: " << tablet_schema_hash_path;
792
0
        return;
793
0
    }
794
795
283k
    auto tablet = _engine.tablet_manager()->get_tablet(tablet_id);
796
283k
    if (!tablet) {
797
        // Could not found the tablet, maybe it's a dropped tablet, will be reclaimed
798
        // in the next time `_perform_path_gc_by_tablet`
799
0
        return;
800
0
    }
801
802
283k
    if (tablet->data_dir() != this) {
803
        // Current running tablet is not in same data_dir, maybe it's a tablet after migration,
804
        // will be reclaimed in the next time `_perform_path_gc_by_tablet`
805
0
        return;
806
0
    }
807
808
283k
    bool exists;
809
283k
    std::vector<io::FileInfo> files;
810
283k
    auto st = io::global_local_filesystem()->list(tablet_schema_hash_path, true, &files, &exists);
811
283k
    if (!st.ok()) [[unlikely]] {
812
0
        LOG(WARNING) << "[path gc] fail to list tablet path " << tablet_schema_hash_path << " : "
813
0
                     << st;
814
0
        return;
815
0
    }
816
817
    // Rowset files excluding pending rowsets
818
283k
    std::vector<std::pair<RowsetId, std::string /* filename */>> rowsets_not_pending;
819
283k
    for (auto&& file : files) {
820
88.6k
        auto rowset_id = extract_rowset_id(file.file_name);
821
88.6k
        if (rowset_id.hi == 0) {
822
216
            continue; // Not a rowset
823
216
        }
824
825
88.4k
        if (_engine.pending_local_rowsets().contains(rowset_id)) {
826
132
            continue; // Pending rowset file
827
132
        }
828
829
88.3k
        rowsets_not_pending.emplace_back(rowset_id, std::move(file.file_name));
830
88.3k
    }
831
832
283k
    RowsetIdUnorderedSet rowsets_in_version_map;
833
283k
    tablet->traverse_rowsets(
834
505k
            [&rowsets_in_version_map](auto& rs) { rowsets_in_version_map.insert(rs->rowset_id()); },
835
283k
            true);
836
837
283k
    DBUG_EXECUTE_IF("DataDir::_perform_rowset_gc.simulation.slow", {
838
283k
        auto target_tablet_id = dp->param<int64_t>("tablet_id", -1);
839
283k
        if (target_tablet_id == tablet_id) {
840
283k
            LOG(INFO) << "debug point wait tablet to remove rsmgr tabletId=" << tablet_id;
841
283k
            DBUG_BLOCK;
842
283k
        }
843
283k
    });
844
845
283k
    auto reclaim_rowset_file = [](const std::string& path) {
846
1.15k
        auto st = io::global_local_filesystem()->delete_file(path);
847
1.15k
        if (!st.ok()) [[unlikely]] {
848
0
            LOG(WARNING) << "[path gc] failed to delete garbage rowset file: " << st;
849
0
            return;
850
0
        }
851
1.15k
        LOG(INFO) << "[path gc] delete garbage path: " << path; // Audit log
852
1.15k
    };
853
854
283k
    auto should_reclaim = [&, this](const RowsetId& rowset_id) {
855
81.2k
        return !rowsets_in_version_map.contains(rowset_id) &&
856
81.2k
               !_engine.check_rowset_id_in_unused_rowsets(rowset_id) &&
857
81.2k
               RowsetMetaManager::exists(get_meta(), tablet->tablet_uid(), rowset_id)
858
1.22k
                       .is<META_KEY_NOT_FOUND>();
859
81.2k
    };
860
861
    // rowset_id -> is_garbage
862
283k
    std::unordered_map<RowsetId, bool> checked_rowsets;
863
283k
    for (auto&& [rowset_id, filename] : rowsets_not_pending) {
864
88.3k
        if (_stop_bg_worker) {
865
0
            return;
866
0
        }
867
868
88.3k
        if (auto it = checked_rowsets.find(rowset_id); it != checked_rowsets.end()) {
869
6.98k
            if (it->second) { // Is checked garbage rowset
870
60
                reclaim_rowset_file(tablet_schema_hash_path + '/' + filename);
871
60
            }
872
6.98k
            continue;
873
6.98k
        }
874
875
81.3k
        if (should_reclaim(rowset_id)) {
876
1.17k
            if (config::path_gc_check_step > 0 &&
877
1.17k
                ++_path_gc_step % config::path_gc_check_step == 0) {
878
0
                std::this_thread::sleep_for(
879
0
                        std::chrono::milliseconds(config::path_gc_check_step_interval_ms));
880
0
            }
881
1.17k
            reclaim_rowset_file(tablet_schema_hash_path + '/' + filename);
882
1.17k
            checked_rowsets.emplace(rowset_id, true);
883
80.1k
        } else {
884
80.1k
            checked_rowsets.emplace(rowset_id, false);
885
80.1k
        }
886
81.3k
    }
887
283k
}
888
889
13
void DataDir::perform_path_gc() {
890
13
    if (_stop_bg_worker) {
891
0
        return;
892
0
    }
893
894
13
    LOG(INFO) << "start to gc data dir " << _path;
895
13
    auto data_path = fmt::format("{}/{}", _path, DATA_PREFIX);
896
13
    std::vector<io::FileInfo> shards;
897
13
    bool exists = true;
898
13
    const auto& fs = io::global_local_filesystem();
899
13
    auto st = fs->list(data_path, false, &shards, &exists);
900
13
    if (!st.ok()) [[unlikely]] {
901
0
        LOG(WARNING) << "failed to scan data dir: " << st;
902
0
        return;
903
0
    }
904
905
12.2k
    for (const auto& shard : shards) {
906
12.2k
        if (_stop_bg_worker) {
907
0
            break;
908
0
        }
909
910
12.2k
        if (shard.is_file) {
911
0
            continue;
912
0
        }
913
914
12.2k
        auto shard_path = fmt::format("{}/{}", data_path, shard.file_name);
915
12.2k
        std::vector<io::FileInfo> tablet_ids;
916
12.2k
        st = io::global_local_filesystem()->list(shard_path, false, &tablet_ids, &exists);
917
12.2k
        if (!st.ok()) [[unlikely]] {
918
0
            LOG(WARNING) << "fail to walk dir, shard_path=" << shard_path << " : " << st;
919
0
            continue;
920
0
        }
921
922
283k
        for (const auto& tablet_id : tablet_ids) {
923
283k
            if (_stop_bg_worker) {
924
0
                break;
925
0
            }
926
927
283k
            if (tablet_id.is_file) {
928
0
                continue;
929
0
            }
930
931
283k
            auto tablet_id_path = fmt::format("{}/{}", shard_path, tablet_id.file_name);
932
283k
            std::vector<io::FileInfo> schema_hashes;
933
283k
            st = fs->list(tablet_id_path, false, &schema_hashes, &exists);
934
283k
            if (!st.ok()) [[unlikely]] {
935
0
                LOG(WARNING) << "fail to walk dir, tablet_id_path=" << tablet_id_path << " : "
936
0
                             << st;
937
0
                continue;
938
0
            }
939
940
283k
            for (auto&& schema_hash : schema_hashes) {
941
283k
                if (schema_hash.is_file) {
942
0
                    continue;
943
0
                }
944
945
283k
                if (config::path_gc_check_step > 0 &&
946
283k
                    ++_path_gc_step % config::path_gc_check_step == 0) {
947
281
                    std::this_thread::sleep_for(
948
281
                            std::chrono::milliseconds(config::path_gc_check_step_interval_ms));
949
281
                }
950
283k
                int16_t shard_id = -1;
951
283k
                try {
952
283k
                    shard_id = cast_set<int16_t>(std::stoi(shard.file_name));
953
283k
                } catch (const std::exception&) {
954
0
                    LOG(WARNING) << "failed to stoi shard_id, shard name=" << shard.file_name;
955
0
                    continue;
956
0
                }
957
283k
                _perform_tablet_gc(tablet_id_path + '/' + schema_hash.file_name, shard_id);
958
283k
            }
959
283k
        }
960
12.2k
    }
961
962
13
    LOG(INFO) << "gc data dir path: " << _path << " finished";
963
13
}
964
965
791
Status DataDir::update_capacity() {
966
791
    RETURN_IF_ERROR(io::global_local_filesystem()->get_space_info(_path, &_disk_capacity_bytes,
967
791
                                                                  &_available_bytes));
968
780
    disks_total_capacity->set_value(_disk_capacity_bytes);
969
780
    disks_avail_capacity->set_value(_available_bytes);
970
780
    LOG(INFO) << "path: " << _path << " total capacity: " << _disk_capacity_bytes
971
780
              << ", available capacity: " << _available_bytes << ", usage: " << get_usage(0)
972
780
              << ", in_use: " << is_used();
973
974
780
    return Status::OK();
975
791
}
976
977
64
void DataDir::update_trash_capacity() {
978
64
    auto trash_path = fmt::format("{}/{}", _path, TRASH_PREFIX);
979
64
    try {
980
64
        _trash_used_bytes = _engine.get_file_or_directory_size(trash_path);
981
64
    } catch (const std::filesystem::filesystem_error& e) {
982
0
        LOG(WARNING) << "update trash capacity failed, path: " << _path << ", err: " << e.what();
983
0
        return;
984
0
    }
985
64
    disks_trash_used_capacity->set_value(_trash_used_bytes);
986
64
    LOG(INFO) << "path: " << _path << " trash capacity: " << _trash_used_bytes;
987
64
}
988
989
430
void DataDir::update_local_data_size(int64_t size) {
990
430
    disks_local_used_capacity->set_value(size);
991
430
}
992
993
430
void DataDir::update_remote_data_size(int64_t size) {
994
430
    disks_remote_used_capacity->set_value(size);
995
430
}
996
997
0
size_t DataDir::tablet_size() const {
998
0
    std::lock_guard<std::mutex> l(_mutex);
999
0
    return _tablet_set.size();
1000
0
}
1001
1002
223k
bool DataDir::reach_capacity_limit(int64_t incoming_data_size) {
1003
223k
    double used_pct = get_usage(incoming_data_size);
1004
223k
    int64_t left_bytes = _available_bytes - incoming_data_size;
1005
223k
    if (used_pct >= config::storage_flood_stage_usage_percent / 100.0 &&
1006
223k
        left_bytes <= config::storage_flood_stage_left_capacity_bytes) {
1007
0
        LOG(WARNING) << "reach capacity limit. used pct: " << used_pct
1008
0
                     << ", left bytes: " << left_bytes << ", path: " << _path;
1009
0
        return true;
1010
0
    }
1011
223k
    return false;
1012
223k
}
1013
1014
8.75k
void DataDir::disks_compaction_score_increment(int64_t delta) {
1015
8.75k
    disks_compaction_score->increment(delta);
1016
8.75k
}
1017
1018
8.75k
void DataDir::disks_compaction_num_increment(int64_t delta) {
1019
8.75k
    disks_compaction_num->increment(delta);
1020
8.75k
}
1021
1022
5.73k
Status DataDir::move_to_trash(const std::string& tablet_path) {
1023
5.73k
    if (config::trash_file_expire_time_sec <= 0) {
1024
5.73k
        LOG(INFO) << "delete tablet dir " << tablet_path
1025
5.73k
                  << " directly due to trash_file_expire_time_sec is 0";
1026
5.73k
        RETURN_IF_ERROR(io::global_local_filesystem()->delete_directory(tablet_path));
1027
5.73k
        return delete_tablet_parent_path_if_empty(tablet_path);
1028
5.73k
    }
1029
1030
0
    Status res = Status::OK();
1031
    // 1. get timestamp string
1032
0
    std::string time_str;
1033
0
    if ((res = gen_timestamp_string(&time_str)) != Status::OK()) {
1034
0
        LOG(WARNING) << "failed to generate time_string when move file to trash.err code=" << res;
1035
0
        return res;
1036
0
    }
1037
1038
    // 2. generate new file path
1039
    // a global counter to avoid file name duplication.
1040
0
    static std::atomic<uint64_t> delete_counter(0);
1041
0
    auto trash_root_path =
1042
0
            fmt::format("{}/{}/{}.{}", _path, TRASH_PREFIX, time_str, delete_counter++);
1043
0
    auto fs_tablet_path = io::Path(tablet_path);
1044
0
    auto trash_tablet_path = trash_root_path /
1045
0
                             fs_tablet_path.parent_path().filename() /* tablet_id */ /
1046
0
                             fs_tablet_path.filename() /* schema_hash */;
1047
1048
    // 3. create target dir, or the rename() function will fail.
1049
0
    auto trash_tablet_parent = trash_tablet_path.parent_path();
1050
    // create dir if not exists
1051
0
    bool exists = true;
1052
0
    RETURN_IF_ERROR(io::global_local_filesystem()->exists(trash_tablet_parent, &exists));
1053
0
    if (!exists) {
1054
0
        RETURN_IF_ERROR(io::global_local_filesystem()->create_directory(trash_tablet_parent));
1055
0
    }
1056
1057
    // 4. move tablet to trash
1058
0
    VLOG_NOTICE << "move file to trash. " << tablet_path << " -> " << trash_tablet_path;
1059
0
    if (rename(tablet_path.c_str(), trash_tablet_path.c_str()) < 0) {
1060
0
        return Status::Error<OS_ERROR>("move file to trash failed. file={}, target={}, err={}",
1061
0
                                       tablet_path, trash_tablet_path.native(), Errno::str());
1062
0
    }
1063
1064
    // 5. check parent dir of source file, delete it when empty
1065
0
    RETURN_IF_ERROR(delete_tablet_parent_path_if_empty(tablet_path));
1066
1067
0
    return Status::OK();
1068
0
}
1069
1070
5.73k
Status DataDir::delete_tablet_parent_path_if_empty(const std::string& tablet_path) {
1071
5.73k
    auto fs_tablet_path = io::Path(tablet_path);
1072
5.73k
    std::string source_parent_dir = fs_tablet_path.parent_path(); // tablet_id level
1073
5.73k
    std::vector<io::FileInfo> sub_files;
1074
5.73k
    bool exists = true;
1075
5.73k
    RETURN_IF_ERROR(
1076
5.73k
            io::global_local_filesystem()->list(source_parent_dir, false, &sub_files, &exists));
1077
5.73k
    if (sub_files.empty()) {
1078
5.73k
        LOG(INFO) << "remove empty dir " << source_parent_dir;
1079
        // no need to exam return status
1080
5.73k
        RETURN_IF_ERROR(io::global_local_filesystem()->delete_directory(source_parent_dir));
1081
5.73k
    }
1082
5.73k
    return Status::OK();
1083
5.73k
}
1084
1085
64
void DataDir::perform_remote_rowset_gc() {
1086
64
    std::vector<std::pair<std::string, std::string>> gc_kvs;
1087
64
    auto traverse_remote_rowset_func = [&gc_kvs](std::string_view key,
1088
64
                                                 std::string_view value) -> bool {
1089
0
        gc_kvs.emplace_back(key, value);
1090
0
        return true;
1091
0
    };
1092
64
    static_cast<void>(_meta->iterate(META_COLUMN_FAMILY_INDEX, REMOTE_ROWSET_GC_PREFIX,
1093
64
                                     traverse_remote_rowset_func));
1094
64
    std::vector<std::string> deleted_keys;
1095
64
    for (auto& [key, val] : gc_kvs) {
1096
0
        auto rowset_id = key.substr(REMOTE_ROWSET_GC_PREFIX.size());
1097
0
        RemoteRowsetGcPB gc_pb;
1098
0
        if (!gc_pb.ParseFromString(val)) {
1099
0
            LOG(WARNING) << "malformed RemoteRowsetGcPB. rowset_id=" << rowset_id;
1100
0
            deleted_keys.push_back(std::move(key));
1101
0
            continue;
1102
0
        }
1103
1104
0
        auto storage_resource = get_storage_resource(gc_pb.resource_id());
1105
0
        if (!storage_resource) {
1106
0
            LOG(WARNING) << "Cannot get file system: " << gc_pb.resource_id();
1107
0
            continue;
1108
0
        }
1109
1110
0
        std::vector<io::Path> seg_paths;
1111
0
        seg_paths.reserve(gc_pb.num_segments());
1112
0
        for (int i = 0; i < gc_pb.num_segments(); ++i) {
1113
0
            seg_paths.emplace_back(
1114
0
                    storage_resource->first.remote_segment_path(gc_pb.tablet_id(), rowset_id, i));
1115
0
        }
1116
1117
0
        auto& fs = storage_resource->first.fs;
1118
0
        LOG(INFO) << "delete remote rowset. root_path=" << fs->root_path()
1119
0
                  << ", rowset_id=" << rowset_id;
1120
0
        auto st = fs->batch_delete(seg_paths);
1121
0
        if (st.ok()) {
1122
0
            deleted_keys.push_back(std::move(key));
1123
0
            unused_remote_rowset_num << -1;
1124
0
        } else {
1125
0
            LOG(WARNING) << "failed to delete remote rowset. err=" << st;
1126
0
        }
1127
0
    }
1128
64
    for (const auto& key : deleted_keys) {
1129
0
        static_cast<void>(_meta->remove(META_COLUMN_FAMILY_INDEX, key));
1130
0
    }
1131
64
}
1132
1133
64
void DataDir::perform_remote_tablet_gc() {
1134
64
    std::vector<std::pair<std::string, std::string>> tablet_gc_kvs;
1135
64
    auto traverse_remote_tablet_func = [&tablet_gc_kvs](std::string_view key,
1136
64
                                                        std::string_view value) -> bool {
1137
0
        tablet_gc_kvs.emplace_back(key, value);
1138
0
        return true;
1139
0
    };
1140
64
    static_cast<void>(_meta->iterate(META_COLUMN_FAMILY_INDEX, REMOTE_TABLET_GC_PREFIX,
1141
64
                                     traverse_remote_tablet_func));
1142
64
    std::vector<std::string> deleted_keys;
1143
64
    for (auto& [key, val] : tablet_gc_kvs) {
1144
0
        auto tablet_id = key.substr(REMOTE_TABLET_GC_PREFIX.size());
1145
0
        RemoteTabletGcPB gc_pb;
1146
0
        if (!gc_pb.ParseFromString(val)) {
1147
0
            LOG(WARNING) << "malformed RemoteTabletGcPB. tablet_id=" << tablet_id;
1148
0
            deleted_keys.push_back(std::move(key));
1149
0
            continue;
1150
0
        }
1151
0
        bool success = true;
1152
0
        for (auto& resource_id : gc_pb.resource_ids()) {
1153
0
            auto fs = get_filesystem(resource_id);
1154
0
            if (!fs) {
1155
0
                LOG(WARNING) << "could not get file system. resource_id=" << resource_id;
1156
0
                success = false;
1157
0
                continue;
1158
0
            }
1159
0
            LOG(INFO) << "delete remote rowsets of tablet. root_path=" << fs->root_path()
1160
0
                      << ", tablet_id=" << tablet_id;
1161
0
            auto st = fs->delete_directory(DATA_PREFIX + '/' + tablet_id);
1162
0
            if (!st.ok()) {
1163
0
                LOG(WARNING) << "failed to delete all remote rowset in tablet. err=" << st;
1164
0
                success = false;
1165
0
            }
1166
0
        }
1167
0
        if (success) {
1168
0
            deleted_keys.push_back(std::move(key));
1169
0
        }
1170
0
    }
1171
64
    for (const auto& key : deleted_keys) {
1172
0
        static_cast<void>(_meta->remove(META_COLUMN_FAMILY_INDEX, key));
1173
0
    }
1174
64
}
1175
} // namespace doris