Coverage Report

Created: 2026-08-07 19:43

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
211
Status read_cluster_id(const std::string& cluster_id_path, int32_t* cluster_id) {
78
211
    bool exists = false;
79
211
    RETURN_IF_ERROR(io::global_local_filesystem()->exists(cluster_id_path, &exists));
80
211
    *cluster_id = -1;
81
211
    if (exists) {
82
0
        io::FileReaderSPtr reader;
83
0
        RETURN_IF_ERROR(io::global_local_filesystem()->open_file(cluster_id_path, &reader));
84
0
        size_t fsize = reader->size();
85
0
        if (fsize > 0) {
86
0
            std::string content;
87
0
            content.resize(fsize, '\0');
88
0
            size_t bytes_read = 0;
89
0
            RETURN_IF_ERROR(reader->read_at(0, {content.data(), fsize}, &bytes_read));
90
0
            DCHECK_EQ(fsize, bytes_read);
91
0
            *cluster_id = std::stoi(content);
92
0
        }
93
0
    }
94
211
    return Status::OK();
95
211
}
96
97
0
Status _write_cluster_id_to_path(const std::string& path, int32_t cluster_id) {
98
0
    bool exists = false;
99
0
    RETURN_IF_ERROR(io::global_local_filesystem()->exists(path, &exists));
100
0
    if (!exists) {
101
0
        io::FileWriterPtr file_writer;
102
0
        RETURN_IF_ERROR(io::global_local_filesystem()->create_file(path, &file_writer));
103
0
        RETURN_IF_ERROR(file_writer->append(std::to_string(cluster_id)));
104
0
        RETURN_IF_ERROR(file_writer->close());
105
0
    }
106
0
    return Status::OK();
107
0
}
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
400
        : _engine(engine),
123
400
          _path(path),
124
400
          _available_bytes(0),
125
400
          _disk_capacity_bytes(0),
126
400
          _trash_used_bytes(0),
127
400
          _storage_medium(storage_medium),
128
400
          _is_used(false),
129
400
          _cluster_id(-1),
