Coverage Report

Created: 2025-04-22 23:04

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