Coverage Report

Created: 2026-07-28 01:20

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