Coverage Report

Created: 2026-05-09 15:32

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