Coverage Report

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