Coverage Report

Created: 2026-04-20 20:34

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