Coverage Report

Created: 2025-04-24 12:23

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