Coverage Report

Created: 2026-05-16 12:16

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/storage/tablet/tablet_manager.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/tablet/tablet_manager.h"
19
20
#include <fmt/format.h>
21
#include <gen_cpp/AgentService_types.h>
22
#include <gen_cpp/BackendService_types.h>
23
#include <gen_cpp/Descriptors_types.h>
24
#include <gen_cpp/MasterService_types.h>
25
#include <gen_cpp/Types_types.h>
26
#include <gen_cpp/olap_file.pb.h>
27
#include <re2/re2.h>
28
#include <unistd.h>
29
30
#include <algorithm>
31
#include <list>
32
#include <mutex>
33
#include <ostream>
34
#include <string_view>
35
36
#include "absl/strings/substitute.h"
37
#include "bvar/bvar.h"
38
#include "common/compiler_util.h" // IWYU pragma: keep
39
#include "common/config.h"
40
#include "common/logging.h"
41
#include "common/metrics/doris_metrics.h"
42
#include "common/metrics/metrics.h"
43
#include "io/fs/local_file_system.h"
44
#include "runtime/exec_env.h"
45
#include "service/backend_options.h"
46
#include "storage/compaction/cumulative_compaction_time_series_policy.h"
47
#include "storage/data_dir.h"
48
#include "storage/olap_common.h"
49
#include "storage/olap_define.h"
50
#include "storage/olap_meta.h"
51
#include "storage/pb_helper.h"
52
#include "storage/rowset/beta_rowset.h"
53
#include "storage/rowset/rowset.h"
54
#include "storage/rowset/rowset_meta_manager.h"
55
#include "storage/storage_engine.h"
56
#include "storage/tablet/tablet.h"
57
#include "storage/tablet/tablet_meta.h"
58
#include "storage/tablet/tablet_meta_manager.h"
59
#include "storage/tablet/tablet_schema.h"
60
#include "storage/txn/txn_manager.h"
61
#include "util/defer_op.h"
62
#include "util/histogram.h"
63
#include "util/path_util.h"
64
#include "util/stopwatch.hpp"
65
#include "util/time.h"
66
#include "util/trace.h"
67
#include "util/uid_util.h"
68
69
namespace doris {
70
class CumulativeCompactionPolicy;
71
} // namespace doris
72
73
using std::map;
74
using std::set;
75
using std::string;
76
using std::vector;
77
78
namespace doris {
79
using namespace ErrorCode;
80
81
bvar::Adder<int64_t> g_tablet_meta_schema_columns_count("tablet_meta_schema_columns_count");
82
83
TabletManager::TabletManager(StorageEngine& engine, int32_t tablet_map_lock_shard_size)
84
381
        : _engine(engine),
85
381
          _tablets_shards_size(tablet_map_lock_shard_size),
86
381
          _tablets_shards_mask(tablet_map_lock_shard_size - 1) {
87
381
    CHECK_GT(_tablets_shards_size, 0);
88
381
    CHECK_EQ(_tablets_shards_size & _tablets_shards_mask, 0);
89
381
    _tablets_shards.resize(_tablets_shards_size);
90
381
}
91
92
378
TabletManager::~TabletManager() = default;
93
94
Status TabletManager::_add_tablet_unlocked(TTabletId tablet_id, const TabletSharedPtr& tablet,
95
285k
                                           bool update_meta, bool force, RuntimeProfile* profile) {
96
285k
    if (profile->get_counter("AddTablet") == nullptr) {
97
278k
        ADD_TIMER(profile, "AddTablet");
98
278k
    }
99
285k
    Status res = Status::OK();
100
285k
    VLOG_NOTICE << "begin to add tablet to TabletManager. "
101
93
                << "tablet_id=" << tablet_id << ", force=" << force;
102
103
285k
    TabletSharedPtr existed_tablet = nullptr;
104
285k
    tablet_map_t& tablet_map = _get_tablet_map(tablet_id);
105
285k
    const auto& iter = tablet_map.find(tablet_id);
106
285k
    if (iter != tablet_map.end()) {
107
176
        existed_tablet = iter->second;
108
176
    }
109
110
285k
    if (existed_tablet == nullptr) {
111
285k
        return _add_tablet_to_map_unlocked(tablet_id, tablet, update_meta, false /*keep_files*/,
112
285k
                                           false /*drop_old*/, profile);
113
285k
    }
114
    // During restore process, the tablet is exist and snapshot loader will replace the tablet's rowsets
115
    // and then reload the tablet, the tablet's path will the same
116
18.4E
    if (!force) {
117
2
        if (existed_tablet->tablet_path() == tablet->tablet_path()) {
118
0
            return Status::Error<ENGINE_INSERT_EXISTS_TABLE>(
119
0
                    "add the same tablet twice! tablet_id={}, tablet_path={}", tablet_id,
120
0
                    tablet->tablet_path());
121
0
        }
122
2
        if (existed_tablet->data_dir() == tablet->data_dir()) {
123
0
            return Status::Error<ENGINE_INSERT_EXISTS_TABLE>(
124
0
                    "add tablet with same data dir twice! tablet_id={}", tablet_id);
125
0
        }
126
2
    }
127
128
18.4E
    MonotonicStopWatch watch;
129
18.4E
    watch.start();
130
131
    // During storage migration, the tablet is moved to another disk, have to check
132
    // if the new tablet's rowset version is larger than the old one to prevent losting data during
133
    // migration
134
18.4E
    int64_t old_time, new_time;
135
18.4E
    int64_t old_version, new_version;
136
18.4E
    {
137
18.4E
        std::shared_lock rdlock(existed_tablet->get_header_lock());
138
18.4E
        const RowsetSharedPtr old_rowset = existed_tablet->get_rowset_with_max_version();
139
18.4E
        const RowsetSharedPtr new_rowset = tablet->get_rowset_with_max_version();
140
        // If new tablet is empty, it is a newly created schema change tablet.
141
        // the old tablet is dropped before add tablet. it should not exist old tablet
142
18.4E
        if (new_rowset == nullptr) {
143
            // it seems useless to call unlock and return here.
144
            // it could prevent error when log level is changed in the future.
145
0
            return Status::Error<ENGINE_INSERT_EXISTS_TABLE>(
146
0
                    "new tablet is empty and old tablet exists. it should not happen. tablet_id={}",
147
0
                    tablet_id);
148
0
        }
149
18.4E
        old_time = old_rowset == nullptr ? -1 : old_rowset->creation_time();
150
18.4E
        new_time = new_rowset->creation_time();
151
18.4E
        old_version = old_rowset == nullptr ? -1 : old_rowset->end_version();
152
18.4E
        new_version = new_rowset->end_version();
153
18.4E
    }
154
18.4E
    COUNTER_UPDATE(ADD_CHILD_TIMER(profile, "GetExistTabletVersion", "AddTablet"),
155
18.4E
                   static_cast<int64_t>(watch.reset()));
156
157
    // In restore process, we replace all origin files in tablet dir with
158
    // the downloaded snapshot files. Then we try to reload tablet header.
159
    // force == true means we forcibly replace the Tablet in tablet_map
160
    // with the new one. But if we do so, the files in the tablet dir will be
161
    // dropped when the origin Tablet deconstruct.
162
    // So we set keep_files == true to not delete files when the
163
    // origin Tablet deconstruct.
164
    // During restore process, snapshot loader
165
    // replaced the old tablet's rowset with new rowsets, but the tablet path is reused, if drop files
166
    // here, the new rowset's file will also be dropped, so use keep files here
167
18.4E
    bool keep_files = force;
168
18.4E
    if (force ||
169
18.4E
        (new_version > old_version || (new_version == old_version && new_time >= old_time))) {
170
        // check if new tablet's meta is in store and add new tablet's meta to meta store
171
176
        res = _add_tablet_to_map_unlocked(tablet_id, tablet, update_meta, keep_files,
172
176
                                          true /*drop_old*/, profile);
173
18.4E
    } else {
174
18.4E
        RETURN_IF_ERROR(tablet->set_tablet_state(TABLET_SHUTDOWN));
175
18.4E
        tablet->save_meta();
176
18.4E
        COUNTER_UPDATE(ADD_CHILD_TIMER(profile, "SaveMeta", "AddTablet"),
177
18.4E
                       static_cast<int64_t>(watch.reset()));
178
18.4E
        {
179
18.4E
            std::lock_guard<std::shared_mutex> shutdown_tablets_wrlock(_shutdown_tablets_lock);
180
18.4E
            _shutdown_tablets.push_back(tablet);
181
18.4E
        }
182
183
18.4E
        res = Status::Error<ENGINE_INSERT_OLD_TABLET>(
184
18.4E
                "set tablet to shutdown state. tablet_id={}, tablet_path={}", tablet->tablet_id(),
185
18.4E
                tablet->tablet_path());
186
18.4E
    }
187
18.4E
    LOG(WARNING) << "add duplicated tablet. force=" << force << ", res=" << res
188
18.4E
                 << ", tablet_id=" << tablet_id << ", old_version=" << old_version
189
18.4E
                 << ", new_version=" << new_version << ", old_time=" << old_time
190
18.4E
                 << ", new_time=" << new_time
191
18.4E
                 << ", old_tablet_path=" << existed_tablet->tablet_path()
192
18.4E
                 << ", new_tablet_path=" << tablet->tablet_path();
193
194
18.4E
    return res;
195
18.4E
}
196
197
Status TabletManager::_add_tablet_to_map_unlocked(TTabletId tablet_id,
198
                                                  const TabletSharedPtr& tablet, bool update_meta,
199
                                                  bool keep_files, bool drop_old,
200
285k
                                                  RuntimeProfile* profile) {
201
    // check if new tablet's meta is in store and add new tablet's meta to meta store
202
285k
    Status res = Status::OK();
203
285k
    MonotonicStopWatch watch;
204
285k
    watch.start();
205
285k
    if (update_meta) {
206
        // call tablet save meta in order to valid the meta
207
7.09k
        tablet->save_meta();
208
7.09k
        COUNTER_UPDATE(ADD_CHILD_TIMER(profile, "SaveMeta", "AddTablet"),
209
7.09k
                       static_cast<int64_t>(watch.reset()));
210
7.09k
    }
211
285k
    if (drop_old) {
212
        // If the new tablet is fresher than the existing one, then replace
213
        // the existing tablet with the new one.
214
        // Use default replica_id to ignore whether replica_id is match when drop tablet.
215
176
        Status status = _drop_tablet(tablet_id, /* replica_id */ 0, keep_files, false, true);
216
176
        COUNTER_UPDATE(ADD_CHILD_TIMER(profile, "DropOldTablet", "AddTablet"),
217
176
                       static_cast<int64_t>(watch.reset()));
218
176
        RETURN_NOT_OK_STATUS_WITH_WARN(
219
176
                status, absl::Substitute("failed to drop old tablet when add new tablet. "
220
176
                                         "tablet_id=$0",
221
176
                                         tablet_id));
222
176
    }
223
    // Register tablet into DataDir, so that we can manage tablet from
224
    // the perspective of root path.
225
    // Example: unregister all tables when a bad disk found.
226
285k
    tablet->register_tablet_into_dir();
227
285k
    tablet_map_t& tablet_map = _get_tablet_map(tablet_id);
228
285k
    tablet_map[tablet_id] = tablet;
229
285k
    _add_tablet_to_partition(tablet);
230
285k
    g_tablet_meta_schema_columns_count << tablet->tablet_meta()->tablet_columns_num();
231
285k
    COUNTER_UPDATE(ADD_CHILD_TIMER(profile, "RegisterTabletInfo", "AddTablet"),
232
285k
                   static_cast<int64_t>(watch.reset()));
233
234
285k
    VLOG_NOTICE << "add tablet to map successfully."
235
99
                << " tablet_id=" << tablet_id;
236
237
285k
    return res;
238
285k
}
239
240
0
bool TabletManager::check_tablet_id_exist(TTabletId tablet_id) {
241
0
    std::shared_lock rdlock(_get_tablets_shard_lock(tablet_id));
242
0
    return _check_tablet_id_exist_unlocked(tablet_id);
243
0
}
244
245
0
bool TabletManager::_check_tablet_id_exist_unlocked(TTabletId tablet_id) {
246
0
    tablet_map_t& tablet_map = _get_tablet_map(tablet_id);
247
0
    return tablet_map.find(tablet_id) != tablet_map.end();
248
0
}
249
250
Status TabletManager::create_tablet(const TCreateTabletReq& request, std::vector<DataDir*> stores,
251
6.99k
                                    RuntimeProfile* profile) {
252
6.99k
    DorisMetrics::instance()->create_tablet_requests_total->increment(1);
253
254
6.99k
    int64_t tablet_id = request.tablet_id;
255
6.99k
    LOG(INFO) << "begin to create tablet. tablet_id=" << tablet_id
256
6.99k
              << ", table_id=" << request.table_id << ", partition_id=" << request.partition_id
257
6.99k
              << ", replica_id=" << request.replica_id << ", stores.size=" << stores.size()
258
6.99k
              << ", first store=" << stores[0]->path();
259
260
    // when we create rollup tablet A(assume on shard-1) from tablet B(assume on shard-2)
261
    // we need use write lock on shard-1 and then use read lock on shard-2
262
    // if there have create rollup tablet C(assume on shard-2) from tablet D(assume on shard-1) at the same time, we will meet deadlock
263
6.99k
    std::unique_lock two_tablet_lock(_two_tablet_mtx, std::defer_lock);
264
6.99k
    bool in_restore_mode = request.__isset.in_restore_mode && request.in_restore_mode;
265
6.99k
    bool is_schema_change_or_atomic_restore =
266
6.99k
            request.__isset.base_tablet_id && request.base_tablet_id > 0;
267
6.99k
    bool need_two_lock =
268
6.99k
            is_schema_change_or_atomic_restore &&
269
6.99k
            ((_tablets_shards_mask & request.base_tablet_id) != (_tablets_shards_mask & tablet_id));
270
6.99k
    if (need_two_lock) {
271
0
        SCOPED_TIMER(ADD_TIMER(profile, "GetTwoTableLock"));
272
0
        two_tablet_lock.lock();
273
0
    }
274
275
6.99k
    MonotonicStopWatch shard_lock_watch;
276
6.99k
    shard_lock_watch.start();
277
6.99k
    std::lock_guard wrlock(_get_tablets_shard_lock(tablet_id));
278
6.99k
    shard_lock_watch.stop();
279
6.99k
    COUNTER_UPDATE(ADD_TIMER(profile, "GetShardLock"),
280
6.99k
                   static_cast<int64_t>(shard_lock_watch.elapsed_time()));
281
    // Make create_tablet operation to be idempotent:
282
    // 1. Return true if tablet with same tablet_id and schema_hash exist;
283
    //           false if tablet with same tablet_id but different schema_hash exist.
284
    // 2. When this is an alter task, if the tablet(both tablet_id and schema_hash are
285
    // same) already exist, then just return true(an duplicate request). But if
286
    // tablet_id exist but with different schema_hash, return an error(report task will
287
    // eventually trigger its deletion).
288
6.99k
    {
289
6.99k
        SCOPED_TIMER(ADD_TIMER(profile, "GetTabletUnlocked"));
290
6.99k
        if (_get_tablet_unlocked(tablet_id) != nullptr) {
291
3
            LOG(INFO) << "success to create tablet. tablet already exist. tablet_id=" << tablet_id;
292
3
            return Status::OK();
293
3
        }
294
6.99k
    }
295
296
6.99k
    TabletSharedPtr base_tablet = nullptr;
297
    // If the CreateTabletReq has base_tablet_id then it is a alter-tablet request
298
6.99k
    if (is_schema_change_or_atomic_restore) {
299
        // if base_tablet_id's lock diffrent with new_tablet_id, we need lock it.
300
0
        if (need_two_lock) {
301
0
            SCOPED_TIMER(ADD_TIMER(profile, "GetBaseTablet"));
302
0
            base_tablet = get_tablet(request.base_tablet_id);
303
0
            two_tablet_lock.unlock();
304
0
        } else {
305
0
            SCOPED_TIMER(ADD_TIMER(profile, "GetBaseTabletUnlocked"));
306
0
            base_tablet = _get_tablet_unlocked(request.base_tablet_id);
307
0
        }
308
0
        if (base_tablet == nullptr) {
309
0
            DorisMetrics::instance()->create_tablet_requests_failed->increment(1);
310
0
            return Status::Error<TABLE_CREATE_META_ERROR>(
311
0
                    "fail to create tablet(change schema/atomic restore), base tablet does not "
312
0
                    "exist. new_tablet_id={}, base_tablet_id={}",
313
0
                    tablet_id, request.base_tablet_id);
314
0
        }
315
        // If we are doing schema-change or atomic-restore, we should use the same data dir
316
        // TODO(lingbin): A litter trick here, the directory should be determined before
317
        // entering this method
318
        //
319
        // ATTN: Since all restored replicas will be saved to HDD, so no storage_medium check here.
320
0
        if (in_restore_mode ||
321
0
            request.storage_medium == base_tablet->data_dir()->storage_medium()) {
322
0
            LOG(INFO) << "create tablet use the base tablet data dir. tablet_id=" << tablet_id
323
0
                      << ", base tablet_id=" << request.base_tablet_id
324
0
                      << ", data dir=" << base_tablet->data_dir()->path();
325
0
            stores.clear();
326
0
            stores.push_back(base_tablet->data_dir());
327
0
        }
328
0
    }
329
330
    // set alter type to schema-change. it is useless
331
6.99k
    TabletSharedPtr tablet = _internal_create_tablet_unlocked(
332
6.99k
            request, is_schema_change_or_atomic_restore, base_tablet.get(), stores, profile);
333
6.99k
    if (tablet == nullptr) {
334
0
        DorisMetrics::instance()->create_tablet_requests_failed->increment(1);
335
0
        return Status::Error<CE_CMD_PARAMS_ERROR>("fail to create tablet. tablet_id={}",
336
0
                                                  request.tablet_id);
337
0
    }
338
339
6.99k
    LOG(INFO) << "success to create tablet. tablet_id=" << tablet_id
340
6.99k
              << ", tablet_path=" << tablet->tablet_path();
341
6.99k
    return Status::OK();
342
6.99k
}
343
344
TabletSharedPtr TabletManager::_internal_create_tablet_unlocked(
345
        const TCreateTabletReq& request, const bool is_schema_change, const Tablet* base_tablet,
346
6.99k
        const std::vector<DataDir*>& data_dirs, RuntimeProfile* profile) {
347
    // If in schema-change state, base_tablet must also be provided.
348
    // i.e., is_schema_change and base_tablet are either assigned or not assigned
349
6.99k
    DCHECK((is_schema_change && base_tablet) || (!is_schema_change && !base_tablet));
350
351
    // NOTE: The existence of tablet_id and schema_hash has already been checked,
352
    // no need check again here.
353
354
6.99k
    const std::string parent_timer_name = "InternalCreateTablet";
355
6.99k
    SCOPED_TIMER(ADD_TIMER(profile, parent_timer_name));
356
357
6.99k
    MonotonicStopWatch watch;
358
6.99k
    watch.start();
359
6.99k
    auto create_meta_timer = ADD_CHILD_TIMER(profile, "CreateMeta", parent_timer_name);
360
6.99k
    auto tablet = _create_tablet_meta_and_dir_unlocked(request, is_schema_change, base_tablet,
361
6.99k
                                                       data_dirs, profile);
362
6.99k
    COUNTER_UPDATE(create_meta_timer, static_cast<int64_t>(watch.reset()));
363
6.99k
    if (tablet == nullptr) {
364
0
        return nullptr;
365
0
    }
366
367
6.99k
    int64_t new_tablet_id = request.tablet_id;
368
6.99k
    int32_t new_schema_hash = request.tablet_schema.schema_hash;
369
370
    // should remove the tablet's pending_id no matter create-tablet success or not
371
6.99k
    DataDir* data_dir = tablet->data_dir();
372
373
    // TODO(yiguolei)
374
    // the following code is very difficult to understand because it mixed alter tablet v2
375
    // and alter tablet v1 should remove alter tablet v1 code after v0.12
376
6.99k
    Status res = Status::OK();
377
6.99k
    bool is_tablet_added = false;
378
6.99k
    do {
379
6.99k
        res = tablet->init();
380
6.99k
        COUNTER_UPDATE(ADD_CHILD_TIMER(profile, "TabletInit", parent_timer_name),
381
6.99k
                       static_cast<int64_t>(watch.reset()));
382
6.99k
        if (!res.ok()) {
383
0
            LOG(WARNING) << "tablet init failed. tablet:" << tablet->tablet_id();
384
0
            break;
385
0
        }
386
387
        // Create init version if this is not a restore mode replica and request.version is set
388
        // bool in_restore_mode = request.__isset.in_restore_mode && request.in_restore_mode;
389
        // if (!in_restore_mode && request.__isset.version) {
390
        // create initial rowset before add it to storage engine could omit many locks
391
6.99k
        res = tablet->create_initial_rowset(request.version);
392
6.99k
        COUNTER_UPDATE(ADD_CHILD_TIMER(profile, "InitRowset", parent_timer_name),
393
6.99k
                       static_cast<int64_t>(watch.reset()));
394
6.99k
        if (!res.ok()) {
395
0
            LOG(WARNING) << "fail to create initial version for tablet. res=" << res;
396
0
            break;
397
0
        }
398
399
6.99k
        if (is_schema_change) {
400
            // if this is a new alter tablet, has to set its state to not ready
401
            // because schema change handler depends on it to check whether history data
402
            // convert finished
403
0
            static_cast<void>(tablet->set_tablet_state(TabletState::TABLET_NOTREADY));
404
0
        }
405
        // Add tablet to StorageEngine will make it visible to user
406
        // Will persist tablet meta
407
6.99k
        auto add_tablet_timer = ADD_CHILD_TIMER(profile, "AddTablet", parent_timer_name);
408
6.99k
        res = _add_tablet_unlocked(new_tablet_id, tablet, /*update_meta*/ true, false, profile);
409
6.99k
        COUNTER_UPDATE(add_tablet_timer, static_cast<int64_t>(watch.reset()));
410
6.99k
        if (!res.ok()) {
411
0
            LOG(WARNING) << "fail to add tablet to StorageEngine. res=" << res;
412
0
            break;
413
0
        }
414
6.99k
        is_tablet_added = true;
415
416
        // TODO(lingbin): The following logic seems useless, can be removed?
417
        // Because if _add_tablet_unlocked() return OK, we must can get it from map.
418
6.99k
        TabletSharedPtr tablet_ptr = _get_tablet_unlocked(new_tablet_id);
419
6.99k
        COUNTER_UPDATE(ADD_CHILD_TIMER(profile, "GetTablet", parent_timer_name),
420
6.99k
                       static_cast<int64_t>(watch.reset()));
421
6.99k
        if (tablet_ptr == nullptr) {
422
0
            res = Status::Error<TABLE_NOT_FOUND>("fail to get tablet. res={}", res);
423
0
            break;
424
0
        }
425
6.99k
    } while (false);
426
427
6.99k
    if (res.ok()) {
428
6.98k
        return tablet;
429
6.98k
    }
430
    // something is wrong, we need clear environment
431
6
    if (is_tablet_added) {
432
0
        Status status = _drop_tablet(new_tablet_id, request.replica_id, false, false, true);
433
0
        COUNTER_UPDATE(ADD_CHILD_TIMER(profile, "DropTablet", parent_timer_name),
434
0
                       static_cast<int64_t>(watch.reset()));
435
0
        if (!status.ok()) {
436
0
            LOG(WARNING) << "fail to drop tablet when create tablet failed. res=" << res;
437
0
        }
438
6
    } else {
439
6
        tablet->delete_all_files();
440
6
        static_cast<void>(TabletMetaManager::remove(data_dir, new_tablet_id, new_schema_hash));
441
6
        COUNTER_UPDATE(ADD_CHILD_TIMER(profile, "RemoveTabletFiles", parent_timer_name),
442
6
                       static_cast<int64_t>(watch.reset()));
443
6
    }
444
6
    return nullptr;
445
6.99k
}
446
447
6.94k
static string _gen_tablet_dir(const string& dir, int32_t shard_id, int64_t tablet_id) {
448
6.94k
    string path = dir;
449
6.94k
    path = path_util::join_path_segments(path, DATA_PREFIX);
450
6.94k
    path = path_util::join_path_segments(path, std::to_string(shard_id));
451
6.94k
    path = path_util::join_path_segments(path, std::to_string(tablet_id));
452
6.94k
    return path;
453
6.94k
}
454
455
TabletSharedPtr TabletManager::_create_tablet_meta_and_dir_unlocked(
456
        const TCreateTabletReq& request, const bool is_schema_change, const Tablet* base_tablet,
457
6.99k
        const std::vector<DataDir*>& data_dirs, RuntimeProfile* profile) {
458
6.99k
    string pending_id = TABLET_ID_PREFIX + std::to_string(request.tablet_id);
459
    // Many attempts are made here in the hope that even if a disk fails, it can still continue.
460
6.99k
    std::string parent_timer_name = "CreateMeta";
461
6.99k
    MonotonicStopWatch watch;
462
6.99k
    watch.start();
463
6.99k
    for (auto& data_dir : data_dirs) {
464
6.98k
        COUNTER_UPDATE(ADD_CHILD_TIMER(profile, "RemovePendingIds", parent_timer_name),
465
6.98k
                       static_cast<int64_t>(watch.reset()));
466
467
6.98k
        TabletMetaSharedPtr tablet_meta;
468
        // if create meta failed, do not need to clean dir, because it is only in memory
469
6.98k
        Status res = _create_tablet_meta_unlocked(request, data_dir, is_schema_change, base_tablet,
470
6.98k
                                                  &tablet_meta);
471
6.98k
        COUNTER_UPDATE(ADD_CHILD_TIMER(profile, "CreateMetaUnlock", parent_timer_name),
472
6.98k
                       static_cast<int64_t>(watch.reset()));
473
6.98k
        if (!res.ok()) {
474
0
            LOG(WARNING) << "fail to create tablet meta. res=" << res
475
0
                         << ", root=" << data_dir->path();
476
0
            continue;
477
0
        }
478
479
6.98k
        string tablet_dir =
480
6.98k
                _gen_tablet_dir(data_dir->path(), tablet_meta->shard_id(), request.tablet_id);
481
6.98k
        string schema_hash_dir = path_util::join_path_segments(
482
6.98k
                tablet_dir, std::to_string(request.tablet_schema.schema_hash));
483
6.98k
        bool has_row_binlog = tablet_meta->binlog_config().is_enable() &&
484
6.98k
                              tablet_meta->binlog_config().is_row_binlog_format();
485
6.98k
        string row_binlog_dir = path_util::join_path_segments(schema_hash_dir, "_row_binlog");
486
487
        // Because the tablet is removed asynchronously, so that the dir may still exist when BE
488
        // receive create-tablet request again, For example retried schema-change request
489
6.98k
        bool exists = true;
490
6.98k
        res = io::global_local_filesystem()->exists(schema_hash_dir, &exists);
491
6.98k
        if (!res.ok()) {
492
0
            continue;
493
0
        }
494
6.98k
        if (exists) {
495
0
            LOG(WARNING) << "skip this dir because tablet path exist, path=" << schema_hash_dir;
496
0
            continue;
497
6.98k
        } else {
498
6.98k
            Status st = io::global_local_filesystem()->create_directory(schema_hash_dir);
499
6.98k
            if (!st.ok()) {
500
0
                continue;
501
0
            }
502
6.98k
        }
503
504
6.98k
        if (has_row_binlog) {
505
6
            Status st = io::global_local_filesystem()->create_directory(row_binlog_dir);
506
6
            if (!st.ok()) {
507
0
                WARN_IF_ERROR(io::global_local_filesystem()->delete_directory(schema_hash_dir),
508
0
                              "failed to cleanup tablet dir after create sub directory failed");
509
0
                continue;
510
0
            }
511
6
        }
512
513
6.98k
        if (tablet_meta->partition_id() <= 0) {
514
233
            LOG(WARNING) << "invalid partition id " << tablet_meta->partition_id() << ", tablet "
515
233
                         << tablet_meta->tablet_id();
516
233
        }
517
6.98k
        TabletSharedPtr new_tablet =
518
6.98k
                std::make_shared<Tablet>(_engine, std::move(tablet_meta), data_dir);
519
6.98k
        COUNTER_UPDATE(ADD_CHILD_TIMER(profile, "CreateTabletFromMeta", parent_timer_name),
520
6.98k
                       static_cast<int64_t>(watch.reset()));
521
6.98k
        return new_tablet;
522
6.98k
    }
523
8
    return nullptr;
524
6.99k
}
525
526
Status TabletManager::drop_tablet(TTabletId tablet_id, TReplicaId replica_id,
527
4.91k
                                  bool is_drop_table_or_partition) {
528
4.91k
    return _drop_tablet(tablet_id, replica_id, false, is_drop_table_or_partition, false);
529
4.91k
}
530
531
// Drop specified tablet.
532
Status TabletManager::_drop_tablet(TTabletId tablet_id, TReplicaId replica_id, bool keep_files,
533
5.08k
                                   bool is_drop_table_or_partition, bool had_held_shard_lock) {
534
5.08k
    LOG(INFO) << "begin drop tablet. tablet_id=" << tablet_id << ", replica_id=" << replica_id
535
5.08k
              << ", is_drop_table_or_partition=" << is_drop_table_or_partition
536
5.08k
              << ", keep_files=" << keep_files;
537
5.08k
    DorisMetrics::instance()->drop_tablet_requests_total->increment(1);
538
539
5.08k
    RETURN_IF_ERROR(register_transition_tablet(tablet_id, "drop tablet"));
540
5.08k
    Defer defer {[&]() { unregister_transition_tablet(tablet_id, "drop tablet"); }};
541
542
    // Fetch tablet which need to be dropped
543
5.08k
    TabletSharedPtr to_drop_tablet;
544
5.08k
    {
545
5.08k
        std::unique_lock<std::shared_mutex> wlock(_get_tablets_shard_lock(tablet_id),
546
5.08k
                                                  std::defer_lock);
547
5.08k
        if (!had_held_shard_lock) {
548
4.91k
            wlock.lock();
549
4.91k
        }
550
5.08k
        to_drop_tablet = _get_tablet_unlocked(tablet_id);
551
5.08k
        if (to_drop_tablet == nullptr) {
552
1
            LOG(WARNING) << "fail to drop tablet because it does not exist. "
553
1
                         << "tablet_id=" << tablet_id;
554
1
            return Status::OK();
555
1
        }
556
557
        // We should compare replica id to avoid dropping new cloned tablet.
558
        // Iff request replica id is 0, FE may be an older release, then we drop this tablet as before.
559
5.08k
        if (to_drop_tablet->replica_id() != replica_id && replica_id != 0) {
560
0
            return Status::Aborted("replica_id not match({} vs {})", to_drop_tablet->replica_id(),
561
0
                                   replica_id);
562
0
        }
563
564
5.08k
        _remove_tablet_from_partition(to_drop_tablet);
565
5.08k
        tablet_map_t& tablet_map = _get_tablet_map(tablet_id);
566
5.08k
        tablet_map.erase(tablet_id);
567
5.08k
    }
568
569
0
    to_drop_tablet->clear_cache();
570
571
5.08k
    {
572
        // drop tablet will update tablet meta, should lock
573
5.08k
        std::lock_guard<std::shared_mutex> wrlock(to_drop_tablet->get_header_lock());
574
5.08k
        SCOPED_SIMPLE_TRACE_IF_TIMEOUT(TRACE_TABLET_LOCK_THRESHOLD);
575
        // NOTE: has to update tablet here, but must not update tablet meta directly.
576
        // because other thread may hold the tablet object, they may save meta too.
577
        // If update meta directly here, other thread may override the meta
578
        // and the tablet will be loaded at restart time.
579
        // To avoid this exception, we first set the state of the tablet to `SHUTDOWN`.
580
        //
581
        // Until now, only the restore task uses keep files.
582
5.08k
        RETURN_IF_ERROR(to_drop_tablet->set_tablet_state(TABLET_SHUTDOWN));
583
5.08k
        if (!keep_files) {
584
4.91k
            LOG(INFO) << "set tablet to shutdown state and remove it from memory. "
585
4.91k
                      << "tablet_id=" << tablet_id
586
4.91k
                      << ", tablet_path=" << to_drop_tablet->tablet_path();
587
            // We must record unused remote rowsets path info to OlapMeta before tablet state is marked as TABLET_SHUTDOWN in OlapMeta,
588
            // otherwise if BE shutdown after saving tablet state, these remote rowsets path info will lost.
589
4.91k
            if (is_drop_table_or_partition) {
590
4.65k
                RETURN_IF_ERROR(to_drop_tablet->remove_all_remote_rowsets());
591
4.65k
            }
592
4.91k
            to_drop_tablet->save_meta();
593
4.91k
            {
594
4.91k
                std::lock_guard<std::shared_mutex> wrdlock(_shutdown_tablets_lock);
595
4.91k
                _shutdown_tablets.push_back(to_drop_tablet);
596
4.91k
            }
597
4.91k
        }
598
5.08k
    }
599
600
5.08k
    to_drop_tablet->deregister_tablet_from_dir();
601
5.08k
    g_tablet_meta_schema_columns_count << -to_drop_tablet->tablet_meta()->tablet_columns_num();
602
5.08k
    return Status::OK();
603
5.08k
}
604
605
1.35M
TabletSharedPtr TabletManager::get_tablet(TTabletId tablet_id, bool include_deleted, string* err) {
606
1.35M
    std::shared_lock rdlock(_get_tablets_shard_lock(tablet_id));
607
1.35M
    return _get_tablet_unlocked(tablet_id, include_deleted, err);
608
1.35M
}
609
610
194
std::vector<TabletSharedPtr> TabletManager::get_all_tablet(std::function<bool(Tablet*)>&& filter) {
611
194
    std::vector<TabletSharedPtr> res;
612
290k
    for_each_tablet([&](const TabletSharedPtr& tablet) { res.emplace_back(tablet); },
613
194
                    std::move(filter));
614
194
    return res;
615
194
}
616
617
void TabletManager::for_each_tablet(std::function<void(const TabletSharedPtr&)>&& handler,
618
12.0k
                                    std::function<bool(Tablet*)>&& filter) {
619
12.0k
    std::vector<TabletSharedPtr> tablets;
620
3.07M
    for (const auto& tablets_shard : _tablets_shards) {
621
3.07M
        tablets.clear();
622
3.07M
        {
623
3.07M
            std::shared_lock rdlock(tablets_shard.lock);
624
358M
            for (const auto& [id, tablet] : tablets_shard.tablet_map) {
625
358M
                if (filter(tablet.get())) {
626
355M
                    tablets.emplace_back(tablet);
627
355M
                }
628
358M
            }
629
3.07M
        }
630
355M
        for (const auto& tablet : tablets) {
631
355M
            handler(tablet);
632
355M
        }
633
3.07M
    }
634
12.0k
}
635
636
TabletSharedPtr TabletManager::_get_tablet_unlocked(TTabletId tablet_id, bool include_deleted,
637
1.36M
                                                    string* err) {
638
1.36M
    TabletSharedPtr tablet;
639
1.36M
    tablet = _get_tablet_unlocked(tablet_id);
640
1.36M
    if (tablet == nullptr && include_deleted) {
641
40
        std::shared_lock rdlock(_shutdown_tablets_lock);
642
5.12k
        for (auto& deleted_tablet : _shutdown_tablets) {
643
5.12k
            CHECK(deleted_tablet != nullptr) << "deleted tablet is nullptr";
644
5.12k
            if (deleted_tablet->tablet_id() == tablet_id) {
645
0
                tablet = deleted_tablet;
646
0
                break;
647
0
            }
648
5.12k
        }
649
40
    }
650
651
1.36M
    if (tablet == nullptr) {
652
7.96k
        if (err != nullptr) {
653
40
            *err = "tablet does not exist. " + BackendOptions::get_localhost();
654
40
        }
655
7.96k
        return nullptr;
656
7.96k
    }
657
1.35M
#ifndef BE_TEST
658
1.35M
    if (!tablet->is_used()) {
659
0
        LOG(WARNING) << "tablet cannot be used. tablet=" << tablet_id;
660
0
        if (err != nullptr) {
661
0
            *err = "tablet cannot be used. " + BackendOptions::get_localhost();
662
0
        }
663
0
        return nullptr;
664
0
    }
665
1.35M
#endif
666
667
1.35M
    return tablet;
668
1.35M
}
669
670
TabletSharedPtr TabletManager::get_tablet(TTabletId tablet_id, TabletUid tablet_uid,
671
17.0k
                                          bool include_deleted, string* err) {
672
17.0k
    std::shared_lock rdlock(_get_tablets_shard_lock(tablet_id));
673
17.0k
    TabletSharedPtr tablet = _get_tablet_unlocked(tablet_id, include_deleted, err);
674
17.0k
    if (tablet != nullptr && tablet->tablet_uid() == tablet_uid) {
675
17.0k
        return tablet;
676
17.0k
    }
677
2
    return nullptr;
678
17.0k
}
679
680
524
uint64_t TabletManager::get_rowset_nums() {
681
524
    uint64_t rowset_nums = 0;
682
4.60M
    for_each_tablet([&](const TabletSharedPtr& tablet) { rowset_nums += tablet->version_count(); },
683
524
                    filter_all_tablets);
684
524
    return rowset_nums;
685
524
}
686
687
524
uint64_t TabletManager::get_segment_nums() {
688
524
    uint64_t segment_nums = 0;
689
4.60M
    for_each_tablet([&](const TabletSharedPtr& tablet) { segment_nums += tablet->segment_count(); },
690
524
                    filter_all_tablets);
691
524
    return segment_nums;
692
524
}
693
694
bool TabletManager::get_tablet_id_and_schema_hash_from_path(const string& path,
695
                                                            TTabletId* tablet_id,
696
562k
                                                            TSchemaHash* schema_hash) {
697
    // the path like: /data/14/10080/964828783/
698
562k
    static re2::RE2 normal_re("/data/\\d+/(\\d+)/(\\d+)($|/)");
699
    // match tablet schema hash data path, for example, the path is /data/1/16791/29998
700
    // 1 is shard id , 16791 is tablet id, 29998 is schema hash
701
562k
    if (RE2::PartialMatch(path, normal_re, tablet_id, schema_hash)) {
702
562k
        return true;
703
562k
    }
704
705
    // If we can't match normal path pattern, this may be a path which is a empty tablet
706
    // directory. Use this pattern to match empty tablet directory. In this case schema_hash
707
    // will be set to zero.
708
4
    static re2::RE2 empty_tablet_re("/data/\\d+/(\\d+)($|/$)");
709
4
    if (!RE2::PartialMatch(path, empty_tablet_re, tablet_id)) {
710
2
        return false;
711
2
    }
712
2
    *schema_hash = 0;
713
2
    return true;
714
4
}
715
716
3
bool TabletManager::get_rowset_id_from_path(const string& path, RowsetId* rowset_id) {
717
    // the path like: /data/14/10080/964828783/02000000000000969144d8725cb62765f9af6cd3125d5a91_0.dat
718
3
    static re2::RE2 re("/data/\\d+/\\d+/\\d+/([A-Fa-f0-9]+)_.*");
719
3
    string id_str;
720
3
    bool ret = RE2::PartialMatch(path, re, &id_str);
721
3
    if (ret) {
722
1
        rowset_id->init(id_str);
723
1
        return true;
724
1
    }
725
2
    return false;
726
3
}
727
728
131
void TabletManager::get_tablet_stat(TTabletStatResult* result) {
729
131
    std::shared_ptr<std::vector<TTabletStat>> local_cache;
730
131
    {
731
131
        std::lock_guard<std::mutex> guard(_tablet_stat_cache_mutex);
732
131
        local_cache = _tablet_stat_list_cache;
733
131
    }
734
131
    result->__set_tablet_stat_list(*local_cache);
735
131
}
736
737
struct TabletScore {
738
    TabletSharedPtr tablet_ptr;
739
    int score;
740
};
741
742
std::vector<TabletSharedPtr> TabletManager::find_best_tablets_to_compaction(
743
        CompactionType compaction_type, DataDir* data_dir,
744
        const std::unordered_set<TabletSharedPtr>& tablet_submitted_compaction, uint32_t* score,
745
        const std::unordered_map<std::string_view, std::shared_ptr<CumulativeCompactionPolicy>>&
746
9.85k
                all_cumulative_compaction_policies) {
747
9.85k
    int64_t now_ms = UnixMillis();
748
9.85k
    const string& compaction_type_str =
749
9.85k
            compaction_type == CompactionType::BASE_COMPACTION ? "base" : "cumulative";
750
9.85k
    uint32_t highest_score = 0;
751
    // find the single compaction tablet
752
9.85k
    uint32_t single_compact_highest_score = 0;
753
9.85k
    TabletSharedPtr best_tablet;
754
9.85k
    TabletSharedPtr best_single_compact_tablet;
755
9.85k
    int64_t compaction_num_per_round =
756
9.85k
            ExecEnv::GetInstance()->storage_engine().to_local().get_compaction_num_per_round();
757
1.87M
    auto cmp = [](TabletScore left, TabletScore right) { return left.score > right.score; };
758
9.85k
    std::priority_queue<TabletScore, std::vector<TabletScore>, decltype(cmp)> top_tablets(cmp);
759
760
337M
    auto handler = [&](const TabletSharedPtr& tablet_ptr) {
761
337M
        if (tablet_ptr->tablet_meta()->tablet_schema()->disable_auto_compaction()) {
762
1.56M
            LOG_EVERY_N(INFO, 500) << "Tablet " << tablet_ptr->tablet_id()
763
3.13k
                                   << " will be ignored by automatic compaction tasks since it's "
764
3.13k
                                   << "set to disabled automatic compaction.";
765
1.56M
            return;
766
1.56M
        }
767
768
336M
        if (config::enable_skip_tablet_compaction &&
769
336M
            tablet_ptr->should_skip_compaction(compaction_type, UnixSeconds())) {
770
313M
            return;
771
313M
        }
772
22.9M
        if (!tablet_ptr->can_do_compaction(data_dir->path_hash(), compaction_type)) {
773
8.25M
            return;
774
8.25M
        }
775
776
14.7M
        auto search = tablet_submitted_compaction.find(tablet_ptr);
777
14.7M
        if (search != tablet_submitted_compaction.end()) {
778
902
            return;
779
902
        }
780
781
14.7M
        int64_t last_failure_ms = tablet_ptr->last_cumu_compaction_failure_time();
782
14.7M
        if (compaction_type == CompactionType::BASE_COMPACTION) {
783
6.16M
            last_failure_ms = tablet_ptr->last_base_compaction_failure_time();
784
6.16M
        }
785
14.7M
        if (now_ms - last_failure_ms <= config::tablet_sched_delay_time_ms) {
786
882k
            VLOG_DEBUG << "Too often to check compaction, skip it. "
787
0
                       << "compaction_type=" << compaction_type_str
788
0
                       << ", last_failure_time_ms=" << last_failure_ms
789
0
                       << ", tablet_id=" << tablet_ptr->tablet_id();
790
882k
            return;
791
882k
        }
792
793
13.8M
        if (compaction_type == CompactionType::BASE_COMPACTION) {
794
6.15M
            std::unique_lock<std::mutex> lock(tablet_ptr->get_base_compaction_lock(),
795
6.15M
                                              std::try_to_lock);
796
6.15M
            if (!lock.owns_lock()) {
797
0
                LOG(INFO) << "can not get base lock: " << tablet_ptr->tablet_id();
798
0
                return;
799
0
            }
800
7.68M
        } else {
801
7.68M
            std::unique_lock<std::mutex> lock(tablet_ptr->get_cumulative_compaction_lock(),
802
7.68M
                                              std::try_to_lock);
803
7.68M
            if (!lock.owns_lock()) {
804
0
                LOG(INFO) << "can not get cumu lock: " << tablet_ptr->tablet_id();
805
0
                return;
806
0
            }
807
7.68M
        }
808
13.8M
        auto cumulative_compaction_policy = all_cumulative_compaction_policies.at(
809
13.8M
                tablet_ptr->tablet_meta()->compaction_policy());
810
13.8M
        uint32_t current_compaction_score = tablet_ptr->calc_compaction_score();
811
13.8M
        if (current_compaction_score < 5) {
812
13.4M
            tablet_ptr->set_skip_compaction(true, compaction_type, UnixSeconds());
813
13.4M
        }
814
815
13.8M
        if (current_compaction_score <= 0) {
816
0
            return;
817
0
        }
818
819
        // tablet should do single compaction
820
13.8M
        if (current_compaction_score > single_compact_highest_score &&
821
13.8M
            tablet_ptr->should_fetch_from_peer()) {
822
3
            bool ret = tablet_ptr->suitable_for_compaction(compaction_type,
823
3
                                                           cumulative_compaction_policy);
824
3
            if (ret) {
825
3
                single_compact_highest_score = current_compaction_score;
826
3
                best_single_compact_tablet = tablet_ptr;
827
3
            }
828
3
        }
829
830
13.8M
        if (compaction_num_per_round > 1 && !tablet_ptr->should_fetch_from_peer()) {
831
13.8M
            TabletScore ts;
832
13.8M
            ts.score = current_compaction_score;
833
13.8M
            ts.tablet_ptr = tablet_ptr;
834
13.8M
            if ((top_tablets.size() >= compaction_num_per_round &&
835
13.8M
                 current_compaction_score > top_tablets.top().score) ||
836
13.8M
                top_tablets.size() < compaction_num_per_round) {
837
979k
                bool ret = tablet_ptr->suitable_for_compaction(compaction_type,
838
979k
                                                               cumulative_compaction_policy);
839
979k
                if (ret) {
840
313k
                    top_tablets.push(ts);
841
313k
                    if (top_tablets.size() > compaction_num_per_round) {
842
105k
                        top_tablets.pop();
843
105k
                    }
844
313k
                    highest_score = std::max(current_compaction_score, highest_score);
845
313k
                }
846
979k
            }
847
13.8M
        } else {
848
52
            if (current_compaction_score > highest_score && !tablet_ptr->should_fetch_from_peer()) {
849
3
                bool ret = tablet_ptr->suitable_for_compaction(compaction_type,
850
3
                                                               cumulative_compaction_policy);
851
3
                if (ret) {
852
3
                    highest_score = current_compaction_score;
853
3
                    best_tablet = tablet_ptr;
854
3
                }
855
3
            }
856
52
        }
857
13.8M
    };
858
859
9.85k
    for_each_tablet(handler, filter_all_tablets);
860
9.85k
    std::vector<TabletSharedPtr> picked_tablet;
861
9.85k
    if (best_tablet != nullptr) {
862
3
        VLOG_CRITICAL << "Found the best tablet for compaction. "
863
3
                      << "compaction_type=" << compaction_type_str
864
3
                      << ", tablet_id=" << best_tablet->tablet_id() << ", path=" << data_dir->path()
865
3
                      << ", highest_score=" << highest_score
866
3
                      << ", fetch from peer: " << best_tablet->should_fetch_from_peer();
867
3
        picked_tablet.emplace_back(std::move(best_tablet));
868
3
    }
869
870
9.85k
    std::vector<TabletSharedPtr> reverse_top_tablets;
871
217k
    while (!top_tablets.empty()) {
872
208k
        reverse_top_tablets.emplace_back(top_tablets.top().tablet_ptr);
873
208k
        top_tablets.pop();
874
208k
    }
875
876
217k
    for (auto it = reverse_top_tablets.rbegin(); it != reverse_top_tablets.rend(); ++it) {
877
208k
        picked_tablet.emplace_back(*it);
878
208k
    }
879
880
    // pick single compaction tablet needs the highest score
881
9.85k
    if (best_single_compact_tablet != nullptr && single_compact_highest_score >= highest_score) {
882
2
        VLOG_CRITICAL << "Found the best tablet for single compaction. "
883
2
                      << "compaction_type=" << compaction_type_str
884
2
                      << ", tablet_id=" << best_single_compact_tablet->tablet_id()
885
2
                      << ", path=" << data_dir->path()
886
2
                      << ", highest_score=" << single_compact_highest_score << ", fetch from peer: "
887
2
                      << best_single_compact_tablet->should_fetch_from_peer();
888
2
        picked_tablet.emplace_back(std::move(best_single_compact_tablet));
889
2
    }
890
9.85k
    *score = highest_score > single_compact_highest_score ? highest_score
891
9.85k
                                                          : single_compact_highest_score;
892
9.85k
    return picked_tablet;
893
9.85k
}
894
895
Status TabletManager::load_tablet_from_meta(DataDir* data_dir, TTabletId tablet_id,
896
                                            TSchemaHash schema_hash, std::string_view meta_binary,
897
                                            bool update_meta, bool force, bool restore,
898
278k
                                            bool check_path) {
899
278k
    TabletMetaSharedPtr tablet_meta(new TabletMeta());
900
278k
    Status status = tablet_meta->deserialize(meta_binary);
901
278k
    if (!status.ok()) {
902
0
        return Status::Error<HEADER_PB_PARSE_FAILED>(
903
0
                "fail to load tablet because can not parse meta_binary string. tablet_id={}, "
904
0
                "schema_hash={}, path={}, status={}",
905
0
                tablet_id, schema_hash, data_dir->path(), status);
906
0
    }
907
908
    // check if tablet meta is valid
909
278k
    if (tablet_meta->tablet_id() != tablet_id || tablet_meta->schema_hash() != schema_hash) {
910
0
        return Status::Error<HEADER_PB_PARSE_FAILED>(
911
0
                "fail to load tablet because meet invalid tablet meta. trying to load "
912
0
                "tablet(tablet_id={}, schema_hash={}), but meet tablet={}, path={}",
913
0
                tablet_id, schema_hash, tablet_meta->tablet_id(), data_dir->path());
914
0
    }
915
278k
    if (tablet_meta->tablet_uid().hi == 0 && tablet_meta->tablet_uid().lo == 0) {
916
0
        return Status::Error<HEADER_PB_PARSE_FAILED>(
917
0
                "fail to load tablet because its uid == 0. tablet={}, path={}",
918
0
                tablet_meta->tablet_id(), data_dir->path());
919
0
    }
920
921
278k
    if (restore) {
922
        // we're restoring tablet from trash, tablet state should be changed from shutdown back to running
923
0
        tablet_meta->set_tablet_state(TABLET_RUNNING);
924
0
    }
925
926
278k
    if (tablet_meta->partition_id() == 0) {
927
1
        LOG(WARNING) << "tablet=" << tablet_id << " load from meta but partition id eq 0";
928
1
    }
929
930
278k
    TabletSharedPtr tablet = std::make_shared<Tablet>(_engine, std::move(tablet_meta), data_dir);
931
932
    // NOTE: method load_tablet_from_meta could be called by two cases as below
933
    // case 1: BE start;
934
    // case 2: Clone Task/Restore
935
    // For case 1 doesn't need path check because BE is just starting and not ready,
936
    // just check tablet meta status to judge whether tablet is delete is enough.
937
    // For case 2, If a tablet has just been copied to local BE,
938
    // it may be cleared by gc-thread(see perform_tablet_gc) because the tablet meta may not be loaded to memory.
939
    // So clone task should check path and then failed and retry in this case.
940
278k
    if (check_path) {
941
176
        bool exists = true;
942
176
        RETURN_IF_ERROR(io::global_local_filesystem()->exists(tablet->tablet_path(), &exists));
943
176
        if (!exists) {
944
0
            return Status::Error<TABLE_ALREADY_DELETED_ERROR>(
945
0
                    "tablet path not exists, create tablet failed, path={}", tablet->tablet_path());
946
0
        }
947
176
    }
948
949
278k
    if (tablet->tablet_meta()->tablet_state() == TABLET_SHUTDOWN) {
950
22
        {
951
22
            std::lock_guard<std::shared_mutex> shutdown_tablets_wrlock(_shutdown_tablets_lock);
952
22
            _shutdown_tablets.push_back(tablet);
953
22
        }
954
22
        return Status::Error<TABLE_ALREADY_DELETED_ERROR>(
955
22
                "fail to load tablet because it is to be deleted. tablet_id={}, schema_hash={}, "
956
22
                "path={}",
957
22
                tablet_id, schema_hash, data_dir->path());
958
22
    }
959
    // NOTE: We do not check tablet's initial version here, because if BE restarts when
960
    // one tablet is doing schema-change, we may meet empty tablet.
961
278k
    if (tablet->max_version().first == -1 && tablet->tablet_state() == TABLET_RUNNING) {
962
        // tablet state is invalid, drop tablet
963
0
        return Status::Error<TABLE_INDEX_VALIDATE_ERROR>(
964
0
                "fail to load tablet. it is in running state but without delta. tablet={}, path={}",
965
0
                tablet->tablet_id(), data_dir->path());
966
0
    }
967
968
278k
    RETURN_NOT_OK_STATUS_WITH_WARN(
969
278k
            tablet->init(), absl::Substitute("tablet init failed. tablet=$0", tablet->tablet_id()));
970
971
278k
    RuntimeProfile profile("CreateTablet");
972
278k
    std::lock_guard<std::shared_mutex> wrlock(_get_tablets_shard_lock(tablet_id));
973
278k
    RETURN_NOT_OK_STATUS_WITH_WARN(
974
278k
            _add_tablet_unlocked(tablet_id, tablet, update_meta, force, &profile),
975
278k
            absl::Substitute("fail to add tablet. tablet=$0", tablet->tablet_id()));
976
977
278k
    return Status::OK();
978
278k
}
979
980
Status TabletManager::load_tablet_from_dir(DataDir* store, TTabletId tablet_id,
981
                                           SchemaHash schema_hash, const string& schema_hash_path,
982
175
                                           bool force, bool restore) {
983
175
    LOG(INFO) << "begin to load tablet from dir. "
984
175
              << " tablet_id=" << tablet_id << " schema_hash=" << schema_hash
985
175
              << " path = " << schema_hash_path << " force = " << force << " restore = " << restore;
986
    // not add lock here, because load_tablet_from_meta already add lock
987
175
    std::string header_path = TabletMeta::construct_header_file_path(schema_hash_path, tablet_id);
988
    // should change shard id before load tablet
989
175
    std::string shard_path =
990
175
            path_util::dir_name(path_util::dir_name(path_util::dir_name(header_path)));
991
175
    std::string shard_str = shard_path.substr(shard_path.find_last_of('/') + 1);
992
175
    int32_t shard = static_cast<int32_t>(stol(shard_str));
993
994
175
    bool exists = false;
995
175
    RETURN_IF_ERROR(io::global_local_filesystem()->exists(header_path, &exists));
996
175
    if (!exists) {
997
0
        return Status::Error<NOT_FOUND>("fail to find header file. [header_path={}]", header_path);
998
0
    }
999
1000
175
    TabletMetaSharedPtr tablet_meta(new TabletMeta());
1001
175
    if (!tablet_meta->create_from_file(header_path).ok()) {
1002
0
        return Status::Error<ENGINE_LOAD_INDEX_TABLE_ERROR>(
1003
0
                "fail to load tablet_meta. file_path={}", header_path);
1004
0
    }
1005
175
    TabletUid tablet_uid = TabletUid::gen_uid();
1006
1007
    // remove rowset binlog metas
1008
175
    auto binlog_metas_file = fmt::format("{}/rowset_binlog_metas.pb", schema_hash_path);
1009
175
    bool binlog_metas_file_exists = false;
1010
175
    auto file_exists_status =
1011
175
            io::global_local_filesystem()->exists(binlog_metas_file, &binlog_metas_file_exists);
1012
175
    if (!file_exists_status.ok()) {
1013
0
        return file_exists_status;
1014
0
    }
1015
175
    bool contain_binlog = false;
1016
175
    RowsetBinlogMetasPB rowset_binlog_metas_pb;
1017
175
    if (binlog_metas_file_exists) {
1018
0
        auto binlog_meta_filesize = std::filesystem::file_size(binlog_metas_file);
1019
0
        if (binlog_meta_filesize > 0) {
1020
0
            contain_binlog = true;
1021
0
            RETURN_IF_ERROR(read_pb(binlog_metas_file, &rowset_binlog_metas_pb));
1022
0
            VLOG_DEBUG << "load rowset binlog metas from file. file_path=" << binlog_metas_file;
1023
0
        }
1024
0
        RETURN_IF_ERROR(io::global_local_filesystem()->delete_file(binlog_metas_file));
1025
0
    }
1026
175
    if (contain_binlog) {
1027
0
        auto binlog_dir = fmt::format("{}/_binlog", schema_hash_path);
1028
0
        RETURN_IF_ERROR(io::global_local_filesystem()->create_directory(binlog_dir));
1029
1030
0
        std::vector<io::FileInfo> files;
1031
0
        RETURN_IF_ERROR(
1032
0
                io::global_local_filesystem()->list(schema_hash_path, true, &files, &exists));
1033
0
        for (auto& file : files) {
1034
0
            auto& filename = file.file_name;
1035
0
            std::string new_suffix;
1036
0
            std::string old_suffix;
1037
1038
0
            if (filename.ends_with(".binlog")) {
1039
0
                old_suffix = ".binlog";
1040
0
                new_suffix = ".dat";
1041
0
            } else if (filename.ends_with(".binlog-index")) {
1042
0
                old_suffix = ".binlog-index";
1043
0
                new_suffix = ".idx";
1044
0
            } else {
1045
0
                continue;
1046
0
            }
1047
1048
0
            std::string new_filename = filename;
1049
0
            new_filename.replace(filename.size() - old_suffix.size(), old_suffix.size(),
1050
0
                                 new_suffix);
1051
0
            auto from = fmt::format("{}/{}", schema_hash_path, filename);
1052
0
            auto to = fmt::format("{}/_binlog/{}", schema_hash_path, new_filename);
1053
0
            RETURN_IF_ERROR(io::global_local_filesystem()->rename(from, to));
1054
0
        }
1055
1056
0
        auto* meta = store->get_meta();
1057
        // if ingest binlog metas error, it will be gc in gc_unused_binlog_metas
1058
0
        RETURN_IF_ERROR(
1059
0
                RowsetMetaManager::ingest_binlog_metas(meta, tablet_uid, &rowset_binlog_metas_pb));
1060
0
    }
1061
1062
    // has to change shard id here, because meta file maybe copied from other source
1063
    // its shard is different from local shard
1064
175
    tablet_meta->set_shard_id(shard);
1065
    // load dir is called by clone, restore, storage migration
1066
    // should change tablet uid when tablet object changed
1067
175
    tablet_meta->set_tablet_uid(std::move(tablet_uid));
1068
175
    std::string meta_binary;
1069
175
    tablet_meta->serialize(&meta_binary);
1070
175
    RETURN_NOT_OK_STATUS_WITH_WARN(
1071
175
            load_tablet_from_meta(store, tablet_id, schema_hash, meta_binary, true, force, restore,
1072
175
                                  true),
1073
175
            absl::Substitute("fail to load tablet. header_path=$0", header_path));
1074
1075
175
    return Status::OK();
1076
175
}
1077
1078
22
Status TabletManager::report_tablet_info(TTabletInfo* tablet_info) {
1079
22
    LOG(INFO) << "begin to process report tablet info."
1080
22
              << "tablet_id=" << tablet_info->tablet_id;
1081
1082
22
    Status res = Status::OK();
1083
1084
22
    TabletSharedPtr tablet = get_tablet(tablet_info->tablet_id);
1085
22
    if (tablet == nullptr) {
1086
0
        return Status::Error<TABLE_NOT_FOUND>("can't find tablet={}", tablet_info->tablet_id);
1087
0
    }
1088
1089
22
    tablet->build_tablet_report_info(tablet_info);
1090
22
    VLOG_TRACE << "success to process report tablet info.";
1091
22
    return res;
1092
22
}
1093
1094
127
void TabletManager::build_all_report_tablets_info(std::map<TTabletId, TTablet>* tablets_info) {
1095
127
    DCHECK(tablets_info != nullptr);
1096
127
    VLOG_NOTICE << "begin to build all report tablets info";
1097
1098
    // build the expired txn map first, outside the tablet map lock
1099
127
    std::map<TabletInfo, std::vector<int64_t>> expire_txn_map;
1100
127
    _engine.txn_manager()->build_expire_txn_map(&expire_txn_map);
1101
127
    LOG(INFO) << "find expired transactions for " << expire_txn_map.size() << " tablets";
1102
1103
127
    HistogramStat tablet_version_num_hist;
1104
127
    auto local_cache = std::make_shared<std::vector<TTabletStat>>();
1105
1.21M
    auto handler = [&](const TabletSharedPtr& tablet) {
1106
1.21M
        auto& t_tablet = (*tablets_info)[tablet->tablet_id()];
1107
1.21M
        TTabletInfo& tablet_info = t_tablet.tablet_infos.emplace_back();
1108
1.21M
        tablet->build_tablet_report_info(&tablet_info, true, true);
1109
        // find expired transaction corresponding to this tablet
1110
1.21M
        TabletInfo tinfo(tablet->tablet_id(), tablet->tablet_uid());
1111
1.21M
        auto find = expire_txn_map.find(tinfo);
1112
1.21M
        if (find != expire_txn_map.end()) {
1113
20
            tablet_info.__set_transaction_ids(find->second);
1114
20
            expire_txn_map.erase(find);
1115
20
        }
1116
1.21M
        tablet_version_num_hist.add(tablet_info.total_version_count);
1117
1.21M
        auto& t_tablet_stat = local_cache->emplace_back();
1118
1.21M
        t_tablet_stat.__set_tablet_id(tablet_info.tablet_id);
1119
1.21M
        t_tablet_stat.__set_data_size(tablet_info.data_size);
1120
1.21M
        t_tablet_stat.__set_remote_data_size(tablet_info.remote_data_size);
1121
1.21M
        t_tablet_stat.__set_row_count(tablet_info.row_count);
1122
1.21M
        t_tablet_stat.__set_total_version_count(tablet_info.total_version_count);
1123
1.21M
        t_tablet_stat.__set_visible_version_count(tablet_info.visible_version_count);
1124
1.21M
        t_tablet_stat.__set_visible_version(tablet_info.version);
1125
1.21M
        t_tablet_stat.__set_local_index_size(tablet_info.local_index_size);
1126
1.21M
        t_tablet_stat.__set_local_segment_size(tablet_info.local_segment_size);
1127
1.21M
        t_tablet_stat.__set_remote_index_size(tablet_info.remote_index_size);
1128
1.21M
        t_tablet_stat.__set_remote_segment_size(tablet_info.remote_segment_size);
1129
1.21M
        if (tablet_info.__isset.binlog_size) {
1130
1.21M
            t_tablet_stat.__set_binlog_size(tablet_info.binlog_size);
1131
1.21M
            t_tablet_stat.__set_binlog_file_num(tablet_info.binlog_file_num);
1132
1.21M
        }
1133
1.21M
    };
1134
127
    for_each_tablet(handler, filter_all_tablets);
1135
1136
127
    {
1137
127
        std::lock_guard<std::mutex> guard(_tablet_stat_cache_mutex);
1138
127
        _tablet_stat_list_cache.swap(local_cache);
1139
127
    }
1140
127
    DorisMetrics::instance()->tablet_version_num_distribution->set_histogram(
1141
127
            tablet_version_num_hist);
1142
127
    LOG(INFO) << "success to build all report tablets info. tablet_count=" << tablets_info->size();
1143
127
}
1144
1145
51
Status TabletManager::start_trash_sweep() {
1146
51
    DBUG_EXECUTE_IF("TabletManager.start_trash_sweep.sleep", DBUG_BLOCK);
1147
51
    std::unique_lock<std::mutex> lock(_gc_tablets_lock, std::defer_lock);
1148
51
    if (!lock.try_lock()) {
1149
0
        return Status::OK();
1150
0
    }
1151
1152
588k
    for_each_tablet([](const TabletSharedPtr& tablet) { tablet->delete_expired_stale_rowset(); },
1153
51
                    filter_all_tablets);
1154
1155
51
    if (config::enable_check_agg_and_remove_pre_rowsets_delete_bitmap) {
1156
0
        int64_t max_useless_rowset_count = 0;
1157
0
        int64_t tablet_id_with_max_useless_rowset_count = 0;
1158
0
        int64_t max_useless_rowset_version_count = 0;
1159
0
        int64_t tablet_id_with_max_useless_rowset_version_count = 0;
1160
0
        OlapStopWatch watch;
1161
0
        for_each_tablet(
1162
0
                [&](const TabletSharedPtr& tablet) {
1163
0
                    int64_t useless_rowset_count = 0;
1164
0
                    int64_t useless_rowset_version_count = 0;
1165
0
                    tablet->check_agg_delete_bitmap_for_stale_rowsets(useless_rowset_count,
1166
0
                                                                      useless_rowset_version_count);
1167
0
                    if (useless_rowset_count > max_useless_rowset_count) {
1168
0
                        max_useless_rowset_count = useless_rowset_count;
1169
0
                        tablet_id_with_max_useless_rowset_count = tablet->tablet_id();
1170
0
                    }
1171
0
                    if (useless_rowset_version_count > max_useless_rowset_version_count) {
1172
0
                        max_useless_rowset_version_count = useless_rowset_version_count;
1173
0
                        tablet_id_with_max_useless_rowset_version_count = tablet->tablet_id();
1174
0
                    }
1175
0
                },
1176
0
                filter_all_tablets);
1177
0
        g_max_rowsets_with_useless_delete_bitmap.set_value(max_useless_rowset_count);
1178
0
        g_max_rowsets_with_useless_delete_bitmap_version.set_value(
1179
0
                max_useless_rowset_version_count);
1180
0
        LOG(INFO) << "finish check_agg_delete_bitmap_for_stale_rowsets, cost(us)="
1181
0
                  << watch.get_elapse_time_us()
1182
0
                  << ". max useless rowset count=" << max_useless_rowset_count
1183
0
                  << ", tablet_id=" << tablet_id_with_max_useless_rowset_count
1184
0
                  << ", max useless rowset version count=" << max_useless_rowset_version_count
1185
0
                  << ", tablet_id=" << tablet_id_with_max_useless_rowset_version_count;
1186
0
    }
1187
1188
51
    std::list<TabletSharedPtr>::iterator last_it;
1189
51
    {
1190
51
        std::shared_lock rdlock(_shutdown_tablets_lock);
1191
51
        last_it = _shutdown_tablets.begin();
1192
51
        if (last_it == _shutdown_tablets.end()) {
1193
14
            return Status::OK();
1194
14
        }
1195
51
    }
1196
1197
76
    auto get_batch_tablets = [this, &last_it](int limit) {
1198
76
        std::vector<TabletSharedPtr> batch_tablets;
1199
76
        std::lock_guard<std::shared_mutex> wrdlock(_shutdown_tablets_lock);
1200
4.53k
        while (last_it != _shutdown_tablets.end() && batch_tablets.size() < limit) {
1201
            // it means current tablet is referenced by other thread
1202
4.46k
            if (last_it->use_count() > 1) {
1203
0
                last_it++;
1204
4.46k
            } else {
1205
4.46k
                batch_tablets.push_back(*last_it);
1206
4.46k
                last_it = _shutdown_tablets.erase(last_it);
1207
4.46k
            }
1208
4.46k
        }
1209
1210
76
        return batch_tablets;
1211
76
    };
1212
1213
37
    std::list<TabletSharedPtr> failed_tablets;
1214
    // return true if need continue delete
1215
44
    auto delete_one_batch = [this, get_batch_tablets, &failed_tablets]() -> bool {
1216
44
        int limit = 200;
1217
76
        for (;;) {
1218
76
            auto batch_tablets = get_batch_tablets(limit);
1219
4.46k
            for (const auto& tablet : batch_tablets) {
1220
4.46k
                if (_move_tablet_to_trash(tablet)) {
1221
4.46k
                    limit--;
1222
4.46k
                } else {
1223
0
                    failed_tablets.push_back(tablet);
1224
0
                }
1225
4.46k
            }
1226
76
            if (limit <= 0) {
1227
12
                return true;
1228
12
            }
1229
64
            if (batch_tablets.empty()) {
1230
32
                return false;
1231
32
            }
1232
64
        }
1233
1234
0
        return false;
1235
44
    };
1236
1237
50
    while (delete_one_batch()) {
1238
13
#ifndef BE_TEST
1239
13
        sleep(1);
1240
13
#endif
1241
13
    }
1242
1243
37
    if (!failed_tablets.empty()) {
1244
0
        std::lock_guard<std::shared_mutex> wrlock(_shutdown_tablets_lock);
1245
0
        _shutdown_tablets.splice(_shutdown_tablets.end(), failed_tablets);
1246
0
    }
1247
1248
37
    return Status::OK();
1249
51
}
1250
1251
4.68k
bool TabletManager::_move_tablet_to_trash(const TabletSharedPtr& tablet) {
1252
4.68k
    RETURN_IF_ERROR(register_transition_tablet(tablet->tablet_id(), "move to trash"));
1253
4.68k
    Defer defer {[&]() { unregister_transition_tablet(tablet->tablet_id(), "move to trash"); }};
1254
1255
4.68k
    TabletSharedPtr tablet_in_not_shutdown = get_tablet(tablet->tablet_id());
1256
4.68k
    if (tablet_in_not_shutdown) {
1257
0
        TSchemaHash schema_hash_not_shutdown = tablet_in_not_shutdown->schema_hash();
1258
0
        size_t path_hash_not_shutdown = tablet_in_not_shutdown->data_dir()->path_hash();
1259
0
        if (tablet->schema_hash() == schema_hash_not_shutdown &&
1260
0
            tablet->data_dir()->path_hash() == path_hash_not_shutdown) {
1261
0
            tablet->clear_cache();
1262
            // shard_id in memory not eq shard_id in shutdown
1263
0
            if (tablet_in_not_shutdown->tablet_path() != tablet->tablet_path()) {
1264
0
                LOG(INFO) << "tablet path not eq shutdown tablet path, move it to trash, tablet_id="
1265
0
                          << tablet_in_not_shutdown->tablet_id()
1266
0
                          << ", mem manager tablet path=" << tablet_in_not_shutdown->tablet_path()
1267
0
                          << ", shutdown tablet path=" << tablet->tablet_path();
1268
0
                return tablet->data_dir()->move_to_trash(tablet->tablet_path());
1269
0
            } else {
1270
0
                LOG(INFO) << "tablet path eq shutdown tablet path, not move to trash, tablet_id="
1271
0
                          << tablet_in_not_shutdown->tablet_id()
1272
0
                          << ", mem manager tablet path=" << tablet_in_not_shutdown->tablet_path()
1273
0
                          << ", shutdown tablet path=" << tablet->tablet_path();
1274
0
                return true;
1275
0
            }
1276
0
        }
1277
0
    }
1278
1279
4.68k
    TabletMetaSharedPtr tablet_meta(new TabletMeta());
1280
4.68k
    int64_t get_meta_ts = MonotonicMicros();
1281
4.68k
    Status check_st = TabletMetaManager::get_meta(tablet->data_dir(), tablet->tablet_id(),
1282
4.68k
                                                  tablet->schema_hash(), tablet_meta);
1283
4.68k
    if (check_st.ok()) {
1284
4.68k
        if (tablet_meta->tablet_state() != TABLET_SHUTDOWN ||
1285
4.68k
            tablet_meta->tablet_uid() != tablet->tablet_uid()) {
1286
0
            LOG(WARNING) << "tablet's state changed to normal, skip remove dirs"
1287
0
                         << " tablet id = " << tablet_meta->tablet_id()
1288
0
                         << " schema hash = " << tablet_meta->schema_hash()
1289
0
                         << " old tablet_uid=" << tablet->tablet_uid()
1290
0
                         << " cur tablet_uid=" << tablet_meta->tablet_uid();
1291
0
            return true;
1292
0
        }
1293
1294
4.68k
        tablet->clear_cache();
1295
1296
        // move data to trash
1297
4.68k
        const auto& tablet_path = tablet->tablet_path();
1298
4.68k
        bool exists = false;
1299
4.68k
        Status exists_st = io::global_local_filesystem()->exists(tablet_path, &exists);
1300
4.68k
        if (!exists_st) {
1301
0
            return false;
1302
0
        }
1303
4.68k
        if (exists) {
1304
            // take snapshot of tablet meta
1305
4.68k
            auto meta_file_path = fmt::format("{}/{}.hdr", tablet_path, tablet->tablet_id());
1306
4.68k
            int64_t save_meta_ts = MonotonicMicros();
1307
4.68k
            auto save_st = tablet->tablet_meta()->save(meta_file_path);
1308
4.68k
            if (!save_st.ok()) {
1309
0
                LOG(WARNING) << "failed to save meta, tablet_id=" << tablet_meta->tablet_id()
1310
0
                             << ", tablet_uid=" << tablet_meta->tablet_uid()
1311
0
                             << ", error=" << save_st;
1312
0
                return false;
1313
0
            }
1314
4.68k
            int64_t now = MonotonicMicros();
1315
4.68k
            LOG(INFO) << "start to move tablet to trash. " << tablet_path
1316
4.68k
                      << ". rocksdb get meta cost " << (save_meta_ts - get_meta_ts)
1317
4.68k
                      << " us, rocksdb save meta cost " << (now - save_meta_ts) << " us";
1318
4.68k
            Status rm_st = tablet->data_dir()->move_to_trash(tablet_path);
1319
4.68k
            if (!rm_st.ok()) {
1320
0
                LOG(WARNING) << "fail to move dir to trash. " << tablet_path;
1321
0
                return false;
1322
0
            }
1323
4.68k
        }
1324
        // remove tablet meta
1325
4.68k
        auto remove_st = TabletMetaManager::remove(tablet->data_dir(), tablet->tablet_id(),
1326
4.68k
                                                   tablet->schema_hash());
1327
4.68k
        if (!remove_st.ok()) {
1328
0
            LOG(WARNING) << "failed to remove meta, tablet_id=" << tablet_meta->tablet_id()
1329
0
                         << ", tablet_uid=" << tablet_meta->tablet_uid() << ", error=" << remove_st;
1330
0
            return false;
1331
0
        }
1332
4.68k
        LOG(INFO) << "successfully move tablet to trash. "
1333
4.68k
                  << "tablet_id=" << tablet->tablet_id()
1334
4.68k
                  << ", schema_hash=" << tablet->schema_hash() << ", tablet_path=" << tablet_path;
1335
4.68k
        return true;
1336
4.68k
    } else {
1337
0
        tablet->clear_cache();
1338
        // if could not find tablet info in meta store, then check if dir existed
1339
0
        const auto& tablet_path = tablet->tablet_path();
1340
0
        bool exists = false;
1341
0
        Status exists_st = io::global_local_filesystem()->exists(tablet_path, &exists);
1342
0
        if (!exists_st) {
1343
0
            return false;
1344
0
        }
1345
0
        if (exists) {
1346
0
            if (check_st.is<META_KEY_NOT_FOUND>()) {
1347
0
                LOG(INFO) << "could not find tablet meta in rocksdb, so just delete it path "
1348
0
                          << "tablet_id=" << tablet->tablet_id()
1349
0
                          << ", schema_hash=" << tablet->schema_hash()
1350
0
                          << ", delete tablet_path=" << tablet_path;
1351
0
                RETURN_IF_ERROR(io::global_local_filesystem()->delete_directory(tablet_path));
1352
0
                RETURN_IF_ERROR(DataDir::delete_tablet_parent_path_if_empty(tablet_path));
1353
0
                return true;
1354
0
            }
1355
0
            LOG(WARNING) << "errors while load meta from store, skip this tablet. "
1356
0
                         << "tablet_id=" << tablet->tablet_id()
1357
0
                         << ", schema_hash=" << tablet->schema_hash();
1358
0
            return false;
1359
0
        } else {
1360
0
            LOG(INFO) << "could not find tablet dir, skip it and remove it from gc-queue. "
1361
0
                      << "tablet_id=" << tablet->tablet_id()
1362
0
                      << ", schema_hash=" << tablet->schema_hash()
1363
0
                      << ", tablet_path=" << tablet_path;
1364
0
            return true;
1365
0
        }
1366
0
    }
1367
4.68k
}
1368
1369
9.78k
Status TabletManager::register_transition_tablet(int64_t tablet_id, std::string reason) {
1370
9.78k
    tablets_shard& shard = _get_tablets_shard(tablet_id);
1371
9.78k
    std::thread::id thread_id = std::this_thread::get_id();
1372
9.78k
    std::lock_guard<std::mutex> lk(shard.lock_for_transition);
1373
9.78k
    if (auto search = shard.tablets_under_transition.find(tablet_id);
1374
9.78k
        search == shard.tablets_under_transition.end()) {
1375
        // not found
1376
9.78k
        shard.tablets_under_transition[tablet_id] = std::make_tuple(reason, thread_id, 1);
1377
9.78k
        LOG(INFO) << "add tablet_id= " << tablet_id << " to map, reason=" << reason
1378
9.78k
                  << ", lock times=1, thread_id_in_map=" << thread_id;
1379
9.78k
        return Status::OK();
1380
9.78k
    } else {
1381
        // found
1382
2
        auto& [r, thread_id_in_map, lock_times] = search->second;
1383
2
        if (thread_id != thread_id_in_map) {
1384
            // other thread, failed
1385
0
            LOG(INFO) << "tablet_id = " << tablet_id << " is doing " << r
1386
0
                      << ", thread_id_in_map=" << thread_id_in_map << " , add reason=" << reason
1387
0
                      << ", thread_id=" << thread_id;
1388
0
            return Status::InternalError<false>("{} failed try later, tablet_id={}", reason,
1389
0
                                                tablet_id);
1390
0
        }
1391
        // add lock times
1392
2
        ++lock_times;
1393
2
        LOG(INFO) << "add tablet_id= " << tablet_id << " to map, reason=" << reason
1394
2
                  << ", lock times=" << lock_times << ", thread_id_in_map=" << thread_id_in_map;
1395
2
        return Status::OK();
1396
2
    }
1397
9.78k
}
1398
1399
9.78k
void TabletManager::unregister_transition_tablet(int64_t tablet_id, std::string reason) {
1400
9.78k
    tablets_shard& shard = _get_tablets_shard(tablet_id);
1401
9.78k
    std::thread::id thread_id = std::this_thread::get_id();
1402
9.78k
    std::lock_guard<std::mutex> lk(shard.lock_for_transition);
1403
9.78k
    if (auto search = shard.tablets_under_transition.find(tablet_id);
1404
9.78k
        search == shard.tablets_under_transition.end()) {
1405
        // impossible, bug
1406
0
        DCHECK(false) << "tablet " << tablet_id
1407
0
                      << " must be found, before unreg must have been reg";
1408
9.78k
    } else {
1409
9.78k
        auto& [r, thread_id_in_map, lock_times] = search->second;
1410
9.78k
        if (thread_id_in_map != thread_id) {
1411
            // impossible, bug
1412
0
            DCHECK(false) << "tablet " << tablet_id << " unreg thread must same reg thread";
1413
0
        }
1414
        // sub lock times
1415
9.78k
        --lock_times;
1416
9.78k
        if (lock_times != 0) {
1417
2
            LOG(INFO) << "erase tablet_id= " << tablet_id << " from map, reason=" << reason
1418
2
                      << ", left=" << lock_times << ", thread_id_in_map=" << thread_id_in_map;
1419
9.78k
        } else {
1420
9.78k
            LOG(INFO) << "erase tablet_id= " << tablet_id << " from map, reason=" << reason
1421
9.78k
                      << ", thread_id_in_map=" << thread_id_in_map;
1422
9.78k
            shard.tablets_under_transition.erase(tablet_id);
1423
9.78k
        }
1424
9.78k
    }
1425
9.78k
}
1426
1427
void TabletManager::try_delete_unused_tablet_path(DataDir* data_dir, TTabletId tablet_id,
1428
                                                  SchemaHash schema_hash,
1429
                                                  const string& schema_hash_path,
1430
284
                                                  int16_t shard_id) {
1431
    // acquire the read lock, so that there is no creating tablet or load tablet from meta tasks
1432
    // create tablet and load tablet task should check whether the dir exists
1433
284
    tablets_shard& shard = _get_tablets_shard(tablet_id);
1434
284
    std::shared_lock rdlock(shard.lock);
1435
1436
    // check if meta already exists
1437
284
    TabletMetaSharedPtr tablet_meta(new TabletMeta());
1438
284
    Status check_st = TabletMetaManager::get_meta(data_dir, tablet_id, schema_hash, tablet_meta);
1439
284
    if (check_st.ok() && tablet_meta->shard_id() == shard_id) {
1440
274
        return;
1441
274
    }
1442
1443
284
    LOG(INFO) << "tablet meta not exists, try delete tablet path " << schema_hash_path;
1444
1445
10
    bool succ = register_transition_tablet(tablet_id, "path gc");
1446
10
    if (!succ) {
1447
0
        return;
1448
0
    }
1449
10
    Defer defer {[&]() { unregister_transition_tablet(tablet_id, "path gc"); }};
1450
1451
10
    TabletSharedPtr tablet = _get_tablet_unlocked(tablet_id);
1452
10
    if (tablet != nullptr && tablet->tablet_path() == schema_hash_path) {
1453
0
        LOG(INFO) << "tablet exists, skip delete the path " << schema_hash_path;
1454
0
        return;
1455
0
    }
1456
1457
    // TODO(ygl): may do other checks in the future
1458
10
    bool exists = false;
1459
10
    Status exists_st = io::global_local_filesystem()->exists(schema_hash_path, &exists);
1460
10
    if (exists_st && exists) {
1461
10
        LOG(INFO) << "start to move tablet to trash. tablet_path = " << schema_hash_path;
1462
10
        Status rm_st = data_dir->move_to_trash(schema_hash_path);
1463
10
        if (!rm_st.ok()) {
1464
0
            LOG(WARNING) << "fail to move dir to trash. dir=" << schema_hash_path;
1465
10
        } else {
1466
10
            LOG(INFO) << "move path " << schema_hash_path << " to trash successfully";
1467
10
        }
1468
10
    }
1469
10
}
1470
1471
void TabletManager::update_root_path_info(std::map<string, DataDirInfo>* path_map,
1472
309
                                          size_t* tablet_count) {
1473
309
    DCHECK(tablet_count);
1474
309
    *tablet_count = 0;
1475
3.16M
    auto filter = [path_map, tablet_count](Tablet* t) -> bool {
1476
3.16M
        ++(*tablet_count);
1477
3.16M
        auto iter = path_map->find(t->data_dir()->path());
1478
3.16M
        return iter != path_map->end() && iter->second.is_used;
1479
3.16M
    };
1480
1481
3.16M
    auto handler = [&](const TabletSharedPtr& tablet) {
1482
3.16M
        auto& data_dir_info = (*path_map)[tablet->data_dir()->path()];
1483
3.16M
        data_dir_info.local_used_capacity += tablet->tablet_local_size();
1484
3.16M
        data_dir_info.remote_used_capacity += tablet->tablet_remote_size();
1485
3.16M
    };
1486
1487
309
    for_each_tablet(handler, filter);
1488
309
}
1489
1490
void TabletManager::get_partition_related_tablets(int64_t partition_id,
1491
5.04k
                                                  std::set<TabletInfo>* tablet_infos) {
1492
5.04k
    std::shared_lock rdlock(_partitions_lock);
1493
5.04k
    auto it = _partitions.find(partition_id);
1494
5.04k
    if (it != _partitions.end()) {
1495
5.04k
        *tablet_infos = it->second.tablets;
1496
5.04k
    }
1497
5.04k
}
1498
1499
127
void TabletManager::get_partitions_visible_version(std::map<int64_t, int64_t>* partitions_version) {
1500
127
    std::shared_lock rdlock(_partitions_lock);
1501
154k
    for (const auto& [partition_id, partition] : _partitions) {
1502
154k
        partitions_version->insert(
1503
154k
                {partition_id, partition.visible_version->version.load(std::memory_order_relaxed)});
1504
154k
    }
1505
127
}
1506
1507
void TabletManager::update_partitions_visible_version(
1508
2.51k
        const std::map<int64_t, int64_t>& partitions_version) {
1509
2.51k
    std::shared_lock rdlock(_partitions_lock);
1510
35.5k
    for (auto [partition_id, version] : partitions_version) {
1511
35.5k
        auto it = _partitions.find(partition_id);
1512
35.5k
        if (it != _partitions.end()) {
1513
35.5k
            it->second.visible_version->update_version_monoto(version);
1514
35.5k
        }
1515
35.5k
    }
1516
2.51k
}
1517
1518
20
void TabletManager::do_tablet_meta_checkpoint(DataDir* data_dir) {
1519
540k
    auto filter = [data_dir](Tablet* tablet) -> bool {
1520
540k
        return tablet->tablet_state() == TABLET_RUNNING &&
1521
540k
               tablet->data_dir()->path_hash() == data_dir->path_hash() && tablet->is_used() &&
1522
540k
               tablet->init_succeeded();
1523
540k
    };
1524
1525
20
    std::vector<TabletSharedPtr> related_tablets = get_all_tablet(filter);
1526
20
    int counter = 0;
1527
20
    MonotonicStopWatch watch;
1528
20
    watch.start();
1529
288k
    for (TabletSharedPtr tablet : related_tablets) {
1530
288k
        if (tablet->do_tablet_meta_checkpoint()) {
1531
6.23k
            ++counter;
1532
6.23k
        }
1533
288k
    }
1534
20
    int64_t cost = watch.elapsed_time() / 1000 / 1000;
1535
20
    LOG(INFO) << "finish to do meta checkpoint on dir: " << data_dir->path()
1536
20
              << ", number: " << counter << ", cost(ms): " << cost;
1537
20
}
1538
1539
Status TabletManager::_create_tablet_meta_unlocked(const TCreateTabletReq& request, DataDir* store,
1540
                                                   const bool is_schema_change,
1541
                                                   const Tablet* base_tablet,
1542
6.98k
                                                   TabletMetaSharedPtr* tablet_meta) {
1543
6.98k
    uint32_t next_unique_id = 0;
1544
6.98k
    std::unordered_map<uint32_t, uint32_t> col_idx_to_unique_id;
1545
6.98k
    if (!is_schema_change) {
1546
50.1k
        for (uint32_t col_idx = 0; col_idx < request.tablet_schema.columns.size(); ++col_idx) {
1547
43.1k
            col_idx_to_unique_id[col_idx] = col_idx;
1548
43.1k
        }
1549
6.98k
        next_unique_id = cast_set<int32_t>(request.tablet_schema.columns.size());
1550
6.98k
    } else {
1551
2
        next_unique_id = cast_set<int32_t>(base_tablet->next_unique_id());
1552
2
        auto& new_columns = request.tablet_schema.columns;
1553
2
        for (uint32_t new_col_idx = 0; new_col_idx < new_columns.size(); ++new_col_idx) {
1554
0
            const TColumn& column = new_columns[new_col_idx];
1555
            // For schema change, compare old_tablet and new_tablet:
1556
            // 1. if column exist in both new_tablet and old_tablet, choose the column's
1557
            //    unique_id in old_tablet to be the column's ordinal number in new_tablet
1558
            // 2. if column exists only in new_tablet, assign next_unique_id of old_tablet
1559
            //    to the new column
1560
0
            int32_t old_col_idx = base_tablet->tablet_schema()->field_index(column.column_name);
1561
0
            if (old_col_idx != -1) {
1562
0
                uint32_t old_unique_id =
1563
0
                        base_tablet->tablet_schema()->column(old_col_idx).unique_id();
1564
0
                col_idx_to_unique_id[new_col_idx] = old_unique_id;
1565
0
            } else {
1566
                // Not exist in old tablet, it is a new added column
1567
0
                col_idx_to_unique_id[new_col_idx] = next_unique_id++;
1568
0
            }
1569
0
        }
1570
2
    }
1571
6.98k
    VLOG_NOTICE << "creating tablet meta. next_unique_id=" << next_unique_id;
1572
1573
    // We generate a new tablet_uid for this new tablet.
1574
6.98k
    uint64_t shard_id = store->get_shard();
1575
6.98k
    *tablet_meta = TabletMeta::create(request, TabletUid::gen_uid(), shard_id, next_unique_id,
1576
6.98k
                                      col_idx_to_unique_id);
1577
6.98k
    if (request.__isset.storage_format) {
1578
6.71k
        if (request.storage_format == TStorageFormat::DEFAULT) {
1579
0
            (*tablet_meta)->set_preferred_rowset_type(_engine.default_rowset_type());
1580
6.71k
        } else if (request.storage_format == TStorageFormat::V1) {
1581
0
            (*tablet_meta)->set_preferred_rowset_type(ALPHA_ROWSET);
1582
6.71k
        } else if (request.storage_format == TStorageFormat::V2 ||
1583
6.72k
                   request.storage_format == TStorageFormat::V3) {
1584
6.72k
            (*tablet_meta)->set_preferred_rowset_type(BETA_ROWSET);
1585
18.4E
        } else {
1586
18.4E
            return Status::Error<CE_CMD_PARAMS_ERROR>("invalid TStorageFormat: {}",
1587
18.4E
                                                      request.storage_format);
1588
18.4E
        }
1589
6.71k
    }
1590
6.99k
    return Status::OK();
1591
6.98k
}
1592
1593
1.38M
TabletSharedPtr TabletManager::_get_tablet_unlocked(TTabletId tablet_id) {
1594
1.38M
    VLOG_NOTICE << "begin to get tablet. tablet_id=" << tablet_id;
1595
1.38M
    tablet_map_t& tablet_map = _get_tablet_map(tablet_id);
1596
1.38M
    const auto& iter = tablet_map.find(tablet_id);
1597
1.38M
    if (iter != tablet_map.end()) {
1598
1.37M
        return iter->second;
1599
1.37M
    }
1600
16.2k
    return nullptr;
1601
1.38M
}
1602
1603
285k
void TabletManager::_add_tablet_to_partition(const TabletSharedPtr& tablet) {
1604
285k
    std::lock_guard<std::shared_mutex> wrlock(_partitions_lock);
1605
285k
    auto& partition = _partitions[tablet->partition_id()];
1606
285k
    partition.tablets.insert(tablet->get_tablet_info());
1607
285k
    tablet->set_visible_version(
1608
285k
            std::static_pointer_cast<const VersionWithTime>(partition.visible_version));
1609
285k
}
1610
1611
5.08k
void TabletManager::_remove_tablet_from_partition(const TabletSharedPtr& tablet) {
1612
5.08k
    tablet->set_visible_version(nullptr);
1613
5.08k
    std::lock_guard<std::shared_mutex> wrlock(_partitions_lock);
1614
5.08k
    auto it = _partitions.find(tablet->partition_id());
1615
5.08k
    if (it == _partitions.end()) {
1616
0
        return;
1617
0
    }
1618
1619
5.08k
    auto& tablets = it->second.tablets;
1620
5.08k
    tablets.erase(tablet->get_tablet_info());
1621
5.08k
    if (tablets.empty()) {
1622
1.11k
        _partitions.erase(it);
1623
1.11k
    }
1624
5.08k
}
1625
1626
void TabletManager::obtain_specific_quantity_tablets(vector<TabletInfo>& tablets_info,
1627
0
                                                     int64_t num) {
1628
0
    for (const auto& tablets_shard : _tablets_shards) {
1629
0
        std::shared_lock rdlock(tablets_shard.lock);
1630
0
        for (const auto& item : tablets_shard.tablet_map) {
1631
0
            TabletSharedPtr tablet = item.second;
1632
0
            if (tablets_info.size() >= num) {
1633
0
                return;
1634
0
            }
1635
0
            if (tablet == nullptr) {
1636
0
                continue;
1637
0
            }
1638
0
            tablets_info.push_back(tablet->get_tablet_info());
1639
0
        }
1640
0
    }
1641
0
}
1642
1643
1.66M
std::shared_mutex& TabletManager::_get_tablets_shard_lock(TTabletId tabletId) {
1644
1.66M
    return _get_tablets_shard(tabletId).lock;
1645
1.66M
}
1646
1647
1.96M
TabletManager::tablet_map_t& TabletManager::_get_tablet_map(TTabletId tabletId) {
1648
1.96M
    return _get_tablets_shard(tabletId).tablet_map;
1649
1.96M
}
1650
1651
3.64M
TabletManager::tablets_shard& TabletManager::_get_tablets_shard(TTabletId tabletId) {
1652
3.64M
    return _tablets_shards[tabletId & _tablets_shards_mask];
1653
3.64M
}
1654
1655
void TabletManager::get_tablets_distribution_on_different_disks(
1656
        std::map<int64_t, std::map<DataDir*, int64_t>>& tablets_num_on_disk,
1657
0
        std::map<int64_t, std::map<DataDir*, std::vector<TabletSize>>>& tablets_info_on_disk) {
1658
0
    std::vector<DataDir*> data_dirs = _engine.get_stores();
1659
0
    std::map<int64_t, Partition> partitions;
1660
0
    {
1661
        // When drop tablet, '_partitions_lock' is locked in 'tablet_shard_lock'.
1662
        // To avoid locking 'tablet_shard_lock' in '_partitions_lock', we lock and
1663
        // copy _partitions here.
1664
0
        std::shared_lock rdlock(_partitions_lock);
1665
0
        partitions = _partitions;
1666
0
    }
1667
1668
0
    for (const auto& [partition_id, partition] : partitions) {
1669
0
        std::map<DataDir*, int64_t> tablets_num;
1670
0
        std::map<DataDir*, std::vector<TabletSize>> tablets_info;
1671
0
        for (auto* data_dir : data_dirs) {
1672
0
            tablets_num[data_dir] = 0;
1673
0
        }
1674
1675
0
        for (const auto& tablet_info : partition.tablets) {
1676
            // get_tablet() will hold 'tablet_shard_lock'
1677
0
            TabletSharedPtr tablet = get_tablet(tablet_info.tablet_id);
1678
0
            if (tablet == nullptr) {
1679
0
                continue;
1680
0
            }
1681
0
            DataDir* data_dir = tablet->data_dir();
1682
0
            size_t tablet_footprint = tablet->tablet_footprint();
1683
0
            tablets_num[data_dir]++;
1684
0
            TabletSize tablet_size(tablet_info.tablet_id, tablet_footprint);
1685
0
            tablets_info[data_dir].push_back(tablet_size);
1686
0
        }
1687
0
        tablets_num_on_disk[partition_id] = tablets_num;
1688
0
        tablets_info_on_disk[partition_id] = tablets_info;
1689
0
    }
1690
0
}
1691
1692
struct SortCtx {
1693
    SortCtx(TabletSharedPtr tablet, RowsetSharedPtr rowset, int64_t cooldown_timestamp,
1694
            int64_t file_size)
1695
0
            : tablet(tablet), cooldown_timestamp(cooldown_timestamp), file_size(file_size) {}
1696
    TabletSharedPtr tablet;
1697
    RowsetSharedPtr rowset;
1698
    // to ensure the tablet with -1 would always be greater than other
1699
    uint64_t cooldown_timestamp;
1700
    int64_t file_size;
1701
0
    bool operator<(const SortCtx& other) const {
1702
0
        if (this->cooldown_timestamp == other.cooldown_timestamp) {
1703
0
            return this->file_size > other.file_size;
1704
0
        }
1705
0
        return this->cooldown_timestamp < other.cooldown_timestamp;
1706
0
    }
1707
};
1708
1709
void TabletManager::get_cooldown_tablets(std::vector<TabletSharedPtr>* tablets,
1710
                                         std::vector<RowsetSharedPtr>* rowsets,
1711
400
                                         std::function<bool(const TabletSharedPtr&)> skip_tablet) {
1712
400
    std::vector<SortCtx> sort_ctx_vec;
1713
400
    std::vector<std::weak_ptr<Tablet>> candidates;
1714
3.80M
    for_each_tablet([&](const TabletSharedPtr& tablet) { candidates.emplace_back(tablet); },
1715
400
                    filter_all_tablets);
1716
3.80M
    auto get_cooldown_tablet = [&sort_ctx_vec, &skip_tablet](std::weak_ptr<Tablet>& t) {
1717
3.80M
        const TabletSharedPtr& tablet = t.lock();
1718
3.80M
        RowsetSharedPtr rowset = nullptr;
1719
3.80M
        if (UNLIKELY(nullptr == tablet)) {
1720
0
            return;
1721
0
        }
1722
3.80M
        int64_t cooldown_timestamp = -1;
1723
3.80M
        size_t file_size = -1;
1724
3.80M
        if (!skip_tablet(tablet) &&
1725
3.80M
            (rowset = tablet->need_cooldown(&cooldown_timestamp, &file_size))) {
1726
0
            sort_ctx_vec.emplace_back(tablet, rowset, cooldown_timestamp, file_size);
1727
0
        }
1728
3.80M
    };
1729
400
    std::for_each(candidates.begin(), candidates.end(), get_cooldown_tablet);
1730
1731
400
    std::sort(sort_ctx_vec.begin(), sort_ctx_vec.end());
1732
1733
400
    for (SortCtx& ctx : sort_ctx_vec) {
1734
0
        VLOG_DEBUG << "get cooldown tablet: " << ctx.tablet->tablet_id();
1735
0
        tablets->push_back(std::move(ctx.tablet));
1736
0
        rowsets->push_back(std::move(ctx.rowset));
1737
0
    }
1738
400
}
1739
1740
0
void TabletManager::get_all_tablets_storage_format(TCheckStorageFormatResult* result) {
1741
0
    DCHECK(result != nullptr);
1742
0
    auto handler = [result](const TabletSharedPtr& tablet) {
1743
0
        if (tablet->all_beta()) {
1744
0
            result->v2_tablets.push_back(tablet->tablet_id());
1745
0
        } else {
1746
0
            result->v1_tablets.push_back(tablet->tablet_id());
1747
0
        }
1748
0
    };
1749
1750
0
    for_each_tablet(handler, filter_all_tablets);
1751
0
    result->__isset.v1_tablets = true;
1752
0
    result->__isset.v2_tablets = true;
1753
0
}
1754
1755
0
std::set<int64_t> TabletManager::check_all_tablet_segment(bool repair) {
1756
0
    std::set<int64_t> bad_tablets;
1757
0
    std::map<int64_t, std::vector<int64_t>> repair_shard_bad_tablets;
1758
0
    auto handler = [&](const TabletSharedPtr& tablet) {
1759
0
        if (!tablet->check_all_rowset_segment()) {
1760
0
            int64_t tablet_id = tablet->tablet_id();
1761
0
            bad_tablets.insert(tablet_id);
1762
0
            if (repair) {
1763
0
                repair_shard_bad_tablets[tablet_id & _tablets_shards_mask].push_back(tablet_id);
1764
0
            }
1765
0
        }
1766
0
    };
1767
0
    for_each_tablet(handler, filter_all_tablets);
1768
1769
0
    for (const auto& [shard_index, shard_tablets] : repair_shard_bad_tablets) {
1770
0
        auto& tablets_shard = _tablets_shards[shard_index];
1771
0
        auto& tablet_map = tablets_shard.tablet_map;
1772
0
        std::lock_guard<std::shared_mutex> wrlock(tablets_shard.lock);
1773
0
        for (auto tablet_id : shard_tablets) {
1774
0
            auto it = tablet_map.find(tablet_id);
1775
0
            if (it == tablet_map.end()) {
1776
0
                bad_tablets.erase(tablet_id);
1777
0
                LOG(WARNING) << "Bad tablet has be removed. tablet_id=" << tablet_id;
1778
0
            } else {
1779
0
                const auto& tablet = it->second;
1780
0
                static_cast<void>(tablet->set_tablet_state(TABLET_SHUTDOWN));
1781
0
                tablet->save_meta();
1782
0
                {
1783
0
                    std::lock_guard<std::shared_mutex> shutdown_tablets_wrlock(
1784
0
                            _shutdown_tablets_lock);
1785
0
                    _shutdown_tablets.push_back(tablet);
1786
0
                }
1787
0
                LOG(WARNING) << "There are some segments lost, set tablet to shutdown state."
1788
0
                             << "tablet_id=" << tablet->tablet_id()
1789
0
                             << ", tablet_path=" << tablet->tablet_path();
1790
0
            }
1791
0
        }
1792
0
    }
1793
1794
0
    return bad_tablets;
1795
0
}
1796
1797
bool TabletManager::update_tablet_partition_id(::doris::TPartitionId partition_id,
1798
0
                                               ::doris::TTabletId tablet_id) {
1799
0
    std::shared_lock rdlock(_get_tablets_shard_lock(tablet_id));
1800
0
    TabletSharedPtr tablet = _get_tablet_unlocked(tablet_id);
1801
0
    if (tablet == nullptr) {
1802
0
        LOG(WARNING) << "get tablet err partition_id: " << partition_id
1803
0
                     << " tablet_id:" << tablet_id;
1804
0
        return false;
1805
0
    }
1806
0
    _remove_tablet_from_partition(tablet);
1807
0
    auto st = tablet->tablet_meta()->set_partition_id(partition_id);
1808
0
    if (!st.ok()) {
1809
0
        LOG(WARNING) << "set partition id err partition_id: " << partition_id
1810
0
                     << " tablet_id:" << tablet_id;
1811
0
        return false;
1812
0
    }
1813
0
    _add_tablet_to_partition(tablet);
1814
0
    return true;
1815
0
}
1816
1817
void TabletManager::get_topn_tablet_delete_bitmap_score(
1818
23
        uint64_t* max_delete_bitmap_score, uint64_t* max_base_rowset_delete_bitmap_score) {
1819
23
    int64_t max_delete_bitmap_score_tablet_id = 0;
1820
23
    int64_t max_base_rowset_delete_bitmap_score_tablet_id = 0;
1821
23
    OlapStopWatch watch;
1822
23
    uint64_t total_delete_map_count = 0;
1823
23
    int n = config::check_tablet_delete_bitmap_score_top_n;
1824
23
    std::vector<std::pair<std::shared_ptr<Tablet>, int64_t>> buf;
1825
23
    buf.reserve(n + 1);
1826
24.4k
    auto handler = [&](const TabletSharedPtr& tablet) {
1827
24.4k
        uint64_t delete_bitmap_count =
1828
24.4k
                tablet->tablet_meta()->delete_bitmap().get_delete_bitmap_count();
1829
24.4k
        total_delete_map_count += delete_bitmap_count;
1830
24.4k
        if (delete_bitmap_count > *max_delete_bitmap_score) {
1831
65
            max_delete_bitmap_score_tablet_id = tablet->tablet_id();
1832
65
            *max_delete_bitmap_score = delete_bitmap_count;
1833
65
        }
1834
24.4k
        buf.emplace_back(std::move(tablet), delete_bitmap_count);
1835
487k
        std::sort(buf.begin(), buf.end(), [](auto& a, auto& b) { return a.second > b.second; });
1836
24.4k
        if (buf.size() > n) {
1837
24.2k
            buf.pop_back();
1838
24.2k
        }
1839
24.4k
    };
1840
23
    for_each_tablet(handler, filter_all_tablets);
1841
230
    for (auto& [t, _] : buf) {
1842
230
        t->get_base_rowset_delete_bitmap_count(max_base_rowset_delete_bitmap_score,
1843
230
                                               &max_base_rowset_delete_bitmap_score_tablet_id);
1844
230
    }
1845
23
    std::stringstream ss;
1846
230
    for (auto& i : buf) {
1847
230
        ss << i.first->tablet_id() << ": " << i.second << ", ";
1848
230
    }
1849
    LOG(INFO) << "get_topn_tablet_delete_bitmap_score, n=" << n
1850
23
              << ", tablet size=" << _tablets_shards.size()
1851
23
              << ", total_delete_map_count=" << total_delete_map_count
1852
23
              << ", cost(us)=" << watch.get_elapse_time_us()
1853
23
              << ", max_delete_bitmap_score=" << *max_delete_bitmap_score
1854
23
              << ", max_delete_bitmap_score_tablet_id=" << max_delete_bitmap_score_tablet_id
1855
23
              << ", max_base_rowset_delete_bitmap_score=" << *max_base_rowset_delete_bitmap_score
1856
23
              << ", max_base_rowset_delete_bitmap_score_tablet_id="
1857
23
              << max_base_rowset_delete_bitmap_score_tablet_id << ", tablets=[" << ss.str() << "]";
1858
23
}
1859
1860
} // end namespace doris