Coverage Report

Created: 2025-04-29 17:56

/root/doris/be/src/olap/tablet_meta.cpp
Line
Count
Source (jump to first uncovered line)
1
// Licensed to the Apache Software Foundation (ASF) under one
2
// or more contributor license agreements.  See the NOTICE file
3
// distributed with this work for additional information
4
// regarding copyright ownership.  The ASF licenses this file
5
// to you under the Apache License, Version 2.0 (the
6
// "License"); you may not use this file except in compliance
7
// with the License.  You may obtain a copy of the License at
8
//
9
//   http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied.  See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
18
#include "olap/tablet_meta.h"
19
20
#include <gen_cpp/Descriptors_types.h>
21
#include <gen_cpp/Types_types.h>
22
#include <gen_cpp/olap_common.pb.h>
23
#include <gen_cpp/olap_file.pb.h>
24
#include <gen_cpp/segment_v2.pb.h>
25
#include <gen_cpp/types.pb.h>
26
#include <json2pb/pb_to_json.h>
27
#include <time.h>
28
29
#include <cstdint>
30
#include <memory>
31
#include <set>
32
#include <utility>
33
34
#include "common/config.h"
35
#include "gutil/integral_types.h"
36
#include "io/fs/file_writer.h"
37
#include "olap/data_dir.h"
38
#include "olap/file_header.h"
39
#include "olap/olap_common.h"
40
#include "olap/olap_define.h"
41
#include "olap/rowset/rowset.h"
42
#include "olap/rowset/rowset_meta_manager.h"
43
#include "olap/tablet_fwd.h"
44
#include "olap/tablet_meta_manager.h"
45
#include "olap/tablet_schema_cache.h"
46
#include "olap/utils.h"
47
#include "util/debug_points.h"
48
#include "util/mem_info.h"
49
#include "util/parse_util.h"
50
#include "util/string_util.h"
51
#include "util/time.h"
52
#include "util/uid_util.h"
53
54
using std::string;
55
using std::unordered_map;
56
using std::vector;
57
58
namespace doris {
59
using namespace ErrorCode;
60
61
TabletMetaSharedPtr TabletMeta::create(
62
        const TCreateTabletReq& request, const TabletUid& tablet_uid, uint64_t shard_id,
63
        uint32_t next_unique_id,
64
295
        const unordered_map<uint32_t, uint32_t>& col_ordinal_to_unique_id) {
65
295
    std::optional<TBinlogConfig> binlog_config;
66
295
    if (request.__isset.binlog_config) {
67
0
        binlog_config = request.binlog_config;
68
0
    }
69
295
    return std::make_shared<TabletMeta>(
70
295
            request.table_id, request.partition_id, request.tablet_id, request.replica_id,
71
295
            request.tablet_schema.schema_hash, shard_id, request.tablet_schema, next_unique_id,
72
295
            col_ordinal_to_unique_id, tablet_uid,
73
295
            request.__isset.tablet_type ? request.tablet_type : TTabletType::TABLET_TYPE_DISK,
74
295
            request.compression_type, request.storage_policy_id,
75
295
            request.__isset.enable_unique_key_merge_on_write
76
295
                    ? request.enable_unique_key_merge_on_write
77
295
                    : false,
78
295
            std::move(binlog_config), request.compaction_policy,
79
295
            request.time_series_compaction_goal_size_mbytes,
80
295
            request.time_series_compaction_file_count_threshold,
81
295
            request.time_series_compaction_time_threshold_seconds,
82
295
            request.time_series_compaction_empty_rowsets_threshold,
83
295
            request.inverted_index_storage_format, request.time_series_compaction_level_threshold);
84
295
}
85
86
973
TabletMeta::~TabletMeta() {
87
973
    if (_handle) {
88
922
        TabletSchemaCache::instance()->release(_handle);
89
922
    }
90
973
}
91
92
TabletMeta::TabletMeta()
93
        : _tablet_uid(0, 0),
94
          _schema(new TabletSchema),
95
535
          _delete_bitmap(new DeleteBitmap(_tablet_id)) {}
96
97
TabletMeta::TabletMeta(int64_t table_id, int64_t partition_id, int64_t tablet_id,
98
                       int64_t replica_id, int32_t schema_hash, uint64_t shard_id,
99
                       const TTabletSchema& tablet_schema, uint32_t next_unique_id,
100
                       const std::unordered_map<uint32_t, uint32_t>& col_ordinal_to_unique_id,
101
                       TabletUid tablet_uid, TTabletType::type tabletType,
102
                       TCompressionType::type compression_type, int64_t storage_policy_id,
103
                       bool enable_unique_key_merge_on_write,
104
                       std::optional<TBinlogConfig> binlog_config, std::string compaction_policy,
105
                       int64_t time_series_compaction_goal_size_mbytes,
106
                       int64_t time_series_compaction_file_count_threshold,
107
                       int64_t time_series_compaction_time_threshold_seconds,
108
                       int64_t time_series_compaction_empty_rowsets_threshold,
109
                       TInvertedIndexStorageFormat::type inverted_index_storage_format,
110
                       int64_t time_series_compaction_level_threshold)
111
        : _tablet_uid(0, 0),
112
          _schema(new TabletSchema),
113
438
          _delete_bitmap(new DeleteBitmap(tablet_id)) {
114
438
    TabletMetaPB tablet_meta_pb;
115
438
    tablet_meta_pb.set_table_id(table_id);
116
438
    tablet_meta_pb.set_partition_id(partition_id);
117
438
    tablet_meta_pb.set_tablet_id(tablet_id);
118
438
    tablet_meta_pb.set_replica_id(replica_id);
119
438
    tablet_meta_pb.set_schema_hash(schema_hash);
120
438
    tablet_meta_pb.set_shard_id(shard_id);
121
    // Persist the creation time, but it is not used
122
438
    tablet_meta_pb.set_creation_time(time(nullptr));
123
438
    tablet_meta_pb.set_cumulative_layer_point(-1);
124
438
    tablet_meta_pb.set_tablet_state(PB_RUNNING);
125
438
    *(tablet_meta_pb.mutable_tablet_uid()) = tablet_uid.to_proto();
126
438
    tablet_meta_pb.set_tablet_type(tabletType == TTabletType::TABLET_TYPE_DISK
127
438
                                           ? TabletTypePB::TABLET_TYPE_DISK
128
438
                                           : TabletTypePB::TABLET_TYPE_MEMORY);
129
438
    tablet_meta_pb.set_enable_unique_key_merge_on_write(enable_unique_key_merge_on_write);
130
438
    tablet_meta_pb.set_storage_policy_id(storage_policy_id);
131
438
    tablet_meta_pb.set_compaction_policy(compaction_policy);
132
438
    tablet_meta_pb.set_time_series_compaction_goal_size_mbytes(
133
438
            time_series_compaction_goal_size_mbytes);
134
438
    tablet_meta_pb.set_time_series_compaction_file_count_threshold(
135
438
            time_series_compaction_file_count_threshold);
136
438
    tablet_meta_pb.set_time_series_compaction_time_threshold_seconds(
137
438
            time_series_compaction_time_threshold_seconds);
138
438
    tablet_meta_pb.set_time_series_compaction_empty_rowsets_threshold(
139
438
            time_series_compaction_empty_rowsets_threshold);
140
438
    tablet_meta_pb.set_time_series_compaction_level_threshold(
141
438
            time_series_compaction_level_threshold);
142
438
    TabletSchemaPB* schema = tablet_meta_pb.mutable_schema();
143
438
    schema->set_num_short_key_columns(tablet_schema.short_key_column_count);
144
438
    schema->set_num_rows_per_row_block(config::default_num_rows_per_column_file_block);
145
438
    schema->set_sequence_col_idx(tablet_schema.sequence_col_idx);
146
438
    switch (tablet_schema.keys_type) {
147
30
    case TKeysType::DUP_KEYS:
148
30
        schema->set_keys_type(KeysType::DUP_KEYS);
149
30
        break;
150
299
    case TKeysType::UNIQUE_KEYS:
151
299
        schema->set_keys_type(KeysType::UNIQUE_KEYS);
152
299
        break;
153
61
    case TKeysType::AGG_KEYS:
154
61
        schema->set_keys_type(KeysType::AGG_KEYS);
155
61
        break;
156
48
    default:
157
48
        LOG(WARNING) << "unknown tablet keys type";
158
48
        break;
159
438
    }
160
    // compress_kind used to compress segment files
161
438
    schema->set_compress_kind(COMPRESS_LZ4);
162
163
    // compression_type used to compress segment page
164
438
    switch (compression_type) {
165
0
    case TCompressionType::NO_COMPRESSION:
166
0
        schema->set_compression_type(segment_v2::NO_COMPRESSION);
167
0
        break;
168
0
    case TCompressionType::SNAPPY:
169
0
        schema->set_compression_type(segment_v2::SNAPPY);
170
0
        break;
171
0
    case TCompressionType::LZ4:
172
0
        schema->set_compression_type(segment_v2::LZ4);
173
0
        break;
174
438
    case TCompressionType::LZ4F:
175
438
        schema->set_compression_type(segment_v2::LZ4F);
176
438
        break;
177
0
    case TCompressionType::ZLIB:
178
0
        schema->set_compression_type(segment_v2::ZLIB);
179
0
        break;
180
0
    case TCompressionType::ZSTD:
181
0
        schema->set_compression_type(segment_v2::ZSTD);
182
0
        break;
183
0
    default:
184
0
        schema->set_compression_type(segment_v2::LZ4F);
185
0
        break;
186
438
    }
187
188
438
    switch (inverted_index_storage_format) {
189
438
    case TInvertedIndexStorageFormat::V1:
190
438
        schema->set_inverted_index_storage_format(InvertedIndexStorageFormatPB::V1);
191
438
        break;
192
0
    case TInvertedIndexStorageFormat::V2:
193
0
        schema->set_inverted_index_storage_format(InvertedIndexStorageFormatPB::V2);
194
0
        break;
195
0
    default:
196
0
        schema->set_inverted_index_storage_format(InvertedIndexStorageFormatPB::V1);
197
0
        break;
198
438
    }
199
200
438
    switch (tablet_schema.sort_type) {
201
0
    case TSortType::type::ZORDER:
202
0
        schema->set_sort_type(SortType::ZORDER);
203
0
        break;
204
438
    default:
205
438
        schema->set_sort_type(SortType::LEXICAL);
206
438
    }
207
438
    schema->set_sort_col_num(tablet_schema.sort_col_num);
208
438
    for (const auto& i : tablet_schema.cluster_key_idxes) {
209
0
        schema->add_cluster_key_idxes(i);
210
0
    }
211
438
    tablet_meta_pb.set_in_restore_mode(false);
212
213
    // set column information
214
438
    uint32_t col_ordinal = 0;
215
438
    bool has_bf_columns = false;
216
2.09k
    for (TColumn tcolumn : tablet_schema.columns) {
217
2.09k
        ColumnPB* column = schema->add_column();
218
2.09k
        uint32_t unique_id = -1;
219
2.09k
        if (tcolumn.col_unique_id >= 0) {
220
0
            unique_id = tcolumn.col_unique_id;
221
2.09k
        } else {
222
2.09k
            unique_id = col_ordinal_to_unique_id.at(col_ordinal);
223
2.09k
        }
224
2.09k
        col_ordinal++;
225
2.09k
        init_column_from_tcolumn(unique_id, tcolumn, column);
226
227
2.09k
        if (column->is_bf_column()) {
228
0
            has_bf_columns = true;
229
0
        }
230
231
2.09k
        if (tablet_schema.__isset.indexes) {
232
0
            for (auto& index : tablet_schema.indexes) {
233
0
                if (index.index_type == TIndexType::type::BITMAP) {
234
0
                    DCHECK_EQ(index.columns.size(), 1);
235
0
                    if (iequal(tcolumn.column_name, index.columns[0])) {
236
0
                        column->set_has_bitmap_index(true);
237
0
                        break;
238
0
                    }
239
0
                } else if (index.index_type == TIndexType::type::BLOOMFILTER ||
240
0
                           index.index_type == TIndexType::type::NGRAM_BF) {
241
0
                    DCHECK_EQ(index.columns.size(), 1);
242
0
                    if (iequal(tcolumn.column_name, index.columns[0])) {
243
0
                        column->set_is_bf_column(true);
244
0
                        break;
245
0
                    }
246
0
                }
247
0
            }
248
0
        }
249
2.09k
    }
250
251
    // copy index meta
252
438
    if (tablet_schema.__isset.indexes) {
253
0
        for (auto& index : tablet_schema.indexes) {
254
0
            TabletIndexPB* index_pb = schema->add_index();
255
0
            index_pb->set_index_id(index.index_id);
256
0
            index_pb->set_index_name(index.index_name);
257
            // init col_unique_id in index at be side, since col_unique_id may be -1 at fe side
258
            // get column unique id by name
259
0
            for (auto column_name : index.columns) {
260
0
                for (auto column : schema->column()) {
261
0
                    if (iequal(column.name(), column_name)) {
262
0
                        index_pb->add_col_unique_id(column.unique_id());
263
0
                    }
264
0
                }
265
0
            }
266
0
            switch (index.index_type) {
267
0
            case TIndexType::BITMAP:
268
0
                index_pb->set_index_type(IndexType::BITMAP);
269
0
                break;
270
0
            case TIndexType::INVERTED:
271
0
                index_pb->set_index_type(IndexType::INVERTED);
272
0
                break;
273
0
            case TIndexType::BLOOMFILTER:
274
0
                index_pb->set_index_type(IndexType::BLOOMFILTER);
275
0
                break;
276
0
            case TIndexType::NGRAM_BF:
277
0
                index_pb->set_index_type(IndexType::NGRAM_BF);
278
0
                break;
279
0
            }
280
281
0
            if (index.__isset.properties) {
282
0
                auto properties = index_pb->mutable_properties();
283
0
                for (auto kv : index.properties) {
284
0
                    (*properties)[kv.first] = kv.second;
285
0
                }
286
0
            }
287
0
        }
288
0
    }
289
290
438
    schema->set_next_column_unique_id(next_unique_id);
291
438
    if (has_bf_columns && tablet_schema.__isset.bloom_filter_fpp) {
292
0
        schema->set_bf_fpp(tablet_schema.bloom_filter_fpp);
293
0
    }
294
295
438
    if (tablet_schema.__isset.is_in_memory) {
296
0
        schema->set_is_in_memory(tablet_schema.is_in_memory);
297
0
    }
298
299
438
    if (tablet_schema.__isset.disable_auto_compaction) {
300
0
        schema->set_disable_auto_compaction(tablet_schema.disable_auto_compaction);
301
0
    }
302
303
438
    if (tablet_schema.__isset.enable_single_replica_compaction) {
304
438
        schema->set_enable_single_replica_compaction(
305
438
                tablet_schema.enable_single_replica_compaction);
306
438
    }
307
308
438
    if (tablet_schema.__isset.delete_sign_idx) {
309
438
        schema->set_delete_sign_idx(tablet_schema.delete_sign_idx);
310
438
    }
311
438
    if (tablet_schema.__isset.store_row_column) {
312
438
        schema->set_store_row_column(tablet_schema.store_row_column);
313
438
    }
314
438
    if (tablet_schema.__isset.row_store_page_size) {
315
438
        schema->set_row_store_page_size(tablet_schema.row_store_page_size);
316
438
    }
317
438
    if (tablet_schema.__isset.skip_write_index_on_load) {
318
438
        schema->set_skip_write_index_on_load(tablet_schema.skip_write_index_on_load);
319
438
    }
320
438
    if (binlog_config.has_value()) {
321
0
        BinlogConfig tmp_binlog_config;
322
0
        tmp_binlog_config = binlog_config.value();
323
0
        tmp_binlog_config.to_pb(tablet_meta_pb.mutable_binlog_config());
324
0
    }
325
326
438
    init_from_pb(tablet_meta_pb);
327
438
}
328
329
TabletMeta::TabletMeta(const TabletMeta& b)
330
        : MetadataAdder(b),
331
          _table_id(b._table_id),
332
          _partition_id(b._partition_id),
333
          _tablet_id(b._tablet_id),
334
          _replica_id(b._replica_id),
335
          _schema_hash(b._schema_hash),
336
          _shard_id(b._shard_id),
337
          _creation_time(b._creation_time),
338
          _cumulative_layer_point(b._cumulative_layer_point),
339
          _tablet_uid(b._tablet_uid),
340
          _tablet_type(b._tablet_type),
341
          _tablet_state(b._tablet_state),
342
          _schema(b._schema),
343
          _rs_metas(b._rs_metas),
344
          _stale_rs_metas(b._stale_rs_metas),
345
          _in_restore_mode(b._in_restore_mode),
346
          _preferred_rowset_type(b._preferred_rowset_type),
347
          _storage_policy_id(b._storage_policy_id),
348
          _cooldown_meta_id(b._cooldown_meta_id),
349
          _enable_unique_key_merge_on_write(b._enable_unique_key_merge_on_write),
350
          _delete_bitmap(b._delete_bitmap),
351
          _binlog_config(b._binlog_config),
352
          _compaction_policy(b._compaction_policy),
353
          _time_series_compaction_goal_size_mbytes(b._time_series_compaction_goal_size_mbytes),
354
          _time_series_compaction_file_count_threshold(
355
                  b._time_series_compaction_file_count_threshold),
356
          _time_series_compaction_time_threshold_seconds(
357
                  b._time_series_compaction_time_threshold_seconds),
358
          _time_series_compaction_empty_rowsets_threshold(
359
                  b._time_series_compaction_empty_rowsets_threshold),
360
0
          _time_series_compaction_level_threshold(b._time_series_compaction_level_threshold) {};
361
362
void TabletMeta::init_column_from_tcolumn(uint32_t unique_id, const TColumn& tcolumn,
363
2.09k
                                          ColumnPB* column) {
364
2.09k
    column->set_unique_id(unique_id);
365
2.09k
    column->set_name(tcolumn.column_name);
366
2.09k
    column->set_has_bitmap_index(tcolumn.has_bitmap_index);
367
2.09k
    column->set_is_auto_increment(tcolumn.is_auto_increment);
368
2.09k
    string data_type;
369
2.09k
    EnumToString(TPrimitiveType, tcolumn.column_type.type, data_type);
370
2.09k
    column->set_type(data_type);
371
372
2.09k
    uint32_t length = TabletColumn::get_field_length_by_type(tcolumn.column_type.type,
373
2.09k
                                                             tcolumn.column_type.len);
374
2.09k
    column->set_length(length);
375
2.09k
    column->set_index_length(length);
376
2.09k
    column->set_precision(tcolumn.column_type.precision);
377
2.09k
    column->set_frac(tcolumn.column_type.scale);
378
379
2.09k
    if (tcolumn.__isset.result_is_nullable) {
380
0
        column->set_result_is_nullable(tcolumn.result_is_nullable);
381
0
    }
382
383
2.09k
    if (tcolumn.column_type.type == TPrimitiveType::VARCHAR ||
384
2.09k
        tcolumn.column_type.type == TPrimitiveType::STRING) {
385
101
        if (!tcolumn.column_type.__isset.index_len) {
386
101
            column->set_index_length(10);
387
101
        } else {
388
0
            column->set_index_length(tcolumn.column_type.index_len);
389
0
        }
390
101
    }
391
2.09k
    if (!tcolumn.is_key) {
392
1.13k
        column->set_is_key(false);
393
1.13k
        if (tcolumn.__isset.aggregation) {
394
0
            column->set_aggregation(tcolumn.aggregation);
395
1.13k
        } else {
396
1.13k
            string aggregation_type;
397
1.13k
            EnumToString(TAggregationType, tcolumn.aggregation_type, aggregation_type);
398
1.13k
            column->set_aggregation(aggregation_type);
399
1.13k
        }
400
1.13k
    } else {
401
967
        column->set_is_key(true);
402
967
        column->set_aggregation("NONE");
403
967
    }
404
2.09k
    column->set_is_nullable(tcolumn.is_allow_null);
405
2.09k
    if (tcolumn.__isset.default_value) {
406
0
        column->set_default_value(tcolumn.default_value);
407
0
    }
408
2.09k
    if (tcolumn.__isset.is_bloom_filter_column) {
409
0
        column->set_is_bf_column(tcolumn.is_bloom_filter_column);
410
0
    }
411
2.09k
    for (size_t i = 0; i < tcolumn.children_column.size(); i++) {
412
0
        ColumnPB* children_column = column->add_children_columns();
413
0
        init_column_from_tcolumn(tcolumn.children_column[i].col_unique_id,
414
0
                                 tcolumn.children_column[i], children_column);
415
0
    }
416
2.09k
}
417
418
5
Status TabletMeta::create_from_file(const string& file_path) {
419
5
    FileHeader<TabletMetaPB> file_header(file_path);
420
    // In file_header.deserialize(), it validates file length, signature, checksum of protobuf.
421
5
    RETURN_IF_ERROR(file_header.deserialize());
422
5
    TabletMetaPB tablet_meta_pb;
423
5
    try {
424
5
        tablet_meta_pb.CopyFrom(file_header.message());
425
5
    } catch (...) {
426
0
        return Status::Error<PARSE_PROTOBUF_ERROR>("fail to copy protocol buffer object. file={}",
427
0
                                                   file_path);
428
0
    }
429
430
5
    init_from_pb(tablet_meta_pb);
431
5
    return Status::OK();
432
5
}
433
434
std::string TabletMeta::construct_header_file_path(const string& schema_hash_path,
435
2
                                                   int64_t tablet_id) {
436
2
    std::stringstream header_name_stream;
437
2
    header_name_stream << schema_hash_path << "/" << tablet_id << ".hdr";
438
2
    return header_name_stream.str();
439
2
}
440
441
0
Status TabletMeta::save_as_json(const string& file_path, DataDir* dir) {
442
0
    std::string json_meta;
443
0
    json2pb::Pb2JsonOptions json_options;
444
0
    json_options.pretty_json = true;
445
0
    json_options.bytes_to_base64 = true;
446
0
    to_json(&json_meta, json_options);
447
    // save to file
448
0
    io::FileWriterPtr file_writer;
449
0
    RETURN_IF_ERROR(dir->fs()->create_file(file_path, &file_writer));
450
0
    RETURN_IF_ERROR(file_writer->append(json_meta));
451
0
    RETURN_IF_ERROR(file_writer->close());
452
0
    return Status::OK();
453
0
}
454
455
227
Status TabletMeta::save(const string& file_path) {
456
227
    TabletMetaPB tablet_meta_pb;
457
227
    to_meta_pb(&tablet_meta_pb);
458
227
    return TabletMeta::save(file_path, tablet_meta_pb);
459
227
}
460
461
229
Status TabletMeta::save(const string& file_path, const TabletMetaPB& tablet_meta_pb) {
462
229
    DCHECK(!file_path.empty());
463
229
    FileHeader<TabletMetaPB> file_header(file_path);
464
229
    try {
465
229
        file_header.mutable_message()->CopyFrom(tablet_meta_pb);
466
229
    } catch (...) {
467
0
        LOG(WARNING) << "fail to copy protocol buffer object. file='" << file_path;
468
0
        return Status::Error<ErrorCode::INTERNAL_ERROR>(
469
0
                "fail to copy protocol buffer object. file={}", file_path);
470
0
    }
471
229
    RETURN_IF_ERROR(file_header.prepare());
472
229
    RETURN_IF_ERROR(file_header.serialize());
473
229
    return Status::OK();
474
229
}
475
476
554
Status TabletMeta::save_meta(DataDir* data_dir) {
477
554
    std::lock_guard<std::shared_mutex> wrlock(_meta_lock);
478
554
    return _save_meta(data_dir);
479
554
}
480
481
554
Status TabletMeta::_save_meta(DataDir* data_dir) {
482
    // check if tablet uid is valid
483
554
    if (_tablet_uid.hi == 0 && _tablet_uid.lo == 0) {
484
0
        LOG(FATAL) << "tablet_uid is invalid"
485
0
                   << " tablet=" << tablet_id() << " _tablet_uid=" << _tablet_uid.to_string();
486
0
    }
487
554
    string meta_binary;
488
489
554
    auto t1 = MonotonicMicros();
490
554
    serialize(&meta_binary);
491
554
    auto t2 = MonotonicMicros();
492
554
    Status status = TabletMetaManager::save(data_dir, tablet_id(), schema_hash(), meta_binary);
493
554
    if (!status.ok()) {
494
0
        LOG(FATAL) << "fail to save tablet_meta. status=" << status << ", tablet_id=" << tablet_id()
495
0
                   << ", schema_hash=" << schema_hash();
496
0
    }
497
554
    auto t3 = MonotonicMicros();
498
554
    auto cost = t3 - t1;
499
554
    if (cost > 1 * 1000 * 1000) {
500
0
        LOG(INFO) << "save tablet(" << tablet_id() << ") meta too slow. serialize cost " << t2 - t1
501
0
                  << "(us), serialized binary size: " << meta_binary.length()
502
0
                  << "(bytes), write rocksdb cost " << t3 - t2 << "(us)";
503
0
    }
504
554
    return status;
505
554
}
506
507
557
void TabletMeta::serialize(string* meta_binary) {
508
557
    TabletMetaPB tablet_meta_pb;
509
557
    to_meta_pb(&tablet_meta_pb);
510
557
    if (tablet_meta_pb.partition_id() <= 0) {
511
461
        LOG(WARNING) << "invalid partition id " << tablet_meta_pb.partition_id() << " tablet "
512
461
                     << tablet_meta_pb.tablet_id();
513
461
    }
514
557
    DBUG_EXECUTE_IF("TabletMeta::serialize::zero_partition_id", {
515
557
        long partition_id = tablet_meta_pb.partition_id();
516
557
        tablet_meta_pb.set_partition_id(0);
517
557
        LOG(WARNING) << "set debug point TabletMeta::serialize::zero_partition_id old="
518
557
                     << partition_id << " new=" << tablet_meta_pb.DebugString();
519
557
    });
520
557
    bool serialize_success = tablet_meta_pb.SerializeToString(meta_binary);
521
557
    if (!_rs_metas.empty() || !_stale_rs_metas.empty()) {
522
557
        _avg_rs_meta_serialize_size =
523
557
                meta_binary->length() / (_rs_metas.size() + _stale_rs_metas.size());
524
557
        if (meta_binary->length() > config::tablet_meta_serialize_size_limit ||
525
557
            !serialize_success) {
526
0
            int64_t origin_meta_size = meta_binary->length();
527
0
            int64_t stale_rowsets_num = tablet_meta_pb.stale_rs_metas().size();
528
0
            tablet_meta_pb.clear_stale_rs_metas();
529
0
            meta_binary->clear();
530
0
            serialize_success = tablet_meta_pb.SerializeToString(meta_binary);
531
0
            LOG(WARNING) << "tablet meta serialization size exceeds limit: "
532
0
                         << config::tablet_meta_serialize_size_limit
533
0
                         << " clean up stale rowsets, tablet id: " << tablet_id()
534
0
                         << " stale rowset num: " << stale_rowsets_num
535
0
                         << " serialization size before clean " << origin_meta_size
536
0
                         << " serialization size after clean " << meta_binary->length();
537
0
        }
538
557
    }
539
540
557
    if (!serialize_success) {
541
0
        LOG(FATAL) << "failed to serialize meta " << tablet_id();
542
0
    }
543
557
}
544
545
457
Status TabletMeta::deserialize(const string& meta_binary) {
546
457
    TabletMetaPB tablet_meta_pb;
547
457
    bool parsed = tablet_meta_pb.ParseFromString(meta_binary);
548
457
    if (!parsed) {
549
0
        return Status::Error<INIT_FAILED>("parse tablet meta failed");
550
0
    }
551
457
    init_from_pb(tablet_meta_pb);
552
457
    return Status::OK();
553
457
}
554
555
2
void TabletMeta::init_rs_metas_fs(const io::FileSystemSPtr& fs) {
556
4
    for (auto& rs_meta : _rs_metas) {
557
4
        if (rs_meta->is_local()) {
558
4
            rs_meta->set_fs(fs);
559
4
        }
560
4
    }
561
2
    for (auto& rs_meta : _stale_rs_metas) {
562
0
        if (rs_meta->is_local()) {
563
0
            rs_meta->set_fs(fs);
564
0
        }
565
0
    }
566
2
}
567
568
925
void TabletMeta::init_from_pb(const TabletMetaPB& tablet_meta_pb) {
569
925
    _table_id = tablet_meta_pb.table_id();
570
925
    _partition_id = tablet_meta_pb.partition_id();
571
925
    _tablet_id = tablet_meta_pb.tablet_id();
572
925
    _replica_id = tablet_meta_pb.replica_id();
573
925
    _schema_hash = tablet_meta_pb.schema_hash();
574
925
    _shard_id = tablet_meta_pb.shard_id();
575
925
    _creation_time = tablet_meta_pb.creation_time();
576
925
    _cumulative_layer_point = tablet_meta_pb.cumulative_layer_point();
577
925
    _tablet_uid = TabletUid(tablet_meta_pb.tablet_uid());
578
925
    if (tablet_meta_pb.has_tablet_type()) {
579
905
        _tablet_type = tablet_meta_pb.tablet_type();
580
905
    } else {
581
20
        _tablet_type = TabletTypePB::TABLET_TYPE_DISK;
582
20
    }
583
584
    // init _tablet_state
585
925
    switch (tablet_meta_pb.tablet_state()) {
586
26
    case PB_NOTREADY:
587
26
        _tablet_state = TabletState::TABLET_NOTREADY;
588
26
        break;
589
675
    case PB_RUNNING:
590
675
        _tablet_state = TabletState::TABLET_RUNNING;
591
675
        break;
592
0
    case PB_TOMBSTONED:
593
0
        _tablet_state = TabletState::TABLET_TOMBSTONED;
594
0
        break;
595
0
    case PB_STOPPED:
596
0
        _tablet_state = TabletState::TABLET_STOPPED;
597
0
        break;
598
224
    case PB_SHUTDOWN:
599
224
        _tablet_state = TabletState::TABLET_SHUTDOWN;
600
224
        break;
601
0
    default:
602
0
        LOG(WARNING) << "tablet has no state. tablet=" << tablet_id()
603
0
                     << ", schema_hash=" << schema_hash();
604
925
    }
605
606
    // init _schema
607
925
    TabletSchemaSPtr schema = std::make_shared<TabletSchema>();
608
925
    schema->init_from_pb(tablet_meta_pb.schema());
609
925
    if (_handle) {
610
3
        TabletSchemaCache::instance()->release(_handle);
611
3
    }
612
925
    auto pair = TabletSchemaCache::instance()->insert(schema->to_key());
613
925
    _handle = pair.first;
614
925
    _schema = pair.second;
615
616
925
    if (tablet_meta_pb.has_enable_unique_key_merge_on_write()) {
617
905
        _enable_unique_key_merge_on_write = tablet_meta_pb.enable_unique_key_merge_on_write();
618
905
    }
619
620
    // init _rs_metas
621
10.6k
    for (auto& it : tablet_meta_pb.rs_metas()) {
622
10.6k
        RowsetMetaSharedPtr rs_meta(new RowsetMeta());
623
10.6k
        rs_meta->init_from_pb(it);
624
10.6k
        _rs_metas.push_back(std::move(rs_meta));
625
10.6k
    }
626
627
    // For mow table, delete bitmap of stale rowsets has not been persisted.
628
    // When be restart, query should not read the stale rowset, otherwise duplicate keys
629
    // will be read out. Therefore, we don't add them to _stale_rs_meta for mow table.
630
925
    if (!config::skip_loading_stale_rowset_meta && !_enable_unique_key_merge_on_write) {
631
891
        for (auto& it : tablet_meta_pb.stale_rs_metas()) {
632
0
            RowsetMetaSharedPtr rs_meta(new RowsetMeta());
633
0
            rs_meta->init_from_pb(it);
634
0
            _stale_rs_metas.push_back(std::move(rs_meta));
635
0
        }
636
891
    }
637
638
925
    if (tablet_meta_pb.has_in_restore_mode()) {
639
905
        _in_restore_mode = tablet_meta_pb.in_restore_mode();
640
905
    }
641
642
925
    if (tablet_meta_pb.has_preferred_rowset_type()) {
643
467
        _preferred_rowset_type = tablet_meta_pb.preferred_rowset_type();
644
467
    }
645
646
925
    _storage_policy_id = tablet_meta_pb.storage_policy_id();
647
925
    if (tablet_meta_pb.has_cooldown_meta_id()) {
648
0
        _cooldown_meta_id = tablet_meta_pb.cooldown_meta_id();
649
0
    }
650
651
925
    if (tablet_meta_pb.has_delete_bitmap()) {
652
0
        int rst_ids_size = tablet_meta_pb.delete_bitmap().rowset_ids_size();
653
0
        int seg_ids_size = tablet_meta_pb.delete_bitmap().segment_ids_size();
654
0
        int versions_size = tablet_meta_pb.delete_bitmap().versions_size();
655
0
        int seg_maps_size = tablet_meta_pb.delete_bitmap().segment_delete_bitmaps_size();
656
0
        CHECK(rst_ids_size == seg_ids_size && seg_ids_size == seg_maps_size &&
657
0
              seg_maps_size == versions_size);
658
0
        for (size_t i = 0; i < rst_ids_size; ++i) {
659
0
            RowsetId rst_id;
660
0
            rst_id.init(tablet_meta_pb.delete_bitmap().rowset_ids(i));
661
0
            auto seg_id = tablet_meta_pb.delete_bitmap().segment_ids(i);
662
0
            uint32_t ver = tablet_meta_pb.delete_bitmap().versions(i);
663
0
            auto bitmap = tablet_meta_pb.delete_bitmap().segment_delete_bitmaps(i).data();
664
0
            delete_bitmap().delete_bitmap[{rst_id, seg_id, ver}] = roaring::Roaring::read(bitmap);
665
0
        }
666
0
    }
667
668
925
    if (tablet_meta_pb.has_binlog_config()) {
669
465
        _binlog_config = tablet_meta_pb.binlog_config();
670
465
    }
671
925
    _compaction_policy = tablet_meta_pb.compaction_policy();
672
925
    _time_series_compaction_goal_size_mbytes =
673
925
            tablet_meta_pb.time_series_compaction_goal_size_mbytes();
674
925
    _time_series_compaction_file_count_threshold =
675
925
            tablet_meta_pb.time_series_compaction_file_count_threshold();
676
925
    _time_series_compaction_time_threshold_seconds =
677
925
            tablet_meta_pb.time_series_compaction_time_threshold_seconds();
678
925
    _time_series_compaction_empty_rowsets_threshold =
679
925
            tablet_meta_pb.time_series_compaction_empty_rowsets_threshold();
680
925
    _time_series_compaction_level_threshold =
681
925
            tablet_meta_pb.time_series_compaction_level_threshold();
682
925
}
683
684
793
void TabletMeta::to_meta_pb(TabletMetaPB* tablet_meta_pb) {
685
793
    tablet_meta_pb->set_table_id(table_id());
686
793
    tablet_meta_pb->set_partition_id(partition_id());
687
793
    tablet_meta_pb->set_tablet_id(tablet_id());
688
793
    tablet_meta_pb->set_replica_id(replica_id());
689
793
    tablet_meta_pb->set_schema_hash(schema_hash());
690
793
    tablet_meta_pb->set_shard_id(shard_id());
691
793
    tablet_meta_pb->set_creation_time(creation_time());
692
793
    tablet_meta_pb->set_cumulative_layer_point(cumulative_layer_point());
693
793
    *(tablet_meta_pb->mutable_tablet_uid()) = tablet_uid().to_proto();
694
793
    tablet_meta_pb->set_tablet_type(_tablet_type);
695
793
    switch (tablet_state()) {
696
6
    case TABLET_NOTREADY:
697
6
        tablet_meta_pb->set_tablet_state(PB_NOTREADY);
698
6
        break;
699
312
    case TABLET_RUNNING:
700
312
        tablet_meta_pb->set_tablet_state(PB_RUNNING);
701
312
        break;
702
0
    case TABLET_TOMBSTONED:
703
0
        tablet_meta_pb->set_tablet_state(PB_TOMBSTONED);
704
0
        break;
705
0
    case TABLET_STOPPED:
706
0
        tablet_meta_pb->set_tablet_state(PB_STOPPED);
707
0
        break;
708
475
    case TABLET_SHUTDOWN:
709
475
        tablet_meta_pb->set_tablet_state(PB_SHUTDOWN);
710
475
        break;
711
793
    }
712
713
21.2k
    for (auto& rs : _rs_metas) {
714
21.2k
        rs->to_rowset_pb(tablet_meta_pb->add_rs_metas());
715
21.2k
    }
716
793
    for (auto rs : _stale_rs_metas) {
717
0
        rs->to_rowset_pb(tablet_meta_pb->add_stale_rs_metas());
718
0
    }
719
793
    _schema->to_schema_pb(tablet_meta_pb->mutable_schema());
720
721
793
    tablet_meta_pb->set_in_restore_mode(in_restore_mode());
722
723
    // to avoid modify tablet meta to the greatest extend
724
793
    if (_preferred_rowset_type == BETA_ROWSET) {
725
793
        tablet_meta_pb->set_preferred_rowset_type(_preferred_rowset_type);
726
793
    }
727
793
    if (_storage_policy_id > 0) {
728
5
        tablet_meta_pb->set_storage_policy_id(_storage_policy_id);
729
5
    }
730
793
    if (_cooldown_meta_id.initialized()) {
731
5
        tablet_meta_pb->mutable_cooldown_meta_id()->CopyFrom(_cooldown_meta_id.to_proto());
732
5
    }
733
734
793
    tablet_meta_pb->set_enable_unique_key_merge_on_write(_enable_unique_key_merge_on_write);
735
736
793
    if (_enable_unique_key_merge_on_write) {
737
2
        std::set<RowsetId> stale_rs_ids;
738
2
        for (const auto& rowset : _stale_rs_metas) {
739
0
            stale_rs_ids.insert(rowset->rowset_id());
740
0
        }
741
2
        DeleteBitmapPB* delete_bitmap_pb = tablet_meta_pb->mutable_delete_bitmap();
742
2
        for (auto& [id, bitmap] : delete_bitmap().snapshot().delete_bitmap) {
743
2
            auto& [rowset_id, segment_id, ver] = id;
744
2
            if (stale_rs_ids.count(rowset_id) != 0) {
745
0
                continue;
746
0
            }
747
2
            delete_bitmap_pb->add_rowset_ids(rowset_id.to_string());
748
2
            delete_bitmap_pb->add_segment_ids(segment_id);
749
2
            delete_bitmap_pb->add_versions(ver);
750
2
            std::string bitmap_data(bitmap.getSizeInBytes(), '\0');
751
2
            bitmap.write(bitmap_data.data());
752
2
            *(delete_bitmap_pb->add_segment_delete_bitmaps()) = std::move(bitmap_data);
753
2
        }
754
2
    }
755
793
    _binlog_config.to_pb(tablet_meta_pb->mutable_binlog_config());
756
793
    tablet_meta_pb->set_compaction_policy(compaction_policy());
757
793
    tablet_meta_pb->set_time_series_compaction_goal_size_mbytes(
758
793
            time_series_compaction_goal_size_mbytes());
759
793
    tablet_meta_pb->set_time_series_compaction_file_count_threshold(
760
793
            time_series_compaction_file_count_threshold());
761
793
    tablet_meta_pb->set_time_series_compaction_time_threshold_seconds(
762
793
            time_series_compaction_time_threshold_seconds());
763
793
    tablet_meta_pb->set_time_series_compaction_empty_rowsets_threshold(
764
793
            time_series_compaction_empty_rowsets_threshold());
765
793
    tablet_meta_pb->set_time_series_compaction_level_threshold(
766
793
            time_series_compaction_level_threshold());
767
793
}
768
769
548
int64_t TabletMeta::mem_size() const {
770
548
    auto size = sizeof(TabletMeta);
771
548
    size += _schema->mem_size();
772
548
    return size;
773
548
}
774
775
2
void TabletMeta::to_json(string* json_string, json2pb::Pb2JsonOptions& options) {
776
2
    TabletMetaPB tablet_meta_pb;
777
2
    to_meta_pb(&tablet_meta_pb);
778
2
    json2pb::ProtoMessageToJson(tablet_meta_pb, json_string, options);
779
2
}
780
781
91
Version TabletMeta::max_version() const {
782
91
    Version max_version = {-1, 0};
783
153
    for (auto& rs_meta : _rs_metas) {
784
153
        if (rs_meta->end_version() > max_version.second) {
785
151
            max_version = rs_meta->version();
786
151
        }
787
153
    }
788
91
    return max_version;
789
91
}
790
791
0
size_t TabletMeta::version_count_cross_with_range(const Version& range) const {
792
0
    size_t count = 0;
793
0
    for (const auto& rs_meta : _rs_metas) {
794
0
        if (!(range.first > rs_meta->version().second || range.second < rs_meta->version().first)) {
795
0
            count++;
796
0
        }
797
0
    }
798
0
    return count;
799
0
}
800
801
10.8k
Status TabletMeta::add_rs_meta(const RowsetMetaSharedPtr& rs_meta) {
802
    // check RowsetMeta is valid
803
337k
    for (auto& rs : _rs_metas) {
804
337k
        if (rs->version() == rs_meta->version()) {
805
0
            if (rs->rowset_id() != rs_meta->rowset_id()) {
806
0
                return Status::Error<PUSH_VERSION_ALREADY_EXIST>(
807
0
                        "version already exist. rowset_id={}, version={}, tablet={}",
808
0
                        rs->rowset_id().to_string(), rs->version().to_string(), tablet_id());
809
0
            } else {
810
                // rowsetid,version is equal, it is a duplicate req, skip it
811
0
                return Status::OK();
812
0
            }
813
0
        }
814
337k
    }
815
10.8k
    _rs_metas.push_back(rs_meta);
816
10.8k
    return Status::OK();
817
10.8k
}
818
819
void TabletMeta::delete_rs_meta_by_version(const Version& version,
820
0
                                           std::vector<RowsetMetaSharedPtr>* deleted_rs_metas) {
821
0
    auto it = _rs_metas.begin();
822
0
    while (it != _rs_metas.end()) {
823
0
        if ((*it)->version() == version) {
824
0
            if (deleted_rs_metas != nullptr) {
825
0
                deleted_rs_metas->push_back(*it);
826
0
            }
827
0
            _rs_metas.erase(it);
828
0
            return;
829
0
        } else {
830
0
            ++it;
831
0
        }
832
0
    }
833
0
}
834
835
void TabletMeta::modify_rs_metas(const std::vector<RowsetMetaSharedPtr>& to_add,
836
                                 const std::vector<RowsetMetaSharedPtr>& to_delete,
837
23
                                 bool same_version) {
838
    // Remove to_delete rowsets from _rs_metas
839
23
    for (auto rs_to_del : to_delete) {
840
17
        auto it = _rs_metas.begin();
841
19
        while (it != _rs_metas.end()) {
842
19
            if (rs_to_del->version() == (*it)->version()) {
843
17
                _rs_metas.erase(it);
844
                // there should be only one rowset match the version
845
17
                break;
846
17
            } else {
847
2
                ++it;
848
2
            }
849
19
        }
850
17
    }
851
23
    if (!same_version) {
852
        // put to_delete rowsets in _stale_rs_metas.
853
6
        _stale_rs_metas.insert(_stale_rs_metas.end(), to_delete.begin(), to_delete.end());
854
6
    }
855
    // put to_add rowsets in _rs_metas.
856
23
    _rs_metas.insert(_rs_metas.end(), to_add.begin(), to_add.end());
857
23
}
858
859
// Use the passing "rs_metas" to replace the rs meta in this tablet meta
860
// Also clear the _stale_rs_metas because this tablet meta maybe copyied from
861
// an existing tablet before. Add after revise, only the passing "rs_metas"
862
// is needed.
863
3
void TabletMeta::revise_rs_metas(std::vector<RowsetMetaSharedPtr>&& rs_metas) {
864
3
    std::lock_guard<std::shared_mutex> wrlock(_meta_lock);
865
3
    _rs_metas = std::move(rs_metas);
866
3
    _stale_rs_metas.clear();
867
3
}
868
869
// This method should call after revise_rs_metas, since new rs_metas might be a subset
870
// of original tablet, we should revise the delete_bitmap according to current rowset.
871
//
872
// Delete bitmap is protected by Tablet::_meta_lock, we don't need to acquire the
873
// TabletMeta's _meta_lock
874
1
void TabletMeta::revise_delete_bitmap_unlocked(const DeleteBitmap& delete_bitmap) {
875
1
    _delete_bitmap = std::make_unique<DeleteBitmap>(tablet_id());
876
2
    for (auto rs : _rs_metas) {
877
2
        DeleteBitmap rs_bm(tablet_id());
878
2
        delete_bitmap.subset({rs->rowset_id(), 0, 0}, {rs->rowset_id(), UINT32_MAX, INT64_MAX},
879
2
                             &rs_bm);
880
2
        _delete_bitmap->merge(rs_bm);
881
2
    }
882
1
    for (auto rs : _stale_rs_metas) {
883
0
        DeleteBitmap rs_bm(tablet_id());
884
0
        delete_bitmap.subset({rs->rowset_id(), 0, 0}, {rs->rowset_id(), UINT32_MAX, INT64_MAX},
885
0
                             &rs_bm);
886
0
        _delete_bitmap->merge(rs_bm);
887
0
    }
888
1
}
889
890
0
void TabletMeta::delete_stale_rs_meta_by_version(const Version& version) {
891
0
    auto it = _stale_rs_metas.begin();
892
0
    while (it != _stale_rs_metas.end()) {
893
0
        if ((*it)->version() == version) {
894
0
            if (_enable_unique_key_merge_on_write) {
895
                // remove rowset delete bitmap
896
0
                delete_bitmap().remove({(*it)->rowset_id(), 0, 0},
897
0
                                       {(*it)->rowset_id(), UINT32_MAX, 0});
898
0
            }
899
0
            it = _stale_rs_metas.erase(it);
900
0
        } else {
901
0
            it++;
902
0
        }
903
0
    }
904
0
}
905
906
0
RowsetMetaSharedPtr TabletMeta::acquire_rs_meta_by_version(const Version& version) const {
907
0
    for (auto it : _rs_metas) {
908
0
        if (it->version() == version) {
909
0
            return it;
910
0
        }
911
0
    }
912
0
    return nullptr;
913
0
}
914
915
8
RowsetMetaSharedPtr TabletMeta::acquire_stale_rs_meta_by_version(const Version& version) const {
916
8
    for (auto it : _stale_rs_metas) {
917
0
        if (it->version() == version) {
918
0
            return it;
919
0
        }
920
0
    }
921
8
    return nullptr;
922
8
}
923
924
22
Status TabletMeta::set_partition_id(int64_t partition_id) {
925
22
    if ((_partition_id > 0 && _partition_id != partition_id) || partition_id < 1) {
926
0
        LOG(WARNING) << "cur partition id=" << _partition_id << " new partition id=" << partition_id
927
0
                     << " not equal";
928
0
    }
929
22
    _partition_id = partition_id;
930
22
    return Status::OK();
931
22
}
932
933
1
bool operator==(const TabletMeta& a, const TabletMeta& b) {
934
1
    if (a._table_id != b._table_id) return false;
935
1
    if (a._partition_id != b._partition_id) return false;
936
1
    if (a._tablet_id != b._tablet_id) return false;
937
1
    if (a._replica_id != b._replica_id) return false;
938
1
    if (a._schema_hash != b._schema_hash) return false;
939
1
    if (a._shard_id != b._shard_id) return false;
940
1
    if (a._creation_time != b._creation_time) return false;
941
1
    if (a._cumulative_layer_point != b._cumulative_layer_point) return false;
942
1
    if (a._tablet_uid != b._tablet_uid) return false;
943
1
    if (a._tablet_type != b._tablet_type) return false;
944
1
    if (a._tablet_state != b._tablet_state) return false;
945
1
    if (*a._schema != *b._schema) return false;
946
1
    if (a._rs_metas.size() != b._rs_metas.size()) return false;
947
1
    for (int i = 0; i < a._rs_metas.size(); ++i) {
948
0
        if (a._rs_metas[i] != b._rs_metas[i]) return false;
949
0
    }
950
1
    if (a._in_restore_mode != b._in_restore_mode) return false;
951
1
    if (a._preferred_rowset_type != b._preferred_rowset_type) return false;
952
1
    if (a._storage_policy_id != b._storage_policy_id) return false;
953
1
    if (a._compaction_policy != b._compaction_policy) return false;
954
1
    if (a._time_series_compaction_goal_size_mbytes != b._time_series_compaction_goal_size_mbytes)
955
0
        return false;
956
1
    if (a._time_series_compaction_file_count_threshold !=
957
1
        b._time_series_compaction_file_count_threshold)
958
0
        return false;
959
1
    if (a._time_series_compaction_time_threshold_seconds !=
960
1
        b._time_series_compaction_time_threshold_seconds)
961
0
        return false;
962
1
    if (a._time_series_compaction_empty_rowsets_threshold !=
963
1
        b._time_series_compaction_empty_rowsets_threshold)
964
0
        return false;
965
1
    if (a._time_series_compaction_level_threshold != b._time_series_compaction_level_threshold)
966
0
        return false;
967
1
    return true;
968
1
}
969
970
0
bool operator!=(const TabletMeta& a, const TabletMeta& b) {
971
0
    return !(a == b);
972
0
}
973
974
1.00k
DeleteBitmap::DeleteBitmap(int64_t tablet_id) : _tablet_id(tablet_id) {
975
    // The default delete bitmap cache is set to 100MB,
976
    // which can be insufficient and cause performance issues when the amount of user data is large.
977
    // To mitigate the problem of an inadequate cache,
978
    // we will take the larger of 0.5% of the total memory and 100MB as the delete bitmap cache size.
979
1.00k
    bool is_percent = false;
980
1.00k
    int64_t delete_bitmap_agg_cache_cache_limit =
981
1.00k
            ParseUtil::parse_mem_spec(config::delete_bitmap_dynamic_agg_cache_limit,
982
1.00k
                                      MemInfo::mem_limit(), MemInfo::physical_mem(), &is_percent);
983
1.00k
    _agg_cache.reset(new AggCache(delete_bitmap_agg_cache_cache_limit >
984
1.00k
                                                  config::delete_bitmap_agg_cache_capacity
985
1.00k
                                          ? delete_bitmap_agg_cache_cache_limit
986
1.00k
                                          : config::delete_bitmap_agg_cache_capacity));
987
1.00k
}
988
989
5
DeleteBitmap::DeleteBitmap(const DeleteBitmap& o) {
990
5
    delete_bitmap = o.delete_bitmap; // just copy data
991
5
    _tablet_id = o._tablet_id;
992
5
}
993
994
0
DeleteBitmap& DeleteBitmap::operator=(const DeleteBitmap& o) {
995
0
    delete_bitmap = o.delete_bitmap; // just copy data
996
0
    _tablet_id = o._tablet_id;
997
0
    return *this;
998
0
}
999
1000
0
DeleteBitmap::DeleteBitmap(DeleteBitmap&& o) {
1001
0
    delete_bitmap = std::move(o.delete_bitmap);
1002
0
    _tablet_id = o._tablet_id;
1003
0
}
1004
1005
0
DeleteBitmap& DeleteBitmap::operator=(DeleteBitmap&& o) {
1006
0
    delete_bitmap = std::move(o.delete_bitmap);
1007
0
    _tablet_id = o._tablet_id;
1008
0
    return *this;
1009
0
}
1010
1011
5
DeleteBitmap DeleteBitmap::snapshot() const {
1012
5
    std::shared_lock l(lock);
1013
5
    return DeleteBitmap(*this);
1014
5
}
1015
1016
3
DeleteBitmap DeleteBitmap::snapshot(Version version) const {
1017
    // Take snapshot first, then remove keys greater than given version.
1018
3
    DeleteBitmap snapshot = this->snapshot();
1019
3
    auto it = snapshot.delete_bitmap.begin();
1020
412
    while (it != snapshot.delete_bitmap.end()) {
1021
409
        if (std::get<2>(it->first) > version) {
1022
4
            it = snapshot.delete_bitmap.erase(it);
1023
405
        } else {
1024
405
            it++;
1025
405
        }
1026
409
    }
1027
3
    return snapshot;
1028
3
}
1029
1030
459k
void DeleteBitmap::add(const BitmapKey& bmk, uint32_t row_id) {
1031
459k
    std::lock_guard l(lock);
1032
459k
    delete_bitmap[bmk].add(row_id);
1033
459k
}
1034
1035
0
int DeleteBitmap::remove(const BitmapKey& bmk, uint32_t row_id) {
1036
0
    std::lock_guard l(lock);
1037
0
    auto it = delete_bitmap.find(bmk);
1038
0
    if (it == delete_bitmap.end()) return -1;
1039
0
    it->second.remove(row_id);
1040
0
    return 0;
1041
0
}
1042
1043
8
void DeleteBitmap::remove(const BitmapKey& start, const BitmapKey& end) {
1044
8
    std::lock_guard l(lock);
1045
107
    for (auto it = delete_bitmap.lower_bound(start); it != delete_bitmap.end();) {
1046
101
        auto& [k, _] = *it;
1047
101
        if (k >= end) {
1048
2
            break;
1049
2
        }
1050
99
        it = delete_bitmap.erase(it);
1051
99
    }
1052
8
}
1053
1054
6
bool DeleteBitmap::contains(const BitmapKey& bmk, uint32_t row_id) const {
1055
6
    std::shared_lock l(lock);
1056
6
    auto it = delete_bitmap.find(bmk);
1057
6
    return it != delete_bitmap.end() && it->second.contains(row_id);
1058
6
}
1059
1060
2
bool DeleteBitmap::contains_agg(const BitmapKey& bmk, uint32_t row_id) const {
1061
2
    return get_agg(bmk)->contains(row_id);
1062
2
}
1063
1064
0
bool DeleteBitmap::empty() const {
1065
0
    std::shared_lock l(lock);
1066
0
    return delete_bitmap.empty();
1067
0
}
1068
1069
62
uint64_t DeleteBitmap::cardinality() const {
1070
62
    std::shared_lock l {lock};
1071
62
    uint64_t res = 0;
1072
62
    for (auto entry : delete_bitmap) {
1073
0
        if (std::get<1>(entry.first) != DeleteBitmap::INVALID_SEGMENT_ID) {
1074
0
            res += entry.second.cardinality();
1075
0
        }
1076
0
    }
1077
62
    return res;
1078
62
}
1079
1080
62
uint64_t DeleteBitmap::get_delete_bitmap_count() const {
1081
62
    std::shared_lock l(lock);
1082
62
    uint64_t count = 0;
1083
62
    for (auto it = delete_bitmap.begin(); it != delete_bitmap.end(); it++) {
1084
0
        if (std::get<1>(it->first) != DeleteBitmap::INVALID_SEGMENT_ID) {
1085
0
            count++;
1086
0
        }
1087
0
    }
1088
62
    return count;
1089
62
}
1090
1091
1
bool DeleteBitmap::contains_agg_without_cache(const BitmapKey& bmk, uint32_t row_id) const {
1092
1
    std::shared_lock l(lock);
1093
1
    DeleteBitmap::BitmapKey start {std::get<0>(bmk), std::get<1>(bmk), 0};
1094
1
    for (auto it = delete_bitmap.lower_bound(start); it != delete_bitmap.end(); ++it) {
1095
0
        auto& [k, bm] = *it;
1096
0
        if (std::get<0>(k) != std::get<0>(bmk) || std::get<1>(k) != std::get<1>(bmk) ||
1097
0
            std::get<2>(k) > std::get<2>(bmk)) {
1098
0
            break;
1099
0
        }
1100
0
        if (bm.contains(row_id)) {
1101
0
            return true;
1102
0
        }
1103
0
    }
1104
1
    return false;
1105
1
}
1106
1107
38
int DeleteBitmap::set(const BitmapKey& bmk, const roaring::Roaring& segment_delete_bitmap) {
1108
38
    std::lock_guard l(lock);
1109
38
    auto [_, inserted] = delete_bitmap.insert_or_assign(bmk, segment_delete_bitmap);
1110
38
    return inserted;
1111
38
}
1112
1113
3
int DeleteBitmap::get(const BitmapKey& bmk, roaring::Roaring* segment_delete_bitmap) const {
1114
3
    std::shared_lock l(lock);
1115
3
    auto it = delete_bitmap.find(bmk);
1116
3
    if (it == delete_bitmap.end()) return -1;
1117
3
    *segment_delete_bitmap = it->second; // copy
1118
3
    return 0;
1119
3
}
1120
1121
54
const roaring::Roaring* DeleteBitmap::get(const BitmapKey& bmk) const {
1122
54
    std::shared_lock l(lock);
1123
54
    auto it = delete_bitmap.find(bmk);
1124
54
    if (it == delete_bitmap.end()) return nullptr;
1125
41
    return &(it->second); // get address
1126
54
}
1127
1128
void DeleteBitmap::subset(const BitmapKey& start, const BitmapKey& end,
1129
3
                          DeleteBitmap* subset_rowset_map) const {
1130
3
    roaring::Roaring roaring;
1131
3
    DCHECK(start < end);
1132
3
    std::shared_lock l(lock);
1133
26
    for (auto it = delete_bitmap.lower_bound(start); it != delete_bitmap.end(); ++it) {
1134
25
        auto& [k, bm] = *it;
1135
25
        if (k >= end) {
1136
2
            break;
1137
2
        }
1138
23
        subset_rowset_map->set(k, bm);
1139
23
    }
1140
3
}
1141
1142
2
void DeleteBitmap::merge(const BitmapKey& bmk, const roaring::Roaring& segment_delete_bitmap) {
1143
2
    std::lock_guard l(lock);
1144
2
    auto [iter, succ] = delete_bitmap.emplace(bmk, segment_delete_bitmap);
1145
2
    if (!succ) {
1146
0
        iter->second |= segment_delete_bitmap;
1147
0
    }
1148
2
}
1149
1150
9
void DeleteBitmap::merge(const DeleteBitmap& other) {
1151
9
    std::lock_guard l(lock);
1152
29
    for (auto& i : other.delete_bitmap) {
1153
29
        auto [j, succ] = this->delete_bitmap.insert(i);
1154
29
        if (!succ) j->second |= i.second;
1155
29
    }
1156
9
}
1157
1158
0
bool DeleteBitmap::has_calculated_for_multi_segments(const RowsetId& rowset_id) const {
1159
0
    return contains({rowset_id, INVALID_SEGMENT_ID, TEMP_VERSION_COMMON}, ROWSET_SENTINEL_MARK);
1160
0
}
1161
1162
// We cannot just copy the underlying memory to construct a string
1163
// due to equivalent objects may have different padding bytes.
1164
// Reading padding bytes is undefined behavior, neither copy nor
1165
// placement new will help simplify the code.
1166
// Refer to C11 standards §6.2.6.1/6 and §6.7.9/21 for more info.
1167
44
static std::string agg_cache_key(int64_t tablet_id, const DeleteBitmap::BitmapKey& bmk) {
1168
44
    std::string ret(sizeof(tablet_id) + sizeof(bmk), '\0');
1169
44
    *reinterpret_cast<int64_t*>(ret.data()) = tablet_id;
1170
44
    auto t = reinterpret_cast<DeleteBitmap::BitmapKey*>(ret.data() + sizeof(tablet_id));
1171
44
    std::get<RowsetId>(*t).version = std::get<RowsetId>(bmk).version;
1172
44
    std::get<RowsetId>(*t).hi = std::get<RowsetId>(bmk).hi;
1173
44
    std::get<RowsetId>(*t).mi = std::get<RowsetId>(bmk).mi;
1174
44
    std::get<RowsetId>(*t).lo = std::get<RowsetId>(bmk).lo;
1175
44
    std::get<1>(*t) = std::get<1>(bmk);
1176
44
    std::get<2>(*t) = std::get<2>(bmk);
1177
44
    return ret;
1178
44
}
1179
1180
44
std::shared_ptr<roaring::Roaring> DeleteBitmap::get_agg(const BitmapKey& bmk) const {
1181
44
    std::string key_str = agg_cache_key(_tablet_id, bmk); // Cache key container
1182
44
    CacheKey key(key_str);
1183
44
    Cache::Handle* handle = _agg_cache->repr()->lookup(key);
1184
1185
44
    AggCache::Value* val =
1186
44
            handle == nullptr
1187
44
                    ? nullptr
1188
44
                    : reinterpret_cast<AggCache::Value*>(_agg_cache->repr()->value(handle));
1189
    // FIXME: do we need a mutex here to get rid of duplicated initializations
1190
    //        of cache entries in some cases?
1191
44
    if (val == nullptr) { // Renew if needed, put a new Value to cache
1192
38
        val = new AggCache::Value();
1193
38
        {
1194
38
            std::shared_lock l(lock);
1195
38
            DeleteBitmap::BitmapKey start {std::get<0>(bmk), std::get<1>(bmk), 0};
1196
69
            for (auto it = delete_bitmap.lower_bound(start); it != delete_bitmap.end(); ++it) {
1197
66
                auto& [k, bm] = *it;
1198
66
                if (std::get<0>(k) != std::get<0>(bmk) || std::get<1>(k) != std::get<1>(bmk) ||
1199
66
                    std::get<2>(k) > std::get<2>(bmk)) {
1200
35
                    break;
1201
35
                }
1202
31
                val->bitmap |= bm;
1203
31
            }
1204
38
        }
1205
38
        size_t charge = val->bitmap.getSizeInBytes() + sizeof(AggCache::Value);
1206
38
        handle = _agg_cache->repr()->insert(key, val, charge, charge, CachePriority::NORMAL);
1207
38
    }
1208
1209
    // It is natural for the cache to reclaim the underlying memory
1210
44
    return std::shared_ptr<roaring::Roaring>(
1211
44
            &val->bitmap, [this, handle](...) { _agg_cache->repr()->release(handle); });
1212
44
}
1213
1214
std::atomic<DeleteBitmap::AggCachePolicy*> DeleteBitmap::AggCache::s_repr {nullptr};
1215
1216
0
std::string tablet_state_name(TabletState state) {
1217
0
    switch (state) {
1218
0
    case TABLET_NOTREADY:
1219
0
        return "TABLET_NOTREADY";
1220
1221
0
    case TABLET_RUNNING:
1222
0
        return "TABLET_RUNNING";
1223
1224
0
    case TABLET_TOMBSTONED:
1225
0
        return "TABLET_TOMBSTONED";
1226
1227
0
    case TABLET_STOPPED:
1228
0
        return "TABLET_STOPPED";
1229
1230
0
    case TABLET_SHUTDOWN:
1231
0
        return "TABLET_SHUTDOWN";
1232
1233
0
    default:
1234
0
        return "TabletState(" + std::to_string(state) + ")";
1235
0
    }
1236
0
}
1237
1238
} // namespace doris