Coverage Report

Created: 2026-05-12 13:04

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