130
400
          _to_be_deleted(false) {
131
400
    _data_dir_metric_entity = DorisMetrics::instance()->metric_registry()->register_entity(
132
400
            std::string("data_dir.") + path, {{"path", path}});
133
400
    INT_GAUGE_METRIC_REGISTER(_data_dir_metric_entity, disks_total_capacity);
134
400
    INT_GAUGE_METRIC_REGISTER(_data_dir_metric_entity, disks_avail_capacity);
135
400
    INT_GAUGE_METRIC_REGISTER(_data_dir_metric_entity, disks_local_used_capacity);
136
400
    INT_GAUGE_METRIC_REGISTER(_data_dir_metric_entity, disks_remote_used_capacity);
137
400
    INT_GAUGE_METRIC_REGISTER(_data_dir_metric_entity, disks_trash_used_capacity);
138
400
    INT_GAUGE_METRIC_REGISTER(_data_dir_metric_entity, disks_state);
139
400
    INT_GAUGE_METRIC_REGISTER(_data_dir_metric_entity, disks_compaction_score);
140
400
    INT_GAUGE_METRIC_REGISTER(_data_dir_metric_entity, disks_compaction_num);
141
400
}
142
143
400
DataDir::~DataDir() {
144
400
    DorisMetrics::instance()->metric_registry()->deregister_entity(_data_dir_metric_entity);
145
400
    delete _meta;
146
400
}
147
148
211
Status DataDir::init(bool init_meta) {
149
211
    bool exists = false;
150
211
    RETURN_IF_ERROR(io::global_local_filesystem()->exists(_path, &exists));
151
211
    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
211
    RETURN_NOT_OK_STATUS_WITH_WARN(update_capacity(), "update_capacity failed");
157
211
    RETURN_NOT_OK_STATUS_WITH_WARN(_init_cluster_id(), "_init_cluster_id failed");
158
211
    RETURN_NOT_OK_STATUS_WITH_WARN(_init_capacity_and_create_shards(),
159
211
                                   "_init_capacity_and_create_shards failed");
160
211
    if (init_meta) {
161
211
        RETURN_NOT_OK_STATUS_WITH_WARN(_init_meta(), "_init_meta failed");
162
211
    }
163
164
211
    _is_used = true;
165
211
    return Status::OK();
166
211
}
167
168
76
void DataDir::stop_bg_worker() {
169
76
    _stop_bg_worker = true;
170
76
}
171
172
211
Status DataDir::_init_cluster_id() {
173
211
    auto cluster_id_path = fmt::format("{}/{}", _path, CLUSTER_ID_PREFIX);
174
211
    RETURN_IF_ERROR(read_cluster_id(cluster_id_path, &_cluster_id));
175
211
    if (_cluster_id == -1) {
176
211
        _cluster_id_incomplete = true;
177
211
    }
178
211
    return Status::OK();
179
211
}
180
181
211
Status DataDir::_init_capacity_and_create_shards() {
182
211
    RETURN_IF_ERROR(io::global_local_filesystem()->get_space_info(_path, &_disk_capacity_bytes,
183
211
                                                                  &_available_bytes));
184
211
    auto data_path = fmt::format("{}/{}", _path, DATA_PREFIX);
185
211
    bool exists = false;
186
211
    RETURN_IF_ERROR(io::global_local_filesystem()->exists(data_path, &exists));
187
211
    if (!exists) {
188
211
        RETURN_IF_ERROR(io::global_local_filesystem()->create_directory(data_path));
189
211
    }
190
216k
    for (int i = 0; i < MAX_SHARD_NUM; ++i) {
191
216k
        auto shard_path = fmt::format("{}/{}", data_path, i);
192
216k
        RETURN_IF_ERROR(io::global_local_filesystem()->exists(shard_path, &exists));
193
216k
        if (!exists) {
194
216k
            RETURN_IF_ERROR(io::global_local_filesystem()->create_directory(shard_path));
195
216k
        }
196
216k
    }
197
198
211
    return Status::OK();
199
211
}
200
201
212
Status DataDir::_init_meta() {
202
    // init path hash
203
212
    _path_hash = hash_of_path(BackendOptions::get_localhost(), _path);
204
212
    LOG(INFO) << "path: " << _path << ", hash: " << _path_hash;
205
206
    // init meta
207
212
    _meta = new (std::nothrow) OlapMeta(_path);
208
212
    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
212
    Status res = _meta->init();
214
212
    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
212
    return Status::OK();
219
212
}
220
221
0
Status DataDir::set_cluster_id(int32_t cluster_id) {
222
0
    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
0
    if (!_cluster_id_incomplete) {
228
0
        return Status::OK();
229
0
    }
230
0
    auto cluster_id_path = fmt::format("{}/{}", _path, CLUSTER_ID_PREFIX);
231
0
    return _write_cluster_id_to_path(cluster_id_path, cluster_id);
232
0
}
233
234
0
void DataDir::health_check() {
235
    // check disk
236
0
    if (_is_used) {
237
0
        Status res = _read_and_write_test_file();
238
0
        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
0
    }
245
0
    disks_state->set_value(_is_used ? 1 : 0);
246
0
}
247
248
0
Status DataDir::_read_and_write_test_file() {
249
0
    auto test_file = fmt::format("{}/{}", _path, kTestFilePath);
250
0
    return read_write_test_file(test_file);
251
0
}
252
253
215
void DataDir::register_tablet(Tablet* tablet) {
254
215
    TabletInfo tablet_info(tablet->tablet_id(), tablet->tablet_uid());
255
256
215
    std::lock_guard<std::mutex> l(_mutex);
257
215
    _tablet_set.emplace(std::move(tablet_info));
258
215
}
259
260
151
void DataDir::deregister_tablet(Tablet* tablet) {
261
151
    TabletInfo tablet_info(tablet->tablet_id(), tablet->tablet_uid());
262
263
151
    std::lock_guard<std::mutex> l(_mutex);
264
151
    _tablet_set.erase(tablet_info);
265
151
}
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
76
Status DataDir::_check_incompatible_old_format_tablet() {
318
76
    auto check_incompatible_old_func = [](int64_t tablet_id, int32_t schema_hash,
319
76
                                          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
76
    Status check_incompatible_old_status = TabletMetaManager::traverse_headers(
337
76
            _meta, check_incompatible_old_func, OLD_HEADER_PREFIX);
338
76
    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
76
    } else {
342
76
        LOG(INFO) << "successfully check incompatible old format meta " << _path;
343
76
    }
344
76
    return check_incompatible_old_status;
345
76
}
346
347
// TODO(ygl): deal with rowsets and tablets when load failed
348
76
Status DataDir::load() {
349
76
    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
76
    RETURN_IF_ERROR(_check_incompatible_old_format_tablet());
358
359
76
    std::vector<RowsetMetaSharedPtr> dir_rowset_metas;
360
76
    LOG(INFO) << "begin loading rowset from meta";
361
76
    auto load_rowset_func = [&dir_rowset_metas, this](TabletUid tablet_uid, RowsetId rowset_id,
362
76
                                                      std::string_view meta_str) -> bool {
363
0
        RowsetMetaSharedPtr rowset_meta(new RowsetMeta());
364
0
        bool parsed = rowset_meta->init(meta_str);
365
0
        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
0
        if (rowset_meta->has_delete_predicate()) {
372
            // copy the delete sub pred v1 to check then
373
0
            auto orig_delete_sub_pred = rowset_meta->delete_predicate().sub_predicates();
374
0
            auto* delete_pred = rowset_meta->mutable_delete_pred_pb();
375
376
0
            if ((!delete_pred->sub_predicates().empty() &&
377
0
                 delete_pred->sub_predicates_v2().empty()) ||
378
0
                (!delete_pred->in_predicates().empty() &&
379
0
                 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
0
        }
400
401
0
        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
0
        dir_rowset_metas.push_back(rowset_meta);
407
0
        return true;
408
0
    };
409
76
    MonotonicStopWatch rs_timer;
410
76
    rs_timer.start();
411
76
    Status load_rowset_status = RowsetMetaManager::traverse_rowset_metas(_meta, load_rowset_func);
412
76
    rs_timer.stop();
413
76
    if (!load_rowset_status) {
414
0
        LOG(WARNING) << "errors when load rowset meta from meta env, skip this data dir:" << _path;
415
76
    } else {
416
76
        LOG(INFO) << "load rowset from meta finished, cost: "
417
76
                  << rs_timer.elapsed_time_milliseconds() << " ms, data dir: " << _path;
418
76
    }
419
420
    // load tablet
421
    // create tablet from tablet meta and add it to tablet mgr
422
76
    LOG(INFO) << "begin loading tablet from meta";
423
76
    std::set<int64_t> tablet_ids;
424
76
    std::set<int64_t> failed_tablet_ids;
425
76
    auto load_tablet_func = [this, &tablet_ids, &failed_tablet_ids](
426
76
                                    int64_t tablet_id, int32_t schema_hash,
427
76
                                    std::string_view value) -> bool {
428
0
        Status status = _engine.tablet_manager()->load_tablet_from_meta(
429
0
                this, tablet_id, schema_hash, value, false, false, false, false);
430
0
        if (!status.ok() && !status.is<TABLE_ALREADY_DELETED_ERROR>() &&
431
0
            !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
0
        } else {
450
0
            tablet_ids.insert(tablet_id);
451
0
        }
452
0
        return true;
453
0
    };
454
76
    MonotonicStopWatch tablet_timer;
455
76
    tablet_timer.start();
456
76
    Status load_tablet_status = TabletMetaManager::traverse_headers(_meta, load_tablet_func);
457
76
    tablet_timer.stop();
458
76
    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
76
    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
76
    } else {
472
76
        LOG(INFO) << "load tablet from meta finished"
473
76
                  << ", loaded tablet: " << tablet_ids.size()
474
76
                  << ", error tablet: " << failed_tablet_ids.size()
475
76
                  << ", cost: " << tablet_timer.elapsed_time_milliseconds()
476
76
                  << " ms, path: " << _path;
477
76
    }
478
479
76
    for (int64_t tablet_id : tablet_ids) {
480
0
        TabletSharedPtr tablet = _engine.tablet_manager()->get_tablet(tablet_id);
481
0
        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
0
    }
486
487
76
    auto load_pending_publish_info_func = [&engine = _engine](int64_t tablet_id,
488
76
                                                              int64_t publish_version,
489
76
                                                              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
76
    MonotonicStopWatch pending_publish_timer;
503
76
    pending_publish_timer.start();
504
76
    RETURN_IF_ERROR(
505
76
            TabletMetaManager::traverse_pending_publish(_meta, load_pending_publish_info_func));
506
76
    pending_publish_timer.stop();
507
76
    LOG(INFO) << "load pending publish task from meta finished, cost: "
508
76
              << pending_publish_timer.elapsed_time_milliseconds() << " ms, data dir: " << _path;
509
510
76
    int64_t rowset_partition_id_eq_0_num = 0;
511
76
    for (auto rowset_meta : dir_rowset_metas) {
512
0
        if (rowset_meta->partition_id() == 0) {
513
0
            ++rowset_partition_id_eq_0_num;
514
0
        }
515
0
    }
516
76
    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
76
    std::map<int64_t, RowsetMetaSharedPtr> txn_id_to_row_binlog_meta;
525
76
    for (auto&& rowset_meta : dir_rowset_metas) {
526
0
        if (rowset_meta->is_row_binlog()) {
527
0
            txn_id_to_row_binlog_meta[rowset_meta->txn_id()] = rowset_meta;
528
0
        }
529
0
    }
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
76
    int64_t invalid_rowset_counter = 0;
536
76
    for (auto&& rowset_meta : dir_rowset_metas) {
537
0
        TabletSharedPtr tablet = _engine.tablet_manager()->get_tablet(rowset_meta->tablet_id());
538
        // tablet maybe dropped, but not drop related rowset meta
539
0
        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
0
        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
0
        if (rowset_meta->is_row_binlog() &&
556
0
            rowset_meta->rowset_state() == RowsetStatePB::COMMITTED) {
557
0
            continue;
558
0
        }
559
560
0
        RowBinlogTxnInfo attach_row_binlog;
561
0
        if (auto it = txn_id_to_row_binlog_meta.find(rowset_meta->txn_id());
562
0
            it != txn_id_to_row_binlog_meta.end()) {
563
0
            const RowsetMetaSharedPtr& attach_row_binlog_rowset_meta = it->second;
564
0
            DCHECK_EQ(attach_row_binlog_rowset_meta->rowset_state(), rowset_meta->rowset_state());
565
0
            TabletSharedPtr binlog_tablet = _engine.tablet_manager()->get_tablet(
566
0
                    attach_row_binlog_rowset_meta->tablet_id());
567
0
            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
0
            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
0
            Status attach_create_status = binlog_tablet->create_rowset(
579
0
                    attach_row_binlog_rowset_meta, &attach_row_binlog.rowset);
580
0
            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
0
            attach_row_binlog.tablet = std::move(binlog_tablet);
589
0
        }
590
591
0
        RowsetSharedPtr rowset;
592
0
        Status create_status = tablet->create_rowset(rowset_meta, &rowset);
593
0
        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
0
        std::optional<BinlogFormatPB> binlog_format = std::nullopt;
602
0
        std::optional<RowsetMetaPB> attach_row_binlog_rowset_meta;
603
0
        if (attach_row_binlog.rowset != nullptr) {
604
0
            binlog_format = BinlogFormatPB::ROW;
605
0
            attach_row_binlog_rowset_meta =
606
0
                    attach_row_binlog.rowset->rowset_meta()->get_rowset_pb();
607
0
        }
608
609
0
        std::string attach_binlog_rowset_id =
610
0
                attach_row_binlog.rowset != nullptr
611
0
                        ? attach_row_binlog.rowset->rowset_id().to_string()
612
0
                        : "0";
613
614
0
        if (rowset_meta->rowset_state() == RowsetStatePB::COMMITTED &&
615
0
            rowset_meta->tablet_uid() == tablet->tablet_uid()) {
616
0
            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
0
            std::vector<RowsetId> rowset_ids {rowset_meta->rowset_id()};
624
0
            if (attach_row_binlog.rowset != nullptr) {
625
0
                rowset_ids.emplace_back(attach_row_binlog.rowset->rowset_id());
626
0
            }
627
0
            Status commit_txn_status = _engine.txn_manager()->commit_txn(
628
0
                    _meta, rowset_meta->partition_id(), rowset_meta->txn_id(),
629
0
                    rowset_meta->tablet_id(), rowset_meta->tablet_uid(), rowset_meta->load_id(),
630
0
                    rowset, _engine.pending_local_rowsets().add(rowset_ids), true, nullptr,
631
0
                    attach_row_binlog);
632
0
            if (commit_txn_status || commit_txn_status.is<PUSH_TRANSACTION_ALREADY_EXIST>()) {
633
0
                LOG(INFO) << "successfully to add committed rowset: " << rowset_meta->rowset_id()
634
0
                          << " to tablet: " << rowset_meta->tablet_id()
635
0
                          << " schema hash: " << rowset_meta->tablet_schema_hash()
636
0
                          << " for txn: " << rowset_meta->txn_id()
637
0
                          << ", binlog<row> rowset: " << attach_binlog_rowset_id;
638
639
0
            } 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
0
        } else if (rowset_meta->rowset_state() == RowsetStatePB::VISIBLE &&
654
0
                   rowset_meta->tablet_uid() == tablet->tablet_uid()) {
655
0
            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
0
            Status publish_status = tablet->add_rowset(rowset);
663
0
            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
0
        } 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
0
    }
682
683
76
    int64_t dbm_cnt {0};
684
76
    int64_t unknown_dbm_cnt {0};
685
76
    auto load_delete_bitmap_func = [this, &dbm_cnt, &unknown_dbm_cnt](int64_t tablet_id,
686
76
                                                                      int64_t version,
687
76
                                                                      std::string_view val) {
688
0
        TabletSharedPtr tablet = _engine.tablet_manager()->get_tablet(tablet_id);
689
0
        if (!tablet) {
690
0
            return true;
691
0
        }
692
0
        RowsetIdUnorderedSet rowset_ids;
693
0
        for (const auto& [_, rowset_meta] : tablet->tablet_meta()->all_rs_metas()) {
694
0
            rowset_ids.insert(rowset_meta->rowset_id());
695
0
        }
696
697
0
        DeleteBitmapPB delete_bitmap_pb;
698
0
        delete_bitmap_pb.ParseFromArray(val.data(), cast_set<int>(val.size()));
699
0
        int rst_ids_size = delete_bitmap_pb.rowset_ids_size();
700
0
        int seg_ids_size = delete_bitmap_pb.segment_ids_size();
701
0
        int seg_maps_size = delete_bitmap_pb.segment_delete_bitmaps_size();
702
0
        CHECK(rst_ids_size == seg_ids_size && seg_ids_size == seg_maps_size);
703
704
0
        for (int i = 0; i < rst_ids_size; ++i) {
705
0
            RowsetId rst_id;
706
0
            rst_id.init(delete_bitmap_pb.rowset_ids(i));
707
            // only process rowsets in current tablet meta.
708
0
            if (rowset_ids.find(rst_id) == rowset_ids.end()) {
709
0
                ++unknown_dbm_cnt;
710
0
                continue;
711
0
            }
712
0
            ++dbm_cnt;
713
0
            auto seg_id = delete_bitmap_pb.segment_ids(i);
714
0
            auto iter = tablet->tablet_meta()->delete_bitmap().delete_bitmap.find(
715
0
                    {rst_id, seg_id, version});
716
            // This version of delete bitmap already exists
717
0
            if (iter != tablet->tablet_meta()->delete_bitmap().delete_bitmap.end()) {
718
0
                continue;
719
0
            }
720
0
            auto bitmap = delete_bitmap_pb.segment_delete_bitmaps(i).data();
721
722
0
            tablet->tablet_meta()->delete_bitmap().delete_bitmap[{rst_id, seg_id, version}] =
723
0
                    roaring::Roaring::read(bitmap);
724
0
            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
0
        }
728
0
        return true;
729
0
    };
730
76
    MonotonicStopWatch dbm_timer;
731
76
    dbm_timer.start();
732
76
    RETURN_IF_ERROR(TabletMetaManager::traverse_delete_bitmap(_meta, load_delete_bitmap_func));
733
76
    dbm_timer.stop();
734
735
76
    LOG(INFO) << "load delete bitmap from meta finished, cost: "
736
76
              << 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
76
    LOG(INFO) << "finish to load tablets from " << _path
742
76
              << ", total rowset meta: " << dir_rowset_metas.size()
743
76
              << ", invalid rowset num: " << invalid_rowset_counter
744
76
              << ", visible/stale rowsets' delete bitmap count: " << dbm_cnt
745
76
              << ", invalid rowsets' delete bitmap count: " << unknown_dbm_cnt;
746
747
76
    return Status::OK();
748
76
}
749
750
// gc unused local tablet dir
751
20
void DataDir::_perform_tablet_gc(const std::string& tablet_schema_hash_path, int16_t shard_id) {
752
20
    if (_stop_bg_worker) {
753
0
        return;
754
0
    }
755
756
20
    TTabletId tablet_id = -1;
757
20
    TSchemaHash schema_hash = -1;
758
20
    bool is_valid = TabletManager::get_tablet_id_and_schema_hash_from_path(
759
20
            tablet_schema_hash_path, &tablet_id, &schema_hash);
760
20
    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
20
    auto tablet = _engine.tablet_manager()->get_tablet(tablet_id);
766
20
    if (!tablet || tablet->data_dir() != this) {
767
10
        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
10
        _engine.tablet_manager()->try_delete_unused_tablet_path(this, tablet_id, schema_hash,
773
10
                                                                tablet_schema_hash_path, shard_id);
774
10
        return;
775
10
    }
776
777
10
    _perform_rowset_gc(tablet_schema_hash_path);
778
10
}
779
780
// gc unused local rowsets under tablet dir
781
10
void DataDir::_perform_rowset_gc(const std::string& tablet_schema_hash_path) {
782
10
    if (_stop_bg_worker) {
783
0
        return;
784
0
    }
785
786
10
    TTabletId tablet_id = -1;
787
10
    TSchemaHash schema_hash = -1;
788
10
    bool is_valid = doris::TabletManager::get_tablet_id_and_schema_hash_from_path(
789
10
            tablet_schema_hash_path, &tablet_id, &schema_hash);
790
10
    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
10
    auto tablet = _engine.tablet_manager()->get_tablet(tablet_id);
796
10
    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
10
    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
10
    bool exists;
809
10
    std::vector<io::FileInfo> files;
810
10
    auto st = io::global_local_filesystem()->list(tablet_schema_hash_path, true, &files, &exists);
811
10
    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
10
    std::vector<std::pair<RowsetId, std::string /* filename */>> rowsets_not_pending;
819
480
    for (auto&& file : files) {
820
480
        auto rowset_id = extract_rowset_id(file.file_name);
821
480
        if (rowset_id.hi == 0) {
822
0
            continue; // Not a rowset
823
0
        }
824
825
480
        if (_engine.pending_local_rowsets().contains(rowset_id)) {
826
80
            continue; // Pending rowset file
827
80
        }
828
829
400
        rowsets_not_pending.emplace_back(rowset_id, std::move(file.file_name));
830
400
    }
831
832
10
    RowsetIdUnorderedSet rowsets_in_version_map;
833
10
    tablet->traverse_rowsets(
834
30
            [&rowsets_in_version_map](auto& rs) { rowsets_in_version_map.insert(rs->rowset_id()); },
835
10
            true);
836
837
10
    DBUG_EXECUTE_IF("DataDir::_perform_rowset_gc.simulation.slow", {
838
10
        auto target_tablet_id = dp->param<int64_t>("tablet_id", -1);
839
10
        if (target_tablet_id == tablet_id) {
840
10
            LOG(INFO) << "debug point wait tablet to remove rsmgr tabletId=" << tablet_id;
841
10
            DBUG_BLOCK;
842
10
        }
843
10
    });
844
845
80
    auto reclaim_rowset_file = [](const std::string& path) {
846
80
        auto st = io::global_local_filesystem()->delete_file(path);
847
80
        if (!st.ok()) [[unlikely]] {
848
0
            LOG(WARNING) << "[path gc] failed to delete garbage rowset file: " << st;
849
0
            return;
850
0
        }
851
80
        LOG(INFO) << "[path gc] delete garbage path: " << path; // Audit log
852
80
    };
853
854
100
    auto should_reclaim = [&, this](const RowsetId& rowset_id) {
855
100
        return !rowsets_in_version_map.contains(rowset_id) &&
856
100
               !_engine.check_rowset_id_in_unused_rowsets(rowset_id) &&
857
100
               RowsetMetaManager::exists(get_meta(), tablet->tablet_uid(), rowset_id)
858
40
                       .is<META_KEY_NOT_FOUND>();
859
100
    };
860
861
    // rowset_id -> is_garbage
862
10
    std::unordered_map<RowsetId, bool> checked_rowsets;
863
400
    for (auto&& [rowset_id, filename] : rowsets_not_pending) {
864
400
        if (_stop_bg_worker) {
865
0
            return;
866
0
        }
867
868
400
        if (auto it = checked_rowsets.find(rowset_id); it != checked_rowsets.end()) {
869
300
            if (it->second) { // Is checked garbage rowset
870
60
                reclaim_rowset_file(tablet_schema_hash_path + '/' + filename);
871
60
            }
872
300
            continue;
873
300
        }
874
875
100
        if (should_reclaim(rowset_id)) {
876
20
            if (config::path_gc_check_step > 0 &&
877
20
                ++_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
20
            reclaim_rowset_file(tablet_schema_hash_path + '/' + filename);
882
20
            checked_rowsets.emplace(rowset_id, true);
883
80
        } else {
884
80
            checked_rowsets.emplace(rowset_id, false);
885
80
        }
886
100
    }
887
10
}
888
889
1
void DataDir::perform_path_gc() {
890
1
    if (_stop_bg_worker) {
891
0
        return;
892
0
    }
893
894
1
    LOG(INFO) << "start to gc data dir " << _path;
895
1
    auto data_path = fmt::format("{}/{}", _path, DATA_PREFIX);
896
1
    std::vector<io::FileInfo> shards;
897
1
    bool exists = true;
898
1
    const auto& fs = io::global_local_filesystem();
899
1
    auto st = fs->list(data_path, false, &shards, &exists);
900
1
    if (!st.ok()) [[unlikely]] {
901
0
        LOG(WARNING) << "failed to scan data dir: " << st;
902
0
        return;
903
0
    }
904
905
4
    for (const auto& shard : shards) {
906
4
        if (_stop_bg_worker) {
907
0
            break;
908
0
        }
909
910
4
        if (shard.is_file) {
911
0
            continue;
912
0
        }
913
914
4
        auto shard_path = fmt::format("{}/{}", data_path, shard.file_name);
915
4
        std::vector<io::FileInfo> tablet_ids;
916
4
        st = io::global_local_filesystem()->list(shard_path, false, &tablet_ids, &exists);
917
4
        if (!st.ok()) [[unlikely]] {
918
0
            LOG(WARNING) << "fail to walk dir, shard_path=" << shard_path << " : " << st;
919
0
            continue;
920
0
        }
921
922
20
        for (const auto& tablet_id : tablet_ids) {
923
20
            if (_stop_bg_worker) {
924
0
                break;
925
0
            }
926
927
20
            if (tablet_id.is_file) {
928
0
                continue;
929
0
            }
930
931
20
            auto tablet_id_path = fmt::format("{}/{}", shard_path, tablet_id.file_name);
932
20
            std::vector<io::FileInfo> schema_hashes;
933
20
            st = fs->list(tablet_id_path, false, &schema_hashes, &exists);
934
20
            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
20
            for (auto&& schema_hash : schema_hashes) {
941
20
                if (schema_hash.is_file) {
942
0
                    continue;
943
0
                }
944
945
20
                if (config::path_gc_check_step > 0 &&
946
20
                    ++_path_gc_step % config::path_gc_check_step == 0) {
947
0
                    std::this_thread::sleep_for(
948
0
                            std::chrono::milliseconds(config::path_gc_check_step_interval_ms));
949
0
                }
950
20
                int16_t shard_id = -1;
951
20
                try {
952
20
                    shard_id = cast_set<int16_t>(std::stoi(shard.file_name));
953
20
                } catch (const std::exception&) {
954
0
                    LOG(WARNING) << "failed to stoi shard_id, shard name=" << shard.file_name;
955
0
                    continue;
956
0
                }
957
20
                _perform_tablet_gc(tablet_id_path + '/' + schema_hash.file_name, shard_id);
958
20
            }
959
20
        }
960
4
    }
961
962
1
    LOG(INFO) << "gc data dir path: " << _path << " finished";
963
1
}
964
965
417
Status DataDir::update_capacity() {
966
417
    RETURN_IF_ERROR(io::global_local_filesystem()->get_space_info(_path, &_disk_capacity_bytes,
967
417
                                                                  &_available_bytes));
968
406
    disks_total_capacity->set_value(_disk_capacity_bytes);
969
406
    disks_avail_capacity->set_value(_available_bytes);
970
406
    LOG(INFO) << "path: " << _path << " total capacity: " << _disk_capacity_bytes
971
406
              << ", available capacity: " << _available_bytes << ", usage: " << get_usage(0)
972
406
              << ", in_use: " << is_used();
973
974
406
    return Status::OK();
975
417
}
976
977
0
void DataDir::update_trash_capacity() {
978
0
    auto trash_path = fmt::format("{}/{}", _path, TRASH_PREFIX);
979
0
    try {
980
0
        _trash_used_bytes = _engine.get_file_or_directory_size(trash_path);
981
0
    } 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
0
    disks_trash_used_capacity->set_value(_trash_used_bytes);
986
0
    LOG(INFO) << "path: " << _path << " trash capacity: " << _trash_used_bytes;
987
0
}
988
989
0
void DataDir::update_local_data_size(int64_t size) {
990
0
    disks_local_used_capacity->set_value(size);
991
0
}
992
993
0
void DataDir::update_remote_data_size(int64_t size) {
994
0
    disks_remote_used_capacity->set_value(size);
995
0
}
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
662
bool DataDir::reach_capacity_limit(int64_t incoming_data_size) {
1003
662
    double used_pct = get_usage(incoming_data_size);
1004
662
    int64_t left_bytes = _available_bytes - incoming_data_size;
1005
662
    if (used_pct >= config::storage_flood_stage_usage_percent / 100.0 &&
1006
662
        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
662
    return false;
1012
662
}
1013
1014
62
void DataDir::disks_compaction_score_increment(int64_t delta) {
1015
62
    disks_compaction_score->increment(delta);
1016
62
}
1017
1018
62
void DataDir::disks_compaction_num_increment(int64_t delta) {
1019
62
    disks_compaction_num->increment(delta);
1020
62
}
1021
1022
123
Status DataDir::move_to_trash(const std::string& tablet_path) {
1023
123
    if (config::trash_file_expire_time_sec <= 0) {
1024
123
        LOG(INFO) << "delete tablet dir " << tablet_path
1025
123
                  << " directly due to trash_file_expire_time_sec is 0";
1026
123
        RETURN_IF_ERROR(io::global_local_filesystem()->delete_directory(tablet_path));
1027
123
        return delete_tablet_parent_path_if_empty(tablet_path);
1028
123
    }
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
123
Status DataDir::delete_tablet_parent_path_if_empty(const std::string& tablet_path) {
1071
123
    auto fs_tablet_path = io::Path(tablet_path);
1072
123
    std::string source_parent_dir = fs_tablet_path.parent_path(); // tablet_id level
1073
123
    std::vector<io::FileInfo> sub_files;
1074
123
    bool exists = true;
1075
123
    RETURN_IF_ERROR(
1076
123
            io::global_local_filesystem()->list(source_parent_dir, false, &sub_files, &exists));
1077
123
    if (sub_files.empty()) {
1078
123
        LOG(INFO) << "remove empty dir " << source_parent_dir;
1079
        // no need to exam return status
1080
123
        RETURN_IF_ERROR(io::global_local_filesystem()->delete_directory(source_parent_dir));
1081
123
    }
1082
123
    return Status::OK();
1083
123
}
1084
1085
0
void DataDir::perform_remote_rowset_gc() {
1086
0
    std::vector<std::pair<std::string, std::string>> gc_kvs;
1087
0
    auto traverse_remote_rowset_func = [&gc_kvs](std::string_view key,
1088
0
                                                 std::string_view value) -> bool {
1089
0
        gc_kvs.emplace_back(key, value);
1090
0
        return true;
1091
0
    };
1092
0
    static_cast<void>(_meta->iterate(META_COLUMN_FAMILY_INDEX, REMOTE_ROWSET_GC_PREFIX,
1093
0
                                     traverse_remote_rowset_func));
1094
0
    std::vector<std::string> deleted_keys;
1095
0
    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
0
    for (const auto& key : deleted_keys) {
1129
0
        static_cast<void>(_meta->remove(META_COLUMN_FAMILY_INDEX, key));
1130
0
    }
1131
0
}
1132
1133
0
void DataDir::perform_remote_tablet_gc() {
1134
0
    std::vector<std::pair<std::string, std::string>> tablet_gc_kvs;
1135
0
    auto traverse_remote_tablet_func = [&tablet_gc_kvs](std::string_view key,
1136
0
                                                        std::string_view value) -> bool {
1137
0
        tablet_gc_kvs.emplace_back(key, value);
1138
0
        return true;
1139
0
    };
1140
0
    static_cast<void>(_meta->iterate(META_COLUMN_FAMILY_INDEX, REMOTE_TABLET_GC_PREFIX,
1141
0
                                     traverse_remote_tablet_func));
1142
0
    std::vector<std::string> deleted_keys;
1143
0
    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
0
    for (const auto& key : deleted_keys) {
1172
0
        static_cast<void>(_meta->remove(META_COLUMN_FAMILY_INDEX, key));
1173
0
    }
1174
0
}
1175
} // namespace doris