Coverage Report

Created: 2024-11-20 16:51

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