Coverage Report

Created: 2025-07-27 01:30

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