Coverage Report

Created: 2026-05-09 01:07

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/storage/snapshot/snapshot_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/snapshot/snapshot_manager.h"
19
20
#include <fmt/format.h>
21
#include <gen_cpp/AgentService_types.h>
22
#include <gen_cpp/Types_constants.h>
23
#include <gen_cpp/olap_file.pb.h>
24
#include <thrift/protocol/TDebugProtocol.h>
25
26
#include <algorithm>
27
#include <atomic>
28
#include <ctime>
29
#include <filesystem>
30
#include <list>
31
#include <map>
32
#include <new>
33
#include <ostream>
34
#include <set>
35
#include <shared_mutex>
36
#include <unordered_map>
37
#include <utility>
38
39
#include "common/config.h"
40
#include "common/logging.h"
41
#include "common/status.h"
42
#include "io/fs/local_file_system.h"
43
#include "runtime/memory/mem_tracker_limiter.h"
44
#include "runtime/thread_context.h"
45
#include "storage/data_dir.h"
46
#include "storage/olap_common.h"
47
#include "storage/olap_define.h"
48
#include "storage/pb_helper.h"
49
#include "storage/rowset/rowset.h"
50
#include "storage/rowset/rowset_factory.h"
51
#include "storage/rowset/rowset_meta.h"
52
#include "storage/rowset/rowset_writer.h"
53
#include "storage/rowset/rowset_writer_context.h"
54
#include "storage/storage_engine.h"
55
#include "storage/tablet/tablet_manager.h"
56
#include "storage/tablet/tablet_meta.h"
57
#include "storage/tablet/tablet_schema.h"
58
#include "storage/tablet/tablet_schema_cache.h"
59
#include "storage/utils.h"
60
#include "util/uid_util.h"
61
62
using std::nothrow;
63
using std::string;
64
using std::stringstream;
65
using std::vector;
66
67
namespace doris {
68
using namespace ErrorCode;
69
70
816
LocalSnapshotLockGuard LocalSnapshotLock::acquire(const std::string& path) {
71
816
    std::unique_lock<std::mutex> l(_lock);
72
816
    auto& ctx = _local_snapshot_contexts[path];
73
816
    while (ctx._is_locked) {
74
0
        ctx._waiting_count++;
75
0
        ctx._cv.wait(l);
76
0
        ctx._waiting_count--;
77
0
    }
78
79
816
    ctx._is_locked = true;
80
816
    return {path};
81
816
}
82
83
816
void LocalSnapshotLock::release(const std::string& path) {
84
816
    std::lock_guard<std::mutex> l(_lock);
85
816
    auto iter = _local_snapshot_contexts.find(path);
86
816
    if (iter == _local_snapshot_contexts.end()) {
87
0
        return;
88
0
    }
89
90
816
    auto& ctx = iter->second;
91
816
    ctx._is_locked = false;
92
816
    if (ctx._waiting_count > 0) {
93
0
        ctx._cv.notify_one();
94
816
    } else {
95
816
        _local_snapshot_contexts.erase(iter);
96
816
    }
97
816
}
98
99
374
SnapshotManager::SnapshotManager(StorageEngine& engine) : _engine(engine) {
100
374
    _mem_tracker =
101
374
            MemTrackerLimiter::create_shared(MemTrackerLimiter::Type::OTHER, "SnapshotManager");
102
374
}
103
104
371
SnapshotManager::~SnapshotManager() = default;
105
106
Status SnapshotManager::make_snapshot(const TSnapshotRequest& request, string* snapshot_path,
107
323
                                      bool* allow_incremental_clone) {
108
323
    SCOPED_ATTACH_TASK(_mem_tracker);
109
323
    Status res = Status::OK();
110
323
    if (snapshot_path == nullptr) {
111
1
        return Status::Error<INVALID_ARGUMENT>("output parameter cannot be null");
112
1
    }
113
114
322
    TabletSharedPtr target_tablet = _engine.tablet_manager()->get_tablet(request.tablet_id);
115
116
322
    DBUG_EXECUTE_IF("SnapshotManager::make_snapshot.inject_failure", { target_tablet = nullptr; })
117
118
322
    if (target_tablet == nullptr) {
119
0
        return Status::Error<TABLE_NOT_FOUND>("failed to get tablet. tablet={}", request.tablet_id);
120
0
    }
121
122
322
    TabletSharedPtr ref_tablet = target_tablet;
123
322
    if (request.__isset.ref_tablet_id) {
124
0
        int64_t ref_tablet_id = request.ref_tablet_id;
125
0
        TabletSharedPtr base_tablet = _engine.tablet_manager()->get_tablet(ref_tablet_id);
126
127
        // Some tasks, like medium migration, cause the target tablet and base tablet to stay on
128
        // different disks. In this case, we fall through to the normal restore path.
129
        //
130
        // Otherwise, we can directly link the rowset files from the base tablet to the target tablet.
131
0
        if (base_tablet != nullptr &&
132
0
            base_tablet->data_dir()->path() == target_tablet->data_dir()->path()) {
133
0
            ref_tablet = std::move(base_tablet);
134
0
        }
135
0
    }
136
137
322
    res = _create_snapshot_files(ref_tablet, target_tablet, request, snapshot_path,
138
322
                                 allow_incremental_clone);
139
140
322
    if (!res.ok()) {
141
0
        LOG(WARNING) << "failed to make snapshot. res=" << res << " tablet=" << request.tablet_id;
142
0
        return res;
143
0
    }
144
145
322
    LOG(INFO) << "success to make snapshot. path=['" << *snapshot_path << "']";
146
322
    return res;
147
322
}
148
149
321
Status SnapshotManager::release_snapshot(const string& snapshot_path) {
150
321
    auto local_snapshot_guard = LocalSnapshotLock::instance().acquire(snapshot_path);
151
152
    // If the requested snapshot_path is located in the root/snapshot folder, it is considered legal and can be deleted.
153
    // Otherwise, it is considered an illegal request and returns an error result.
154
321
    SCOPED_ATTACH_TASK(_mem_tracker);
155
321
    auto stores = _engine.get_stores();
156
321
    for (auto* store : stores) {
157
320
        std::string abs_path;
158
320
        RETURN_IF_ERROR(io::global_local_filesystem()->canonicalize(store->path(), &abs_path));
159
320
        if (snapshot_path.compare(0, abs_path.size(), abs_path) == 0 &&
160
320
            snapshot_path.compare(abs_path.size() + 1, SNAPSHOT_PREFIX.size(), SNAPSHOT_PREFIX) ==
161
320
                    0) {
162
320
            RETURN_IF_ERROR(io::global_local_filesystem()->delete_directory(snapshot_path));
163
320
            LOG(INFO) << "success to release snapshot path. [path='" << snapshot_path << "']";
164
320
            return Status::OK();
165
320
        }
166
320
    }
167
168
1
    return Status::Error<CE_CMD_PARAMS_ERROR>("released snapshot path illegal. [path='{}']",
169
1
                                              snapshot_path);
170
321
}
171
172
Result<std::vector<PendingRowsetGuard>> SnapshotManager::convert_rowset_ids(
173
        const std::string& clone_dir, int64_t tablet_id, int64_t replica_id, int64_t table_id,
174
178
        int64_t partition_id, int32_t schema_hash) {
175
178
    SCOPED_SWITCH_THREAD_MEM_TRACKER_LIMITER(_mem_tracker);
176
178
    std::vector<PendingRowsetGuard> guards;
177
    // check clone dir existed
178
178
    bool exists = true;
179
178
    RETURN_IF_ERROR_RESULT(io::global_local_filesystem()->exists(clone_dir, &exists));
180
178
    if (!exists) {
181
1
        return unexpected(Status::Error<DIR_NOT_EXIST>(
182
1
                "clone dir not existed when convert rowsetids. clone_dir={}", clone_dir));
183
1
    }
184
185
177
    TabletSharedPtr target_tablet = _engine.tablet_manager()->get_tablet(tablet_id);
186
177
    TabletSchemaSPtr target_tablet_schema = nullptr;
187
177
    if (target_tablet != nullptr) {
188
176
        target_tablet_schema = std::make_shared<TabletSchema>();
189
176
        target_tablet_schema->copy_from(*target_tablet->tablet_schema());
190
176
    }
191
192
    // load original tablet meta
193
177
    auto cloned_meta_file = fmt::format("{}/{}.hdr", clone_dir, tablet_id);
194
177
    TabletMetaPB cloned_tablet_meta_pb;
195
177
    RETURN_IF_ERROR_RESULT(TabletMeta::load_from_file(cloned_meta_file, &cloned_tablet_meta_pb));
196
197
177
    TabletMetaPB new_tablet_meta_pb;
198
177
    new_tablet_meta_pb = cloned_tablet_meta_pb;
199
177
    new_tablet_meta_pb.clear_rs_metas();
200
    // inc_rs_meta is deprecated since 0.13.
201
    // keep this just for safety
202
177
    new_tablet_meta_pb.clear_inc_rs_metas();
203
177
    new_tablet_meta_pb.clear_stale_rs_metas();
204
205
    // should modify tablet id and schema hash because in restore process the tablet id is not
206
    // equal to tablet id in meta
207
177
    new_tablet_meta_pb.set_tablet_id(tablet_id);
208
177
    *new_tablet_meta_pb.mutable_tablet_uid() = TabletUid::gen_uid().to_proto();
209
177
    new_tablet_meta_pb.set_replica_id(replica_id);
210
177
    if (table_id > 0) {
211
173
        new_tablet_meta_pb.set_table_id(table_id);
212
173
    }
213
177
    if (partition_id != -1) {
214
177
        new_tablet_meta_pb.set_partition_id(partition_id);
215
177
    }
216
177
    new_tablet_meta_pb.set_schema_hash(schema_hash);
217
177
    TabletSchemaSPtr tablet_schema = std::make_shared<TabletSchema>();
218
177
    tablet_schema->init_from_pb(new_tablet_meta_pb.schema());
219
220
177
    std::unordered_map<Version, RowsetMetaPB*, HashOfVersion> rs_version_map;
221
177
    std::unordered_map<RowsetId, RowsetId> rowset_id_mapping;
222
177
    guards.reserve(cloned_tablet_meta_pb.rs_metas_size() +
223
177
                   cloned_tablet_meta_pb.stale_rs_metas_size());
224
353
    for (auto&& visible_rowset : cloned_tablet_meta_pb.rs_metas()) {
225
353
        RowsetMetaPB* rowset_meta = new_tablet_meta_pb.add_rs_metas();
226
353
        if (!visible_rowset.has_resource_id()) {
227
            // src be local rowset
228
353
            RowsetId rowset_id = _engine.next_rowset_id();
229
353
            guards.push_back(_engine.pending_local_rowsets().add(rowset_id));
230
353
            RETURN_IF_ERROR_RESULT(_rename_rowset_id(
231
353
                    visible_rowset, clone_dir, tablet_schema, rowset_id, rowset_meta,
232
353
                    new_tablet_meta_pb.enable_unique_key_merge_on_write()));
233
353
            RowsetId src_rs_id;
234
353
            if (visible_rowset.rowset_id() > 0) {
235
1
                src_rs_id.init(visible_rowset.rowset_id());
236
352
            } else {
237
352
                src_rs_id.init(visible_rowset.rowset_id_v2());
238
352
            }
239
353
            rowset_id_mapping[src_rs_id] = rowset_id;
240
353
            rowset_meta->set_source_rowset_id(visible_rowset.rowset_id_v2());
241
353
            rowset_meta->set_source_tablet_id(cloned_tablet_meta_pb.tablet_id());
242
353
        } else {
243
            // remote rowset
244
0
            *rowset_meta = visible_rowset;
245
0
        }
246
247
353
        rowset_meta->set_tablet_id(tablet_id);
248
353
        if (partition_id != -1) {
249
353
            rowset_meta->set_partition_id(partition_id);
250
353
        }
251
252
353
        if (rowset_meta->has_tablet_schema() && rowset_meta->tablet_schema().index_size() > 0) {
253
1
            RETURN_IF_ERROR_RESULT(
254
1
                    _rename_index_ids(*rowset_meta->mutable_tablet_schema(), target_tablet_schema));
255
1
        }
256
257
353
        Version rowset_version = {visible_rowset.start_version(), visible_rowset.end_version()};
258
353
        rs_version_map[rowset_version] = rowset_meta;
259
353
    }
260
261
177
    for (auto&& stale_rowset : cloned_tablet_meta_pb.stale_rs_metas()) {
262
0
        Version rowset_version = {stale_rowset.start_version(), stale_rowset.end_version()};
263
0
        auto exist_rs = rs_version_map.find(rowset_version);
264
0
        if (exist_rs != rs_version_map.end()) {
265
0
            continue;
266
0
        }
267
0
        RowsetMetaPB* rowset_meta = new_tablet_meta_pb.add_stale_rs_metas();
268
269
0
        if (!stale_rowset.has_resource_id()) {
270
            // src be local rowset
271
0
            RowsetId rowset_id = _engine.next_rowset_id();
272
0
            guards.push_back(_engine.pending_local_rowsets().add(rowset_id));
273
0
            RETURN_IF_ERROR_RESULT(_rename_rowset_id(
274
0
                    stale_rowset, clone_dir, tablet_schema, rowset_id, rowset_meta,
275
0
                    new_tablet_meta_pb.enable_unique_key_merge_on_write()));
276
0
            RowsetId src_rs_id;
277
0
            if (stale_rowset.rowset_id() > 0) {
278
0
                src_rs_id.init(stale_rowset.rowset_id());
279
0
            } else {
280
0
                src_rs_id.init(stale_rowset.rowset_id_v2());
281
0
            }
282
0
            rowset_id_mapping[src_rs_id] = rowset_id;
283
0
            rowset_meta->set_source_rowset_id(stale_rowset.rowset_id_v2());
284
0
            rowset_meta->set_source_tablet_id(cloned_tablet_meta_pb.tablet_id());
285
0
        } else {
286
            // remote rowset
287
0
            *rowset_meta = stale_rowset;
288
0
        }
289
290
0
        rowset_meta->set_tablet_id(tablet_id);
291
0
        if (partition_id != -1) {
292
0
            rowset_meta->set_partition_id(partition_id);
293
0
        }
294
295
0
        if (rowset_meta->has_tablet_schema() && rowset_meta->tablet_schema().index_size() > 0) {
296
0
            RETURN_IF_ERROR_RESULT(
297
0
                    _rename_index_ids(*rowset_meta->mutable_tablet_schema(), target_tablet_schema));
298
0
        }
299
0
    }
300
301
177
    if (new_tablet_meta_pb.schema().index_size() > 0) {
302
1
        RETURN_IF_ERROR_RESULT(
303
1
                _rename_index_ids(*new_tablet_meta_pb.mutable_schema(), target_tablet_schema));
304
1
    }
305
306
177
    if (!rowset_id_mapping.empty() && cloned_tablet_meta_pb.has_delete_bitmap()) {
307
32
        const auto& cloned_del_bitmap_pb = cloned_tablet_meta_pb.delete_bitmap();
308
32
        DeleteBitmapPB* new_del_bitmap_pb = new_tablet_meta_pb.mutable_delete_bitmap();
309
32
        int rst_ids_size = cloned_del_bitmap_pb.rowset_ids_size();
310
32
        for (int i = 0; i < rst_ids_size; ++i) {
311
0
            RowsetId rst_id;
312
0
            rst_id.init(cloned_del_bitmap_pb.rowset_ids(i));
313
            // It should not happen, if we can't convert some rowid in delete bitmap, the
314
            // data might be inconsist.
315
0
            CHECK(rowset_id_mapping.find(rst_id) != rowset_id_mapping.end())
316
0
                    << "can't find rowset_id " << rst_id.to_string() << " in convert_rowset_ids";
317
0
            new_del_bitmap_pb->set_rowset_ids(i, rowset_id_mapping[rst_id].to_string());
318
0
        }
319
32
    }
320
321
177
    RETURN_IF_ERROR_RESULT(TabletMeta::save(cloned_meta_file, new_tablet_meta_pb));
322
323
177
    return guards;
324
177
}
325
326
Status SnapshotManager::_rename_rowset_id(const RowsetMetaPB& rs_meta_pb,
327
                                          const std::string& new_tablet_path,
328
                                          TabletSchemaSPtr tablet_schema, const RowsetId& rowset_id,
329
                                          RowsetMetaPB* new_rs_meta_pb,
330
353
                                          bool enable_unique_key_merge_on_write) {
331
353
    Status st = Status::OK();
332
353
    RowsetMetaSharedPtr rowset_meta(new RowsetMeta());
333
353
    rowset_meta->init_from_pb(rs_meta_pb);
334
353
    RowsetSharedPtr org_rowset;
335
353
    RETURN_IF_ERROR(
336
353
            RowsetFactory::create_rowset(tablet_schema, new_tablet_path, rowset_meta, &org_rowset));
337
    // do not use cache to load index
338
    // because the index file may conflict
339
    // and the cached fd may be invalid
340
353
    RETURN_IF_ERROR(org_rowset->load(false));
341
353
    RowsetMetaSharedPtr org_rowset_meta = org_rowset->rowset_meta();
342
353
    RowsetWriterContext context;
343
353
    context.rowset_id = rowset_id;
344
353
    context.tablet_id = org_rowset_meta->tablet_id();
345
353
    context.partition_id = org_rowset_meta->partition_id();
346
353
    context.tablet_schema_hash = org_rowset_meta->tablet_schema_hash();
347
353
    context.rowset_type = org_rowset_meta->rowset_type();
348
353
    context.tablet_path = new_tablet_path;
349
353
    context.tablet_schema =
350
353
            org_rowset_meta->tablet_schema() ? org_rowset_meta->tablet_schema() : tablet_schema;
351
353
    context.rowset_state = org_rowset_meta->rowset_state();
352
353
    context.version = org_rowset_meta->version();
353
353
    context.newest_write_timestamp = org_rowset_meta->newest_write_timestamp();
354
    // keep segments_overlap same as origin rowset
355
353
    context.segments_overlap = rowset_meta->segments_overlap();
356
    // propagate MOW flag so that non-MOW key-bounds aggregation is not applied
357
    // when restoring a MOW tablet's rowset
358
353
    context.enable_unique_key_merge_on_write = enable_unique_key_merge_on_write;
359
360
353
    auto rs_writer = DORIS_TRY(RowsetFactory::create_rowset_writer(_engine, context, false));
361
362
353
    st = rs_writer->add_rowset(org_rowset);
363
353
    if (!st.ok()) {
364
0
        LOG(WARNING) << "failed to add rowset "
365
0
                     << " id = " << org_rowset->rowset_id() << " to rowset " << rowset_id;
366
0
        return st;
367
0
    }
368
353
    RowsetSharedPtr new_rowset;
369
353
    RETURN_NOT_OK_STATUS_WITH_WARN(rs_writer->build(new_rowset),
370
353
                                   "failed to build rowset when rename rowset id");
371
353
    RETURN_IF_ERROR(new_rowset->load(false));
372
353
    new_rowset->rowset_meta()->to_rowset_pb(new_rs_meta_pb);
373
353
    RETURN_IF_ERROR(org_rowset->remove());
374
353
    return Status::OK();
375
353
}
376
377
Status SnapshotManager::_rename_index_ids(TabletSchemaPB& schema_pb,
378
2
                                          const TabletSchemaSPtr& tablet_schema) const {
379
2
    if (tablet_schema == nullptr) {
380
0
        return Status::OK();
381
0
    }
382
383
4
    for (int i = 0; i < schema_pb.index_size(); ++i) {
384
2
        TabletIndexPB* index_pb = schema_pb.mutable_index(i);
385
2
        for (int32_t col_unique_id : index_pb->col_unique_id()) {
386
2
            auto local_index = tablet_schema->get_index(col_unique_id, index_pb->index_type(),
387
2
                                                        index_pb->index_suffix_name());
388
2
            if (local_index) {
389
2
                if (index_pb->index_id() != local_index->index_id()) {
390
2
                    index_pb->set_index_id(local_index->index_id());
391
2
                }
392
2
                break;
393
2
            }
394
2
        }
395
2
    }
396
2
    return Status::OK();
397
2
}
398
399
// get snapshot path: curtime.seq.timeout
400
// eg: 20190819221234.3.86400
401
Status SnapshotManager::_calc_snapshot_id_path(const TabletSharedPtr& tablet, int64_t timeout_s,
402
322
                                               std::string* out_path) {
403
322
    Status res = Status::OK();
404
322
    if (out_path == nullptr) {
405
0
        return Status::Error<INVALID_ARGUMENT>("output parameter cannot be null");
406
0
    }
407
408
    // get current timestamp string
409
322
    string time_str;
410
322
    if ((res = gen_timestamp_string(&time_str)) != Status::OK()) {
411
0
        LOG(WARNING) << "failed to generate time_string when move file to trash."
412
0
                     << "err code=" << res;
413
0
        return res;
414
0
    }
415
416
322
    uint64_t sid = _snapshot_base_id.fetch_add(1, std::memory_order_relaxed) - 1;
417
322
    *out_path = fmt::format("{}/{}/{}.{}.{}", tablet->data_dir()->path(), SNAPSHOT_PREFIX, time_str,
418
322
                            sid, timeout_s);
419
322
    return res;
420
322
}
421
422
// prefix: /path/to/data/DATA_PREFIX/shard_id
423
// return: /path/to/data/DATA_PREFIX/shard_id/tablet_id/schema_hash
424
std::string SnapshotManager::get_schema_hash_full_path(const TabletSharedPtr& ref_tablet,
425
324
                                                       const std::string& prefix) {
426
324
    return fmt::format("{}/{}/{}", prefix, ref_tablet->tablet_id(), ref_tablet->schema_hash());
427
324
}
428
429
std::string SnapshotManager::_get_header_full_path(const TabletSharedPtr& ref_tablet,
430
322
                                                   const std::string& schema_hash_path) const {
431
322
    return fmt::format("{}/{}.hdr", schema_hash_path, ref_tablet->tablet_id());
432
322
}
433
434
std::string SnapshotManager::_get_json_header_full_path(const TabletSharedPtr& ref_tablet,
435
320
                                                        const std::string& schema_hash_path) const {
436
320
    return fmt::format("{}/{}.hdr.json", schema_hash_path, ref_tablet->tablet_id());
437
320
}
438
439
Status SnapshotManager::_link_index_and_data_files(
440
        const std::string& schema_hash_path, const TabletSharedPtr& ref_tablet,
441
0
        const std::vector<RowsetSharedPtr>& consistent_rowsets) {
442
0
    Status res = Status::OK();
443
0
    for (auto& rs : consistent_rowsets) {
444
0
        RETURN_IF_ERROR(rs->link_files_to(schema_hash_path, rs->rowset_id()));
445
0
    }
446
0
    return res;
447
0
}
448
449
Status SnapshotManager::_create_snapshot_files(const TabletSharedPtr& ref_tablet,
450
                                               const TabletSharedPtr& target_tablet,
451
                                               const TSnapshotRequest& request,
452
                                               string* snapshot_path,
453
322
                                               bool* allow_incremental_clone) {
454
322
    int32_t snapshot_version = request.preferred_snapshot_version;
455
322
    LOG(INFO) << "receive a make snapshot request"
456
322
              << ", request detail is " << apache::thrift::ThriftDebugString(request)
457
322
              << ", snapshot_version is " << snapshot_version;
458
322
    Status res = Status::OK();
459
322
    if (snapshot_path == nullptr) {
460
0
        return Status::Error<INVALID_ARGUMENT>("output parameter cannot be null");
461
0
    }
462
463
    // snapshot_id_path:
464
    //      /data/shard_id/tablet_id/snapshot/time_str/id.timeout/
465
322
    int64_t timeout_s = config::snapshot_expire_time_sec;
466
322
    if (request.__isset.timeout) {
467
320
        timeout_s = request.timeout;
468
320
    }
469
322
    std::string snapshot_id_path;
470
322
    res = _calc_snapshot_id_path(target_tablet, timeout_s, &snapshot_id_path);
471
322
    if (!res.ok()) {
472
0
        LOG(WARNING) << "failed to calc snapshot_id_path, tablet="
473
0
                     << target_tablet->data_dir()->path();
474
0
        return res;
475
0
    }
476
477
322
    bool is_copy_binlog = request.__isset.is_copy_binlog ? request.is_copy_binlog : false;
478
479
    // schema_full_path_desc.filepath:
480
    //      /snapshot_id_path/tablet_id/schema_hash/
481
322
    auto schema_full_path = get_schema_hash_full_path(target_tablet, snapshot_id_path);
482
    // header_path:
483
    //      /schema_full_path/tablet_id.hdr
484
322
    auto header_path = _get_header_full_path(target_tablet, schema_full_path);
485
    //      /schema_full_path/tablet_id.hdr.json
486
322
    auto json_header_path = _get_json_header_full_path(target_tablet, schema_full_path);
487
322
    bool exists = true;
488
322
    RETURN_IF_ERROR(io::global_local_filesystem()->exists(schema_full_path, &exists));
489
322
    if (exists) {
490
0
        VLOG_TRACE << "remove the old schema_full_path." << schema_full_path;
491
0
        RETURN_IF_ERROR(io::global_local_filesystem()->delete_directory(schema_full_path));
492
0
    }
493
494
322
    RETURN_IF_ERROR(io::global_local_filesystem()->create_directory(schema_full_path));
495
322
    string snapshot_id;
496
322
    RETURN_IF_ERROR(io::global_local_filesystem()->canonicalize(snapshot_id_path, &snapshot_id));
497
498
322
    std::vector<RowsetSharedPtr> consistent_rowsets;
499
322
    do {
500
322
        TabletMetaSharedPtr new_tablet_meta(new (nothrow) TabletMeta());
501
322
        if (new_tablet_meta == nullptr) {
502
0
            res = Status::Error<MEM_ALLOC_FAILED>("fail to malloc TabletMeta.");
503
0
            break;
504
0
        }
505
322
        DeleteBitmap delete_bitmap_snapshot(new_tablet_meta->tablet_id());
506
507
        /// If set missing_version, try to get all missing version.
508
        /// If some of them not exist in tablet, we will fall back to
509
        /// make the full snapshot of the tablet.
510
322
        {
511
322
            std::shared_lock rdlock(ref_tablet->get_header_lock());
512
322
            if (ref_tablet->tablet_state() == TABLET_SHUTDOWN) {
513
0
                return Status::Aborted("tablet has shutdown");
514
0
            }
515
322
            bool is_single_rowset_clone =
516
322
                    (request.__isset.start_version && request.__isset.end_version);
517
322
            if (is_single_rowset_clone) {
518
0
                LOG(INFO) << "handle compaction clone make snapshot, tablet_id: "
519
0
                          << ref_tablet->tablet_id();
520
0
                Version version(request.start_version, request.end_version);
521
0
                const RowsetSharedPtr rowset = ref_tablet->get_rowset_by_version(version, false);
522
0
                if (rowset && rowset->is_local()) {
523
0
                    consistent_rowsets.push_back(rowset);
524
0
                } else {
525
0
                    LOG(WARNING) << "failed to find local version when do compaction snapshot. "
526
0
                                 << " tablet=" << request.tablet_id
527
0
                                 << " schema_hash=" << request.schema_hash
528
0
                                 << " version=" << version;
529
0
                    res = Status::InternalError(
530
0
                            "failed to find version when do compaction snapshot");
531
0
                    break;
532
0
                }
533
0
            }
534
            // be would definitely set it as true no matter has missed version or not
535
            // but it would take no effects on the following range loop
536
322
            if (!is_single_rowset_clone && request.__isset.missing_version) {
537
0
                for (int64_t missed_version : request.missing_version) {
538
0
                    Version version = {missed_version, missed_version};
539
                    // find rowset in both rs_meta and stale_rs_meta
540
0
                    const RowsetSharedPtr rowset = ref_tablet->get_rowset_by_version(version, true);
541
0
                    if (rowset != nullptr) {
542
0
                        if (!rowset->is_local()) {
543
                            // MUST make full snapshot to ensure `cooldown_meta_id` is consistent with the cooldowned rowsets after clone.
544
0
                            res = Status::Error<ErrorCode::INTERNAL_ERROR>(
545
0
                                    "missed version is a cooldowned rowset, must make full "
546
0
                                    "snapshot. missed_version={}, tablet_id={}",
547
0
                                    missed_version, ref_tablet->tablet_id());
548
0
                            break;
549
0
                        }
550
0
                        consistent_rowsets.push_back(rowset);
551
0
                    } else {
552
0
                        res = Status::InternalError(
553
0
                                "failed to find missed version when snapshot. tablet={}, "
554
0
                                "schema_hash={}, version={}",
555
0
                                request.tablet_id, request.schema_hash, version.to_string());
556
0
                        break;
557
0
                    }
558
0
                }
559
0
            }
560
561
322
            DBUG_EXECUTE_IF("SnapshotManager.create_snapshot_files.allow_inc_clone", {
562
322
                auto tablet_id = dp->param("tablet_id", 0);
563
322
                auto is_full_clone = dp->param("is_full_clone", false);
564
322
                if (ref_tablet->tablet_id() == tablet_id && is_full_clone) {
565
322
                    LOG(INFO) << "injected full clone for tabelt: " << tablet_id;
566
322
                    res = Status::InternalError("fault injection error");
567
322
                }
568
322
            });
569
570
            // be would definitely set it as true no matter has missed version or not, we could
571
            // just check whether the missed version is empty or not
572
322
            int64_t version = -1;
573
322
            if (!is_single_rowset_clone && (!res.ok() || request.missing_version.empty())) {
574
322
                if (!request.__isset.missing_version &&
575
322
                    ref_tablet->tablet_meta()->cooldown_meta_id().initialized()) {
576
0
                    LOG(WARNING) << "currently not support backup tablet with cooldowned remote "
577
0
                                    "data. tablet="
578
0
                                 << request.tablet_id;
579
0
                    return Status::NotSupported(
580
0
                            "currently not support backup tablet with cooldowned remote data");
581
0
                }
582
                /// not all missing versions are found, fall back to full snapshot.
583
322
                res = Status::OK();         // reset res
584
322
                consistent_rowsets.clear(); // reset vector
585
586
                // get latest version
587
322
                const RowsetSharedPtr last_version = ref_tablet->get_rowset_with_max_version();
588
322
                if (last_version == nullptr) {
589
0
                    res = Status::InternalError("tablet has not any version. path={}",
590
0
                                                ref_tablet->tablet_id());
591
0
                    break;
592
0
                }
593
                // get snapshot version, use request.version if specified
594
322
                version = last_version->end_version();
595
322
                if (request.__isset.version) {
596
148
                    if (last_version->end_version() < request.version) {
597
0
                        res = Status::Error<INVALID_ARGUMENT>(
598
0
                                "invalid make snapshot request. version={}, req_version={}",
599
0
                                last_version->version().to_string(), request.version);
600
0
                        break;
601
0
                    }
602
148
                    version = request.version;
603
148
                }
604
322
                if (ref_tablet->tablet_meta()->cooldown_meta_id().initialized()) {
605
                    // Tablet has cooldowned data, MUST pick consistent rowsets with continuous cooldowned version
606
                    // Get max cooldowned version
607
0
                    int64_t max_cooldowned_version = -1;
608
0
                    for (auto& [v, rs] : ref_tablet->rowset_map()) {
609
0
                        if (rs->is_local()) {
610
0
                            continue;
611
0
                        }
612
0
                        consistent_rowsets.push_back(rs);
613
0
                        max_cooldowned_version = std::max(max_cooldowned_version, v.second);
614
0
                    }
615
0
                    DCHECK_GE(max_cooldowned_version, 1) << "tablet_id=" << ref_tablet->tablet_id();
616
0
                    std::sort(consistent_rowsets.begin(), consistent_rowsets.end(),
617
0
                              Rowset::comparator);
618
0
                    res = check_version_continuity(consistent_rowsets);
619
0
                    if (res.ok() && max_cooldowned_version < version) {
620
                        // Pick consistent rowsets of remaining required version
621
0
                        auto ret = ref_tablet->capture_consistent_rowsets_unlocked(
622
0
                                {max_cooldowned_version + 1, version}, CaptureRowsetOps {});
623
0
                        if (ret) {
624
0
                            consistent_rowsets = std::move(ret->rowsets);
625
0
                        } else {
626
0
                            res = std::move(ret.error());
627
0
                        }
628
0
                    }
629
322
                } else {
630
322
                    auto ret = ref_tablet->capture_consistent_rowsets_unlocked(Version(0, version),
631
322
                                                                               CaptureRowsetOps {});
632
322
                    if (ret) {
633
322
                        consistent_rowsets = std::move(ret->rowsets);
634
322
                    } else {
635
0
                        res = std::move(ret.error());
636
0
                    }
637
322
                }
638
322
                if (!res.ok()) {
639
0
                    LOG(WARNING) << "fail to select versions to span. res=" << res;
640
0
                    break;
641
0
                }
642
322
                *allow_incremental_clone = false;
643
322
            } else {
644
0
                version = ref_tablet->max_version_unlocked();
645
0
                *allow_incremental_clone = true;
646
0
            }
647
648
            // copy the tablet meta to new_tablet_meta inside header lock
649
322
            CHECK(res.ok()) << res;
650
322
            ref_tablet->generate_tablet_meta_copy_unlocked(*new_tablet_meta, false);
651
            // The delete bitmap update operation and the add_inc_rowset operation is not atomic,
652
            // so delete bitmap may contains some data generated by invisible rowset, we should
653
            // get rid of these useless bitmaps when doing snapshot.
654
322
            if (ref_tablet->keys_type() == UNIQUE_KEYS &&
655
322
                ref_tablet->enable_unique_key_merge_on_write()) {
656
40
                delete_bitmap_snapshot =
657
40
                        ref_tablet->tablet_meta()->delete_bitmap().snapshot(version);
658
40
            }
659
322
        }
660
661
0
        std::vector<RowsetMetaSharedPtr> rs_metas;
662
470
        for (auto& rs : consistent_rowsets) {
663
472
            if (rs->is_local()) {
664
                // local rowset
665
472
                res = rs->link_files_to(schema_full_path, rs->rowset_id());
666
472
                if (!res.ok()) {
667
0
                    break;
668
0
                }
669
472
            }
670
470
            rs_metas.push_back(rs->rowset_meta());
671
18.4E
            VLOG_NOTICE << "add rowset meta to clone list. "
672
18.4E
                        << " start version " << rs->rowset_meta()->start_version()
673
18.4E
                        << " end version " << rs->rowset_meta()->end_version() << " empty "
674
18.4E
                        << rs->rowset_meta()->empty();
675
470
        }
676
322
        if (!res.ok()) {
677
0
            LOG(WARNING) << "fail to create hard link. path=" << snapshot_id_path
678
0
                         << " tablet=" << target_tablet->tablet_id()
679
0
                         << " ref tablet=" << ref_tablet->tablet_id();
680
0
            break;
681
0
        }
682
683
        // The inc_rs_metas is deprecated since Doris version 0.13.
684
        // Clear it for safety reason.
685
        // Whether it is incremental or full snapshot, rowset information is stored in rs_meta.
686
322
        new_tablet_meta->revise_rs_metas(std::move(rs_metas));
687
322
        if (ref_tablet->keys_type() == UNIQUE_KEYS &&
688
322
            ref_tablet->enable_unique_key_merge_on_write()) {
689
40
            new_tablet_meta->revise_delete_bitmap_unlocked(delete_bitmap_snapshot);
690
40
        }
691
692
322
        if (snapshot_version == g_Types_constants.TSNAPSHOT_REQ_VERSION2) {
693
320
            res = new_tablet_meta->save(header_path);
694
320
            if (res.ok() && request.__isset.is_copy_tablet_task && request.is_copy_tablet_task) {
695
0
                res = new_tablet_meta->save_as_json(json_header_path);
696
0
            }
697
320
        } else {
698
2
            res = Status::Error<INVALID_SNAPSHOT_VERSION>(
699
2
                    "snapshot_version not equal to g_Types_constants.TSNAPSHOT_REQ_VERSION2");
700
2
        }
701
702
322
        if (!res.ok()) {
703
0
            LOG(WARNING) << "convert rowset failed, res:" << res
704
0
                         << ", tablet:" << new_tablet_meta->tablet_id()
705
0
                         << ", schema hash:" << new_tablet_meta->schema_hash()
706
0
                         << ", snapshot_version:" << snapshot_version
707
0
                         << ", is incremental:" << request.__isset.missing_version;
708
0
            break;
709
0
        }
710
711
322
    } while (false);
712
713
    // link all binlog files to snapshot path
714
322
    do {
715
322
        if (!res.ok()) {
716
0
            break;
717
0
        }
718
719
322
        if (!is_copy_binlog || !target_tablet->enable_ccr_binlog()) {
720
314
            break;
721
314
        }
722
723
8
        RowsetBinlogMetasPB rowset_binlog_metas_pb;
724
8
        for (auto& rs : consistent_rowsets) {
725
0
            if (!rs->is_local()) {
726
0
                continue;
727
0
            }
728
0
            res = ref_tablet->get_rowset_binlog_metas(rs->version(), &rowset_binlog_metas_pb);
729
0
            if (!res.ok()) {
730
0
                break;
731
0
            }
732
0
        }
733
8
        if (!res.ok() || rowset_binlog_metas_pb.rowset_binlog_metas_size() == 0) {
734
0
            break;
735
0
        }
736
737
        // write to pb file
738
8
        auto rowset_binlog_metas_pb_filename =
739
8
                fmt::format("{}/rowset_binlog_metas.pb", schema_full_path);
740
8
        res = write_pb(rowset_binlog_metas_pb_filename, rowset_binlog_metas_pb);
741
8
        if (!res.ok()) {
742
0
            break;
743
0
        }
744
745
8
        for (const auto& rowset_binlog_meta : rowset_binlog_metas_pb.rowset_binlog_metas()) {
746
0
            std::string segment_file_path;
747
0
            auto num_segments = rowset_binlog_meta.num_segments();
748
0
            std::string_view rowset_id = rowset_binlog_meta.rowset_id();
749
750
0
            RowsetMetaPB rowset_meta_pb;
751
0
            if (!rowset_meta_pb.ParseFromString(rowset_binlog_meta.data())) {
752
0
                auto err_msg = fmt::format("fail to parse binlog meta data value:{}",
753
0
                                           rowset_binlog_meta.data());
754
0
                res = Status::InternalError(err_msg);
755
0
                LOG(WARNING) << err_msg;
756
0
                return res;
757
0
            }
758
0
            const auto& tablet_schema_pb = rowset_meta_pb.tablet_schema();
759
0
            TabletSchema tablet_schema;
760
0
            tablet_schema.init_from_pb(tablet_schema_pb);
761
762
0
            std::vector<string> linked_success_files;
763
0
            Defer remove_linked_files {[&]() { // clear linked files if errors happen
764
0
                if (!res.ok()) {
765
0
                    LOG(WARNING) << "will delete linked success files due to error " << res;
766
0
                    std::vector<io::Path> paths;
767
0
                    for (auto& file : linked_success_files) {
768
0
                        paths.emplace_back(file);
769
0
                        LOG(WARNING)
770
0
                                << "will delete linked success file " << file << " due to error";
771
0
                    }
772
0
                    static_cast<void>(io::global_local_filesystem()->batch_delete(paths));
773
0
                    LOG(WARNING) << "done delete linked success files due to error " << res;
774
0
                }
775
0
            }};
776
777
            // link segment files and index files
778
0
            for (int64_t segment_index = 0; segment_index < num_segments; ++segment_index) {
779
0
                segment_file_path = ref_tablet->get_segment_filepath(rowset_id, segment_index);
780
0
                auto snapshot_segment_file_path =
781
0
                        fmt::format("{}/{}_{}.binlog", schema_full_path, rowset_id, segment_index);
782
783
0
                res = io::global_local_filesystem()->link_file(segment_file_path,
784
0
                                                               snapshot_segment_file_path);
785
0
                if (!res.ok()) {
786
0
                    LOG(WARNING) << "fail to link binlog file. [src=" << segment_file_path
787
0
                                 << ", dest=" << snapshot_segment_file_path << "]";
788
0
                    break;
789
0
                }
790
0
                linked_success_files.push_back(snapshot_segment_file_path);
791
792
0
                if (tablet_schema.get_inverted_index_storage_format() ==
793
0
                    InvertedIndexStorageFormatPB::V1) {
794
0
                    for (const auto& index : tablet_schema.inverted_indexes()) {
795
0
                        auto index_id = index->index_id();
796
0
                        auto index_file = InvertedIndexDescriptor::get_index_file_path_v1(
797
0
                                InvertedIndexDescriptor::get_index_file_path_prefix(
798
0
                                        segment_file_path),
799
0
                                index_id, index->get_index_suffix());
800
0
                        auto snapshot_segment_index_file_path =
801
0
                                fmt::format("{}/{}_{}_{}.binlog-index", schema_full_path, rowset_id,
802
0
                                            segment_index, index_id);
803
0
                        VLOG_DEBUG << "link " << index_file << " to "
804
0
                                   << snapshot_segment_index_file_path;
805
0
                        res = io::global_local_filesystem()->link_file(
806
0
                                index_file, snapshot_segment_index_file_path);
807
0
                        if (!res.ok()) {
808
0
                            LOG(WARNING) << "fail to link binlog index file. [src=" << index_file
809
0
                                         << ", dest=" << snapshot_segment_index_file_path << "]";
810
0
                            break;
811
0
                        }
812
0
                        linked_success_files.push_back(snapshot_segment_index_file_path);
813
0
                    }
814
0
                } else {
815
0
                    if (tablet_schema.has_inverted_index() || tablet_schema.has_ann_index()) {
816
0
                        auto index_file = InvertedIndexDescriptor::get_index_file_path_v2(
817
0
                                InvertedIndexDescriptor::get_index_file_path_prefix(
818
0
                                        segment_file_path));
819
0
                        auto snapshot_segment_index_file_path =
820
0
                                fmt::format("{}/{}_{}.binlog-index", schema_full_path, rowset_id,
821
0
                                            segment_index);
822
0
                        VLOG_DEBUG << "link " << index_file << " to "
823
0
                                   << snapshot_segment_index_file_path;
824
0
                        res = io::global_local_filesystem()->link_file(
825
0
                                index_file, snapshot_segment_index_file_path);
826
0
                        if (!res.ok()) {
827
0
                            LOG(WARNING) << "fail to link binlog index file. [src=" << index_file
828
0
                                         << ", dest=" << snapshot_segment_index_file_path << "]";
829
0
                            break;
830
0
                        }
831
0
                        linked_success_files.push_back(snapshot_segment_index_file_path);
832
0
                    }
833
0
                }
834
0
            }
835
836
0
            if (!res.ok()) {
837
0
                break;
838
0
            }
839
0
        }
840
8
    } while (false);
841
842
322
    if (!res.ok()) {
843
0
        LOG(WARNING) << "fail to make snapshot, try to delete the snapshot path. path="
844
0
                     << snapshot_id_path.c_str();
845
846
0
        bool exist = true;
847
0
        RETURN_IF_ERROR(io::global_local_filesystem()->exists(snapshot_id_path, &exist));
848
0
        if (exist) {
849
0
            VLOG_NOTICE << "remove snapshot path. [path=" << snapshot_id_path << "]";
850
0
            RETURN_IF_ERROR(io::global_local_filesystem()->delete_directory(snapshot_id_path));
851
0
        }
852
322
    } else {
853
322
        *snapshot_path = snapshot_id;
854
322
    }
855
856
322
    return res;
857
322
}
858
} // namespace doris