Coverage Report

Created: 2026-08-06 14:04

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/storage/task/engine_clone_task.cpp
Line
Count
Source
1
// Licensed to the Apache Software Foundation (ASF) under one
2
// or more contributor license agreements.  See the NOTICE file
3
// distributed with this work for additional information
4
// regarding copyright ownership.  The ASF licenses this file
5
// to you under the Apache License, Version 2.0 (the
6
// "License"); you may not use this file except in compliance
7
// with the License.  You may obtain a copy of the License at
8
//
9
//   http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied.  See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
18
#include "storage/task/engine_clone_task.h"
19
20
#include <absl/strings/str_split.h>
21
#include <curl/curl.h>
22
#include <fcntl.h>
23
#include <fmt/format.h>
24
#include <gen_cpp/AgentService_types.h>
25
#include <gen_cpp/BackendService.h>
26
#include <gen_cpp/HeartbeatService_types.h>
27
#include <gen_cpp/MasterService_types.h>
28
#include <gen_cpp/Status_types.h>
29
#include <gen_cpp/Types_constants.h>
30
#include <sys/stat.h>
31
32
#include <filesystem>
33
#include <memory>
34
#include <mutex>
35
#include <ostream>
36
#include <shared_mutex>
37
#include <system_error>
38
#include <unordered_map>
39
#include <unordered_set>
40
#include <utility>
41
#include <vector>
42
43
#include "common/config.h"
44
#include "common/logging.h"
45
#include "io/fs/file_system.h"
46
#include "io/fs/local_file_system.h"
47
#include "io/fs/path.h"
48
#include "runtime/cluster_info.h"
49
#include "runtime/memory/mem_tracker_limiter.h"
50
#include "runtime/thread_context.h"
51
#include "service/http/http_client.h"
52
#include "service/http/utils.h"
53
#include "storage/binlog.h"
54
#include "storage/data_dir.h"
55
#include "storage/olap_common.h"
56
#include "storage/olap_define.h"
57
#include "storage/pb_helper.h"
58
#include "storage/rowset/rowset.h"
59
#include "storage/snapshot/snapshot_manager.h"
60
#include "storage/storage_engine.h"
61
#include "storage/tablet/tablet.h"
62
#include "storage/tablet/tablet_manager.h"
63
#include "storage/tablet/tablet_meta.h"
64
#include "util/client_cache.h"
65
#include "util/debug_points.h"
66
#include "util/defer_op.h"
67
#include "util/network_util.h"
68
#include "util/security.h"
69
#include "util/stopwatch.hpp"
70
#include "util/thrift_rpc_helper.h"
71
#include "util/trace.h"
72
73
using std::stringstream;
74
75
namespace doris {
76
using namespace ErrorCode;
77
78
namespace {
79
/// if binlog file exist, then check if binlog file md5sum equal
80
/// if equal, then skip link file
81
/// if not equal, then return error
82
/// return value: if binlog file not exist, then return to binlog file path
83
Result<std::string> check_dest_binlog_valid(const std::string& tablet_dir,
84
                                            const std::string& clone_dir,
85
0
                                            const std::string& clone_file, bool* skip_link_file) {
86
0
    std::string from, to;
87
0
    std::string new_clone_file = clone_file;
88
0
    if (clone_file.ends_with(".binlog")) {
89
        // change clone_file suffix from .binlog to .dat
90
0
        new_clone_file.replace(clone_file.size() - 7, 7, ".dat");
91
0
    } else if (clone_file.ends_with(".binlog-index")) {
92
        // change clone_file suffix from .binlog-index to .idx
93
0
        new_clone_file.replace(clone_file.size() - 13, 13, ".idx");
94
0
    }
95
0
    from = fmt::format("{}/{}", clone_dir, clone_file);
96
0
    to = fmt::format("{}/_binlog/{}", tablet_dir, new_clone_file);
97
98
    // check to to file exist
99
0
    bool exists = true;
100
0
    auto status = io::global_local_filesystem()->exists(to, &exists);
101
0
    if (!status.ok()) {
102
0
        return ResultError(std::move(status));
103
0
    }
104
105
0
    if (!exists) {
106
0
        return to;
107
0
    }
108
109
0
    LOG(WARNING) << "binlog file already exist. "
110
0
                 << "tablet_dir=" << tablet_dir << ", clone_file=" << from << ", to=" << to;
111
112
0
    std::string clone_file_md5sum;
113
0
    status = io::global_local_filesystem()->md5sum(from, &clone_file_md5sum);
114
0
    if (!status.ok()) {
115
0
        return ResultError(std::move(status));
116
0
    }
117
0
    std::string to_file_md5sum;
118
0
    status = io::global_local_filesystem()->md5sum(to, &to_file_md5sum);
119
0
    if (!status.ok()) {
120
0
        return ResultError(std::move(status));
121
0
    }
122
123
0
    if (clone_file_md5sum == to_file_md5sum) {
124
        // if md5sum equal, then skip link file
125
0
        *skip_link_file = true;
126
0
        return to;
127
0
    } else {
128
0
        auto err_msg = fmt::format(
129
0
                "binlog file already exist, but md5sum not equal. "
130
0
                "tablet_dir={}, clone_file={}",
131
0
                tablet_dir, clone_file);
132
0
        LOG(WARNING) << err_msg;
133
0
        return ResultError(Status::InternalError(std::move(err_msg)));
134
0
    }
135
0
}
136
} // namespace
137
138
#define RETURN_IF_ERROR_(status, stmt) \
139
0
    do {                               \
140
0
        status = (stmt);               \
141
0
        if (UNLIKELY(!status.ok())) {  \
142
0
            return status;             \
143
0
        }                              \
144
0
    } while (false)
145
146
EngineCloneTask::EngineCloneTask(StorageEngine& engine, const TCloneReq& clone_req,
147
                                 const ClusterInfo* cluster_info, int64_t signature,
148
                                 std::vector<TTabletInfo>* tablet_infos)
149
0
        : _engine(engine),
150
0
          _clone_req(clone_req),
151
0
          _tablet_infos(tablet_infos),
152
0
          _signature(signature),
153
0
          _cluster_info(cluster_info) {
154
0
    _mem_tracker = MemTrackerLimiter::create_shared(
155
0
            MemTrackerLimiter::Type::OTHER,
156
0
            "EngineCloneTask#tabletId=" + std::to_string(_clone_req.tablet_id));
157
0
}
158
159
0
Status EngineCloneTask::execute() {
160
    // register the tablet to avoid it is deleted by gc thread during clone process
161
0
    Status st = _do_clone();
162
0
    _engine.tablet_manager()->update_partitions_visible_version(
163
0
            {{_clone_req.partition_id, _clone_req.version}});
164
0
    return st;
165
0
}
166
167
0
Status EngineCloneTask::_do_clone() {
168
0
    DBUG_EXECUTE_IF("EngineCloneTask.wait_clone", {
169
0
        auto duration = std::chrono::milliseconds(dp->param("duration", 10 * 1000));
170
0
        std::this_thread::sleep_for(duration);
171
0
    });
172
173
0
    DBUG_EXECUTE_IF("EngineCloneTask.failed_clone", {
174
0
        LOG_WARNING("EngineCloneTask.failed_clone")
175
0
                .tag("tablet_id", _clone_req.tablet_id)
176
0
                .tag("replica_id", _clone_req.replica_id)
177
0
                .tag("version", _clone_req.version);
178
0
        return Status::InternalError(
179
0
                "in debug point, EngineCloneTask.failed_clone tablet={}, replica={}, version={}",
180
0
                _clone_req.tablet_id, _clone_req.replica_id, _clone_req.version);
181
0
    });
182
0
    Status status = Status::OK();
183
0
    std::string src_file_path;
184
0
    TBackend src_host;
185
0
    int32_t copy_type =
186
0
            _clone_req.__isset.copy_type ? _clone_req.copy_type : TabletCopyType::DEFAULT;
187
0
    RETURN_IF_ERROR(TabletCopyType::validate(copy_type));
188
0
    bool copy_row_binlog = TabletCopyType::has(copy_type, TTabletCopyType::ROW_BINLOG);
189
0
    RETURN_IF_ERROR(
190
0
            _engine.tablet_manager()->register_transition_tablet(_clone_req.tablet_id, "clone"));
191
0
    Defer defer {[&]() {
192
0
        _engine.tablet_manager()->unregister_transition_tablet(_clone_req.tablet_id, "clone");
193
0
    }};
194
195
    // Check local tablet exist or not
196
0
    TabletSharedPtr tablet = _engine.tablet_manager()->get_tablet(_clone_req.tablet_id);
197
198
    // The status of a tablet is not ready, indicating that it is a residual tablet after a schema
199
    // change failure. Clone a new tablet from remote be to overwrite it. This situation basically only
200
    // occurs when the be_rebalancer_fuzzy_test configuration is enabled.
201
0
    if (tablet && tablet->tablet_state() == TABLET_NOTREADY) {
202
0
        LOG(WARNING) << "tablet state is not ready when clone, need to drop old tablet, tablet_id="
203
0
                     << tablet->tablet_id();
204
0
        RETURN_IF_ERROR(_engine.tablet_manager()->drop_tablet(tablet->tablet_id(),
205
0
                                                              tablet->replica_id(), false));
206
0
        tablet.reset();
207
0
    }
208
0
    _is_new_tablet = tablet == nullptr;
209
    // try to incremental clone
210
0
    Versions missed_versions;
211
    // try to repair a tablet with missing version
212
0
    if (tablet != nullptr) {
213
0
        std::shared_lock migration_rlock(tablet->get_migration_lock(), std::try_to_lock);
214
0
        if (!migration_rlock.owns_lock()) {
215
0
            return Status::Error<TRY_LOCK_FAILED>(
216
0
                    "EngineCloneTask::_do_clone meet try lock failed");
217
0
        }
218
0
        if (tablet->replica_id() < _clone_req.replica_id) {
219
            // `tablet` may be a dropped replica in FE, e.g:
220
            //   BE1 migrates replica of tablet_1 to BE2, but before BE1 drop this replica, another new replica of tablet_1 is migrated to BE1.
221
            // Clone can still continue in this case. But to keep `replica_id` consitent with FE, MUST reset `replica_id` with request `replica_id`.
222
0
            tablet->tablet_meta()->set_replica_id(_clone_req.replica_id);
223
0
        }
224
225
        // get download path
226
0
        auto local_data_path = fmt::format("{}/{}", tablet->tablet_path(), CLONE_PREFIX);
227
0
        bool allow_incremental_clone = false;
228
229
0
        int64_t specified_version = _clone_req.version;
230
0
        if (tablet->enable_unique_key_merge_on_write()) {
231
0
            int64_t min_pending_ver = _engine.get_pending_publish_min_version(tablet->tablet_id());
232
0
            if (min_pending_ver - 1 < specified_version) {
233
0
                LOG(INFO) << "use min pending publish version for clone, min_pending_ver: "
234
0
                          << min_pending_ver << " visible_version: " << _clone_req.version;
235
0
                specified_version = min_pending_ver - 1;
236
0
            }
237
0
        }
238
239
0
        missed_versions = tablet->get_missed_versions(specified_version);
240
241
        // if missed version size is 0, then it is useless to clone from remote be, it means local data is
242
        // completed. Or remote be will just return header not the rowset files. clone will failed.
243
0
        if (missed_versions.empty()) {
244
0
            LOG(INFO) << "missed version size = 0, skip clone and return success. tablet_id="
245
0
                      << _clone_req.tablet_id << " replica_id=" << _clone_req.replica_id;
246
0
            RETURN_IF_ERROR(_set_tablet_info());
247
0
            return Status::OK();
248
0
        }
249
250
0
        LOG(INFO) << "clone to existed tablet. missed_versions_size=" << missed_versions.size()
251
0
                  << ", allow_incremental_clone=" << allow_incremental_clone
252
0
                  << ", signature=" << _signature << ", tablet_id=" << _clone_req.tablet_id
253
0
                  << ", visible_version=" << _clone_req.version
254
0
                  << ", replica_id=" << _clone_req.replica_id;
255
256
        // try to download missing version from src backend.
257
        // if tablet on src backend does not contains missing version, it will download all versions,
258
        // and set allow_incremental_clone to false
259
0
        RETURN_IF_ERROR(_make_and_download_snapshots(*(tablet->data_dir()), local_data_path,
260
0
                                                     &src_host, &src_file_path, missed_versions,
261
0
                                                     &allow_incremental_clone));
262
0
        RETURN_IF_ERROR(_finish_clone(tablet.get(), local_data_path, specified_version,
263
0
                                      allow_incremental_clone, copy_row_binlog));
264
0
    } else {
265
0
        LOG(INFO) << "clone tablet not exist, begin clone a new tablet from remote be. "
266
0
                  << "signature=" << _signature << ", tablet_id=" << _clone_req.tablet_id
267
0
                  << ", visible_version=" << _clone_req.version
268
0
                  << ", req replica=" << _clone_req.replica_id;
269
        // create a new tablet in this be
270
        // Get local disk from olap
271
0
        std::string local_shard_root_path;
272
0
        DataDir* store = nullptr;
273
0
        RETURN_IF_ERROR(_engine.obtain_shard_path(_clone_req.storage_medium,
274
0
                                                  _clone_req.dest_path_hash, &local_shard_root_path,
275
0
                                                  &store, _clone_req.partition_id));
276
0
        auto tablet_dir = fmt::format("{}/{}/{}", local_shard_root_path, _clone_req.tablet_id,
277
0
                                      _clone_req.schema_hash);
278
279
0
        Defer remove_useless_dir {[&] {
280
0
            if (status.ok()) {
281
0
                return;
282
0
            }
283
0
            LOG(INFO) << "clone failed. want to delete local dir: " << tablet_dir
284
0
                      << ". signature: " << _signature;
285
0
            WARN_IF_ERROR(io::global_local_filesystem()->delete_directory(tablet_dir),
286
0
                          "failed to delete useless clone dir ");
287
0
            WARN_IF_ERROR(DataDir::delete_tablet_parent_path_if_empty(tablet_dir),
288
0
                          "failed to delete parent dir");
289
0
        }};
290
291
0
        bool exists = true;
292
0
        Status exists_st = io::global_local_filesystem()->exists(tablet_dir, &exists);
293
0
        if (!exists_st) {
294
0
            LOG(WARNING) << "cant get path=" << tablet_dir << " state, st=" << exists_st;
295
0
            return exists_st;
296
0
        }
297
0
        if (exists) {
298
0
            LOG(WARNING) << "before clone dest path=" << tablet_dir << " exist, remove it first";
299
0
            RETURN_IF_ERROR(io::global_local_filesystem()->delete_directory(tablet_dir));
300
0
        }
301
302
0
        bool allow_incremental_clone = false;
303
0
        RETURN_IF_ERROR_(status,
304
0
                         _make_and_download_snapshots(*store, tablet_dir, &src_host, &src_file_path,
305
0
                                                      missed_versions, &allow_incremental_clone));
306
307
0
        LOG(INFO) << "clone copy done. src_host: " << src_host.host
308
0
                  << " src_file_path: " << src_file_path;
309
0
        auto tablet_manager = _engine.tablet_manager();
310
0
        RETURN_IF_ERROR_(status, tablet_manager->load_tablet_from_dir(store, _clone_req.tablet_id,
311
0
                                                                      _clone_req.schema_hash,
312
0
                                                                      tablet_dir, false));
313
0
        auto nested_tablet = tablet_manager->get_tablet(_clone_req.tablet_id);
314
0
        if (!nested_tablet) {
315
0
            status = Status::NotFound("tablet not found, tablet_id={}", _clone_req.tablet_id);
316
0
            return status;
317
0
        }
318
        // MUST reset `replica_id` to request `replica_id` to keep consistent with FE
319
0
        nested_tablet->tablet_meta()->set_replica_id(_clone_req.replica_id);
320
        // clone success, delete .hdr file because tablet meta is stored in rocksdb
321
0
        std::string header_path =
322
0
                TabletMeta::construct_header_file_path(tablet_dir, _clone_req.tablet_id);
323
0
        RETURN_IF_ERROR(io::global_local_filesystem()->delete_file(header_path));
324
0
    }
325
326
0
    return _set_tablet_info();
327
0
}
328
329
0
Status EngineCloneTask::_set_tablet_info() {
330
    // Get clone tablet info
331
0
    TTabletInfo tablet_info;
332
0
    tablet_info.__set_tablet_id(_clone_req.tablet_id);
333
0
    tablet_info.__set_replica_id(_clone_req.replica_id);
334
0
    tablet_info.__set_schema_hash(_clone_req.schema_hash);
335
0
    RETURN_IF_ERROR(_engine.tablet_manager()->report_tablet_info(&tablet_info));
336
0
    if (_clone_req.__isset.version && tablet_info.version < _clone_req.version) {
337
        // if it is a new tablet and clone failed, then remove the tablet
338
        // if it is incremental clone, then must not drop the tablet
339
0
        if (_is_new_tablet) {
340
            // we need to check if this cloned table's version is what we expect.
341
            // if not, maybe this is a stale remaining table which is waiting for drop.
342
            // we drop it.
343
0
            LOG(WARNING) << "begin to drop the stale tablet. tablet_id:" << _clone_req.tablet_id
344
0
                         << ", replica_id:" << _clone_req.replica_id
345
0
                         << ", schema_hash:" << _clone_req.schema_hash
346
0
                         << ", signature:" << _signature << ", version:" << tablet_info.version
347
0
                         << ", expected_version: " << _clone_req.version;
348
0
            WARN_IF_ERROR(_engine.tablet_manager()->drop_tablet(_clone_req.tablet_id,
349
0
                                                                _clone_req.replica_id, false),
350
0
                          "drop stale cloned table failed");
351
0
        }
352
0
        return Status::InternalError("unexpected version. tablet version: {}, expected version: {}",
353
0
                                     tablet_info.version, _clone_req.version);
354
0
    }
355
0
    LOG(INFO) << "clone get tablet info success. tablet_id:" << _clone_req.tablet_id
356
0
              << ", schema_hash:" << _clone_req.schema_hash << ", signature:" << _signature
357
0
              << ", replica id:" << _clone_req.replica_id << ", version:" << tablet_info.version;
358
0
    _tablet_infos->push_back(tablet_info);
359
0
    return Status::OK();
360
0
}
361
362
/// This method will do following things:
363
/// 1. Make snapshots on source BE.
364
/// 2. Download all snapshots to CLONE dir.
365
/// 3. Convert rowset ids of downloaded snapshots(would also change the replica id).
366
/// 4. Release the snapshots on source BE.
367
Status EngineCloneTask::_make_and_download_snapshots(DataDir& data_dir,
368
                                                     const std::string& local_data_path,
369
                                                     TBackend* src_host, std::string* snapshot_path,
370
                                                     const std::vector<Version>& missed_versions,
371
0
                                                     bool* allow_incremental_clone) {
372
0
    Status status;
373
374
0
    const auto& token = _cluster_info->token;
375
376
0
    int timeout_s = 0;
377
0
    if (_clone_req.__isset.timeout_s) {
378
0
        timeout_s = _clone_req.timeout_s;
379
0
    }
380
381
0
    for (auto&& src : _clone_req.src_backends) {
382
        // Make snapshot in remote olap engine
383
0
        *src_host = src;
384
        // make snapshot
385
0
        status = _make_snapshot(src.host, src.be_port, _clone_req.tablet_id, _clone_req.schema_hash,
386
0
                                timeout_s, missed_versions, snapshot_path, allow_incremental_clone);
387
0
        if (!status.ok()) [[unlikely]] {
388
0
            LOG_WARNING("failed to make snapshot in remote BE")
389
0
                    .tag("host", src.host)
390
0
                    .tag("port", src.be_port)
391
0
                    .tag("tablet", _clone_req.tablet_id)
392
0
                    .tag("signature", _signature)
393
0
                    .tag("missed_versions", missed_versions)
394
0
                    .error(status);
395
0
            continue; // Try another BE
396
0
        }
397
0
        LOG_INFO("successfully make snapshot in remote BE")
398
0
                .tag("host", src.host)
399
0
                .tag("port", src.be_port)
400
0
                .tag("tablet", _clone_req.tablet_id)
401
0
                .tag("snapshot_path", *snapshot_path)
402
0
                .tag("signature", _signature)
403
0
                .tag("missed_versions", missed_versions);
404
0
        Defer defer {[host = src.host, port = src.be_port, &snapshot_path = *snapshot_path, this] {
405
            // TODO(plat1ko): Async release snapshot
406
0
            auto st = _release_snapshot(host, port, snapshot_path);
407
0
            if (!st.ok()) [[unlikely]] {
408
0
                LOG_WARNING("failed to release snapshot in remote BE")
409
0
                        .tag("host", host)
410
0
                        .tag("port", port)
411
0
                        .tag("snapshot_path", snapshot_path)
412
0
                        .error(st);
413
0
            }
414
0
        }};
415
416
0
        std::string remote_dir;
417
0
        {
418
0
            std::stringstream ss;
419
0
            if (snapshot_path->back() == '/') {
420
0
                ss << *snapshot_path << _clone_req.tablet_id << "/" << _clone_req.schema_hash
421
0
                   << "/";
422
0
            } else {
423
0
                ss << *snapshot_path << "/" << _clone_req.tablet_id << "/" << _clone_req.schema_hash
424
0
                   << "/";
425
0
            }
426
0
            remote_dir = ss.str();
427
0
        }
428
429
0
        std::string address = get_host_port(src.host, src.http_port);
430
0
        int32_t copy_type =
431
0
                _clone_req.__isset.copy_type ? _clone_req.copy_type : TabletCopyType::DEFAULT;
432
0
        RETURN_IF_ERROR(TabletCopyType::validate(copy_type));
433
0
        bool copy_row_binlog = TabletCopyType::has(copy_type, TTabletCopyType::ROW_BINLOG);
434
435
0
        if (config::enable_batch_download && is_support_batch_download(address).ok()) {
436
            // download files via batch api.
437
0
            LOG_INFO("remote BE supports batch download, use batch file download")
438
0
                    .tag("address", address)
439
0
                    .tag("remote_dir", remote_dir);
440
0
            status = _batch_download_files(&data_dir, address, remote_dir, local_data_path);
441
0
            if (!status.ok()) [[unlikely]] {
442
0
                LOG_WARNING("failed to download snapshot from remote BE in batch")
443
0
                        .tag("address", address)
444
0
                        .tag("remote_dir", remote_dir)
445
0
                        .error(status);
446
0
                continue; // Try another BE
447
0
            }
448
0
            if (copy_row_binlog) {
449
0
                std::string row_binlog_remote_dir =
450
0
                        fmt::format("{}{}/", remote_dir, FDRowBinlogSuffix);
451
0
                std::string row_binlog_local_path =
452
0
                        fmt::format("{}/{}", local_data_path, FDRowBinlogSuffix);
453
0
                status = _batch_download_files(&data_dir, address, row_binlog_remote_dir,
454
0
                                               row_binlog_local_path);
455
0
                if (!status.ok()) [[unlikely]] {
456
0
                    LOG_WARNING("failed to download row binlog snapshot from remote BE in batch")
457
0
                            .tag("address", address)
458
0
                            .tag("remote_dir", row_binlog_remote_dir)
459
0
                            .error(status);
460
0
                    continue; // Try another BE
461
0
                }
462
0
            }
463
0
        } else {
464
0
            if (config::enable_batch_download) {
465
0
                LOG_INFO("remote BE does not support batch download, use single file download")
466
0
                        .tag("address", address)
467
0
                        .tag("remote_dir", remote_dir);
468
0
            } else {
469
0
                LOG_INFO("batch download is disabled, use single file download")
470
0
                        .tag("address", address)
471
0
                        .tag("remote_dir", remote_dir);
472
0
            }
473
474
0
            std::string remote_url_prefix;
475
0
            {
476
0
                std::stringstream ss;
477
0
                ss << "http://" << address << HTTP_REQUEST_PREFIX << HTTP_REQUEST_TOKEN_PARAM
478
0
                   << token << HTTP_REQUEST_FILE_PARAM << remote_dir;
479
0
                remote_url_prefix = ss.str();
480
0
            }
481
482
0
            status = _download_files(&data_dir, remote_url_prefix, local_data_path);
483
0
            if (!status.ok()) [[unlikely]] {
484
0
                LOG_WARNING("failed to download snapshot from remote BE")
485
0
                        .tag("url", mask_token(remote_url_prefix))
486
0
                        .error(status);
487
0
                continue; // Try another BE
488
0
            }
489
0
            if (copy_row_binlog) {
490
0
                std::string row_binlog_remote_url_prefix;
491
0
                {
492
0
                    std::stringstream ss;
493
0
                    ss << "http://" << address << HTTP_REQUEST_PREFIX << HTTP_REQUEST_TOKEN_PARAM
494
0
                       << token << HTTP_REQUEST_FILE_PARAM << remote_dir << FDRowBinlogSuffix
495
0
                       << "/";
496
0
                    row_binlog_remote_url_prefix = ss.str();
497
0
                }
498
0
                std::string row_binlog_local_path =
499
0
                        fmt::format("{}/{}", local_data_path, FDRowBinlogSuffix);
500
0
                status = _download_files(&data_dir, row_binlog_remote_url_prefix,
501
0
                                         row_binlog_local_path);
502
0
                if (!status.ok()) [[unlikely]] {
503
0
                    LOG_WARNING("failed to download row binlog snapshot from remote BE")
504
0
                            .tag("url", mask_token(row_binlog_remote_url_prefix))
505
0
                            .error(status);
506
0
                    continue; // Try another BE
507
0
                }
508
0
            }
509
0
        }
510
511
        // No need to try again with another BE
512
0
        _pending_rs_guards = DORIS_TRY(_engine.snapshot_mgr()->convert_rowset_ids(
513
0
                local_data_path, _clone_req.tablet_id, _clone_req.replica_id, _clone_req.table_id,
514
0
                _clone_req.partition_id, _clone_req.schema_hash));
515
0
        break;
516
0
    } // clone copy from one backend
517
0
    return status;
518
0
}
519
520
Status EngineCloneTask::_make_snapshot(const std::string& ip, int port, TTableId tablet_id,
521
                                       TSchemaHash schema_hash, int timeout_s,
522
                                       const std::vector<Version>& missed_versions,
523
0
                                       std::string* snapshot_path, bool* allow_incremental_clone) {
524
0
    TSnapshotRequest request;
525
0
    request.__set_tablet_id(tablet_id);
526
0
    request.__set_schema_hash(schema_hash);
527
0
    request.__set_preferred_snapshot_version(g_Types_constants.TPREFER_SNAPSHOT_REQ_VERSION);
528
0
    request.__set_version(_clone_req.version);
529
0
    int32_t copy_type =
530
0
            _clone_req.__isset.copy_type ? _clone_req.copy_type : TabletCopyType::DEFAULT;
531
0
    RETURN_IF_ERROR(TabletCopyType::validate(copy_type));
532
0
    request.__set_copy_type(copy_type);
533
0
    request.__set_is_copy_binlog(TabletCopyType::has(copy_type, TTabletCopyType::CCR_BINLOG));
534
    // TODO: missing version composed of singleton delta.
535
    // if not, this place should be rewrote.
536
    // we make every TSnapshotRequest sent from be with __isset.missing_version = true
537
    // then if one be received one req with __isset.missing_version = false it means
538
    // this req is sent from FE(FE would never set this field)
539
0
    request.__isset.missing_version = true;
540
0
    for (auto& version : missed_versions) {
541
0
        request.missing_version.push_back(version.first);
542
0
    }
543
0
    if (timeout_s > 0) {
544
0
        request.__set_timeout(timeout_s);
545
0
    }
546
547
0
    TAgentResult result;
548
0
    RETURN_IF_ERROR(ThriftRpcHelper::rpc<BackendServiceClient>(
549
0
            ip, port, [&request, &result](BackendServiceConnection& client) {
550
0
                client->make_snapshot(result, request);
551
0
            }));
552
0
    if (result.status.status_code != TStatusCode::OK) {
553
0
        return Status::create(result.status);
554
0
    }
555
556
0
    if (!result.__isset.snapshot_path) {
557
0
        return Status::InternalError("success snapshot request without snapshot path");
558
0
    }
559
0
    *snapshot_path = result.snapshot_path;
560
0
    if (snapshot_path->at(snapshot_path->length() - 1) != '/') {
561
0
        snapshot_path->append("/");
562
0
    }
563
564
0
    if (result.__isset.allow_incremental_clone) {
565
        // During upgrading, some BE nodes still be installed an old previous old.
566
        // which incremental clone is not ready in those nodes.
567
        // should add a symbol to indicate it.
568
0
        *allow_incremental_clone = result.allow_incremental_clone;
569
0
    }
570
0
    return Status::OK();
571
0
}
572
573
Status EngineCloneTask::_release_snapshot(const std::string& ip, int port,
574
0
                                          const std::string& snapshot_path) {
575
0
    TAgentResult result;
576
0
    RETURN_IF_ERROR(ThriftRpcHelper::rpc<BackendServiceClient>(
577
0
            ip, port, [&snapshot_path, &result](BackendServiceConnection& client) {
578
0
                client->release_snapshot(result, snapshot_path);
579
0
            }));
580
0
    return Status::create(result.status);
581
0
}
582
583
Status EngineCloneTask::_download_files(DataDir* data_dir, const std::string& remote_url_prefix,
584
0
                                        const std::string& local_path) {
585
    // Check local path exist, if exist, remove it, then create the dir
586
    // local_file_full_path = tabletid/clone, for a specific tablet, there should be only one folder
587
    // if this folder exists, then should remove it
588
    // for example, BE clone from BE 1 to download file 1 with version (2,2), but clone from BE 1 failed
589
    // then it will try to clone from BE 2, but it will find the file 1 already exist, but file 1 with same
590
    // name may have different versions.
591
0
    RETURN_IF_ERROR(io::global_local_filesystem()->delete_directory(local_path));
592
0
    RETURN_IF_ERROR(io::global_local_filesystem()->create_directory(local_path));
593
594
    // Get remote dir file list
595
0
    std::string file_list_str;
596
0
    auto list_files_cb = [&remote_url_prefix, &file_list_str](HttpClient* client) {
597
0
        RETURN_IF_ERROR(client->init(remote_url_prefix));
598
0
        client->set_timeout_ms(LIST_REMOTE_FILE_TIMEOUT * 1000);
599
0
        return client->execute(&file_list_str);
600
0
    };
601
0
    RETURN_IF_ERROR(HttpClient::execute_with_retry(DOWNLOAD_FILE_MAX_RETRY, 1, list_files_cb));
602
0
    std::vector<std::string> file_name_list =
603
0
            absl::StrSplit(file_list_str, "\n", absl::SkipWhitespace());
604
605
    // If the header file is not exist, the table couldn't loaded by olap engine.
606
    // Avoid of data is not complete, we copy the header file at last.
607
    // The header file's name is end of .hdr.
608
0
    for (int i = 0; i + 1 < file_name_list.size(); ++i) {
609
0
        if (file_name_list[i].ends_with(".hdr")) {
610
0
            std::swap(file_name_list[i], file_name_list[file_name_list.size() - 1]);
611
0
            break;
612
0
        }
613
0
    }
614
615
    // Get copy from remote
616
0
    uint64_t total_file_size = 0;
617
0
    MonotonicStopWatch watch;
618
0
    watch.start();
619
0
    for (auto& file_name : file_name_list) {
620
0
        auto remote_file_url = remote_url_prefix + file_name;
621
622
        // get file length
623
0
        uint64_t file_size = 0;
624
0
        auto get_file_size_cb = [&remote_file_url, &file_size](HttpClient* client) {
625
0
            RETURN_IF_ERROR(client->init(remote_file_url));
626
0
            client->set_timeout_ms(GET_LENGTH_TIMEOUT * 1000);
627
0
            RETURN_IF_ERROR(client->head());
628
0
            RETURN_IF_ERROR(client->get_content_length(&file_size));
629
0
            return Status::OK();
630
0
        };
631
0
        RETURN_IF_ERROR(
632
0
                HttpClient::execute_with_retry(DOWNLOAD_FILE_MAX_RETRY, 1, get_file_size_cb));
633
        // check disk capacity
634
0
        if (data_dir->reach_capacity_limit(file_size)) {
635
0
            return Status::Error<EXCEEDED_LIMIT>(
636
0
                    "reach the capacity limit of path {}, file_size={}", data_dir->path(),
637
0
                    file_size);
638
0
        }
639
640
0
        total_file_size += file_size;
641
0
        uint64_t estimate_timeout = file_size / config::download_low_speed_limit_kbps / 1024;
642
0
        if (estimate_timeout < config::download_low_speed_time) {
643
0
            estimate_timeout = config::download_low_speed_time;
644
0
        }
645
646
0
        std::string local_file_path = local_path + "/" + file_name;
647
648
0
        LOG(INFO) << "clone begin to download file from: " << mask_token(remote_file_url)
649
0
                  << " to: " << local_file_path << ". size(B): " << file_size
650
0
                  << ", timeout(s): " << estimate_timeout;
651
652
0
        auto download_cb = [&remote_file_url, estimate_timeout, &local_file_path,
653
0
                            file_size](HttpClient* client) {
654
0
            RETURN_IF_ERROR(client->init(remote_file_url));
655
0
            client->set_timeout_ms(estimate_timeout * 1000);
656
0
            RETURN_IF_ERROR(client->download(local_file_path));
657
658
0
            std::error_code ec;
659
            // Check file length
660
0
            uint64_t local_file_size = std::filesystem::file_size(local_file_path, ec);
661
0
            if (ec) {
662
0
                LOG(WARNING) << "download file error" << ec.message();
663
0
                return Status::IOError("can't retrive file_size of {}, due to {}", local_file_path,
664
0
                                       ec.message());
665
0
            }
666
0
            if (local_file_size != file_size) {
667
0
                LOG(WARNING) << "download file length error"
668
0
                             << ", remote_path=" << mask_token(remote_file_url)
669
0
                             << ", file_size=" << file_size
670
0
                             << ", local_file_size=" << local_file_size;
671
0
                return Status::InternalError("downloaded file size is not equal");
672
0
            }
673
0
            return io::global_local_filesystem()->permission(local_file_path,
674
0
                                                             io::LocalFileSystem::PERMS_OWNER_RW);
675
0
        };
676
0
        RETURN_IF_ERROR(HttpClient::execute_with_retry(DOWNLOAD_FILE_MAX_RETRY, 1, download_cb));
677
0
    } // Clone files from remote backend
678
679
0
    uint64_t total_time_ms = watch.elapsed_time() / 1000 / 1000;
680
0
    total_time_ms = total_time_ms > 0 ? total_time_ms : 0;
681
0
    double copy_rate = 0.0;
682
0
    if (total_time_ms > 0) {
683
0
        copy_rate = total_file_size / ((double)total_time_ms) / 1000;
684
0
    }
685
0
    _copy_size = (int64_t)total_file_size;
686
0
    _copy_time_ms = (int64_t)total_time_ms;
687
0
    LOG(INFO) << "succeed to copy tablet " << _signature
688
0
              << ", total files: " << file_name_list.size()
689
0
              << ", total file size: " << total_file_size << " B, cost: " << total_time_ms << " ms"
690
0
              << ", rate: " << copy_rate << " MB/s";
691
0
    return Status::OK();
692
0
}
693
694
Status EngineCloneTask::_batch_download_files(DataDir* data_dir, const std::string& address,
695
                                              const std::string& remote_dir,
696
0
                                              const std::string& local_dir) {
697
0
    constexpr size_t BATCH_FILE_SIZE = 64 << 20; // 64MB
698
0
    constexpr size_t BATCH_FILE_NUM = 64;
699
700
    // Check local path exist, if exist, remove it, then create the dir
701
    // local_file_full_path = tabletid/clone, for a specific tablet, there should be only one folder
702
    // if this folder exists, then should remove it
703
    // for example, BE clone from BE 1 to download file 1 with version (2,2), but clone from BE 1 failed
704
    // then it will try to clone from BE 2, but it will find the file 1 already exist, but file 1 with same
705
    // name may have different versions.
706
0
    RETURN_IF_ERROR(io::global_local_filesystem()->delete_directory(local_dir));
707
0
    RETURN_IF_ERROR(io::global_local_filesystem()->create_directory(local_dir));
708
709
0
    const std::string& token = _cluster_info->token;
710
0
    std::vector<std::pair<std::string, size_t>> file_info_list;
711
0
    RETURN_IF_ERROR(list_remote_files_v2(address, token, remote_dir, &file_info_list));
712
713
    // If the header file is not exist, the table couldn't loaded by olap engine.
714
    // Avoid of data is not complete, we copy the header file at last.
715
    // The header file's name is end of .hdr.
716
0
    for (int i = 0; i + 1 < file_info_list.size(); ++i) {
717
0
        if (file_info_list[i].first.ends_with(".hdr")) {
718
0
            std::swap(file_info_list[i], file_info_list[file_info_list.size() - 1]);
719
0
            break;
720
0
        }
721
0
    }
722
723
0
    MonotonicStopWatch watch;
724
0
    watch.start();
725
726
0
    size_t total_file_size = 0;
727
0
    size_t total_files = file_info_list.size();
728
0
    std::vector<std::pair<std::string, size_t>> batch_files;
729
0
    for (size_t i = 0; i < total_files;) {
730
0
        size_t batch_file_size = 0;
731
0
        for (size_t j = i; j < total_files; j++) {
732
            // Split batchs by file number and file size,
733
0
            if (BATCH_FILE_NUM <= batch_files.size() || BATCH_FILE_SIZE <= batch_file_size ||
734
                // ... or separate the last .hdr file into a single batch.
735
0
                (j + 1 == total_files && !batch_files.empty())) {
736
0
                break;
737
0
            }
738
0
            batch_files.push_back(file_info_list[j]);
739
0
            batch_file_size += file_info_list[j].second;
740
0
        }
741
742
        // check disk capacity
743
0
        if (data_dir->reach_capacity_limit(batch_file_size)) {
744
0
            return Status::Error<EXCEEDED_LIMIT>(
745
0
                    "reach the capacity limit of path {}, file_size={}", data_dir->path(),
746
0
                    batch_file_size);
747
0
        }
748
749
0
        RETURN_IF_ERROR(download_files_v2(address, token, remote_dir, local_dir, batch_files));
750
751
0
        total_file_size += batch_file_size;
752
0
        i += batch_files.size();
753
0
        batch_files.clear();
754
0
    }
755
756
0
    uint64_t total_time_ms = watch.elapsed_time() / 1000 / 1000;
757
0
    total_time_ms = total_time_ms > 0 ? total_time_ms : 0;
758
0
    double copy_rate = 0.0;
759
0
    if (total_time_ms > 0) {
760
0
        copy_rate = total_file_size / ((double)total_time_ms) / 1000;
761
0
    }
762
0
    _copy_size = (int64_t)total_file_size;
763
0
    _copy_time_ms = (int64_t)total_time_ms;
764
0
    LOG(INFO) << "succeed to copy tablet " << _signature
765
0
              << ", total files: " << file_info_list.size()
766
0
              << ", total file size: " << total_file_size << " B, cost: " << total_time_ms << " ms"
767
0
              << ", rate: " << copy_rate << " MB/s";
768
769
0
    return Status::OK();
770
0
}
771
772
/// This method will only be called if tablet already exist in this BE when doing clone.
773
/// This method will do the following things:
774
/// 1. Link all files from CLONE dir to tablet dir if file does not exist in tablet dir
775
/// 2. Call _finish_xx_clone() to revise the tablet meta.
776
Status EngineCloneTask::_finish_clone(Tablet* tablet, const std::string& clone_dir, int64_t version,
777
0
                                      bool is_incremental_clone, bool copy_row_binlog) {
778
0
    Defer remove_clone_dir {[&]() {
779
0
        std::error_code ec;
780
0
        std::filesystem::remove_all(clone_dir, ec);
781
0
        if (ec) {
782
0
            LOG(WARNING) << "failed to remove=" << clone_dir << " msg=" << ec.message();
783
0
        }
784
0
    }};
785
786
    // check clone dir existed
787
0
    bool exists = true;
788
0
    RETURN_IF_ERROR(io::global_local_filesystem()->exists(clone_dir, &exists));
789
0
    if (!exists) {
790
0
        return Status::InternalError("clone dir not existed. clone_dir={}", clone_dir);
791
0
    }
792
793
    // Load src header.
794
    // The tablet meta info is downloaded from source BE as .hdr file.
795
    // So we load it and generate cloned_tablet_meta.
796
0
    auto cloned_tablet_meta_file = fmt::format("{}/{}.hdr", clone_dir, tablet->tablet_id());
797
0
    auto cloned_tablet_meta = std::make_shared<TabletMeta>();
798
0
    RETURN_IF_ERROR(cloned_tablet_meta->create_from_file(cloned_tablet_meta_file));
799
800
    // remove the cloned meta file
801
0
    RETURN_IF_ERROR(io::global_local_filesystem()->delete_file(cloned_tablet_meta_file));
802
803
    // remove rowset binlog metas
804
0
    const auto& tablet_dir = tablet->tablet_path();
805
0
    auto binlog_metas_file = fmt::format("{}/rowset_binlog_metas.pb", clone_dir);
806
0
    bool binlog_metas_file_exists = false;
807
0
    auto file_exists_status =
808
0
            io::global_local_filesystem()->exists(binlog_metas_file, &binlog_metas_file_exists);
809
0
    if (!file_exists_status.ok()) {
810
0
        return file_exists_status;
811
0
    }
812
0
    bool contain_binlog = false;
813
0
    RowsetBinlogMetasPB rowset_binlog_metas_pb;
814
0
    if (binlog_metas_file_exists) {
815
0
        std::error_code ec;
816
0
        auto binlog_meta_filesize = std::filesystem::file_size(binlog_metas_file, ec);
817
0
        if (ec) {
818
0
            LOG(WARNING) << "get file size error" << ec.message();
819
0
            return Status::IOError("can't retrive file_size of {}, due to {}", binlog_metas_file,
820
0
                                   ec.message());
821
0
        }
822
0
        if (binlog_meta_filesize > 0) {
823
0
            contain_binlog = true;
824
0
            RETURN_IF_ERROR(read_pb(binlog_metas_file, &rowset_binlog_metas_pb));
825
0
        }
826
0
        RETURN_IF_ERROR(io::global_local_filesystem()->delete_file(binlog_metas_file));
827
0
    }
828
0
    if (contain_binlog) {
829
0
        auto binlog_dir = fmt::format("{}/_binlog", tablet_dir);
830
0
        RETURN_IF_ERROR(io::global_local_filesystem()->create_directory(binlog_dir));
831
0
    }
832
833
0
    enum class CloneFileType { DATA, ROW_BINLOG, CCR_BINLOG };
834
835
    // check all files in /clone and /tablet
836
0
    std::vector<io::FileInfo> clone_files;
837
0
    RETURN_IF_ERROR(io::global_local_filesystem()->list(clone_dir, true, &clone_files, &exists));
838
0
    std::vector<std::pair<CloneFileType, std::string>> clone_file_names;
839
0
    for (auto& file : clone_files) {
840
0
        CloneFileType file_type = CloneFileType::DATA;
841
0
        if (file.file_name.ends_with(".binlog") || file.file_name.ends_with(".binlog-index")) {
842
0
            file_type = CloneFileType::CCR_BINLOG;
843
0
        }
844
0
        clone_file_names.emplace_back(file_type, file.file_name);
845
0
    }
846
0
    auto row_binlog_clone_dir = fmt::format("{}/{}", clone_dir, FDRowBinlogSuffix);
847
0
    if (copy_row_binlog) {
848
0
        clone_files.clear();
849
0
        RETURN_IF_ERROR(io::global_local_filesystem()->list(row_binlog_clone_dir, true,
850
0
                                                            &clone_files, &exists));
851
0
        if (!exists) {
852
0
            return Status::InternalError("row binlog clone dir not existed. clone_dir={}",
853
0
                                         row_binlog_clone_dir);
854
0
        }
855
0
        for (auto& file : clone_files) {
856
0
            clone_file_names.emplace_back(CloneFileType::ROW_BINLOG, file.file_name);
857
0
        }
858
0
    }
859
860
0
    std::vector<io::FileInfo> local_files;
861
0
    RETURN_IF_ERROR(io::global_local_filesystem()->list(tablet_dir, true, &local_files, &exists));
862
0
    std::unordered_set<std::string> data_local_file_names;
863
0
    for (auto& file : local_files) {
864
0
        data_local_file_names.insert(file.file_name);
865
0
    }
866
0
    auto row_binlog_dir = tablet->row_binlog_path();
867
0
    std::unordered_set<std::string> row_binlog_local_file_names;
868
0
    if (copy_row_binlog) {
869
0
        RETURN_IF_ERROR(io::global_local_filesystem()->create_directory(row_binlog_dir));
870
0
        local_files.clear();
871
0
        RETURN_IF_ERROR(
872
0
                io::global_local_filesystem()->list(row_binlog_dir, true, &local_files, &exists));
873
0
        for (auto& file : local_files) {
874
0
            row_binlog_local_file_names.insert(file.file_name);
875
0
        }
876
0
    }
877
878
0
    Status status;
879
0
    std::vector<std::string> linked_success_files;
880
0
    Defer remove_linked_files {[&]() { // clear linked files if errors happen
881
0
        if (!status.ok()) {
882
0
            std::vector<io::Path> paths;
883
0
            for (auto& file : linked_success_files) {
884
0
                paths.emplace_back(file);
885
0
            }
886
0
            static_cast<void>(io::global_local_filesystem()->batch_delete(paths));
887
0
        }
888
0
    }};
889
    /// Traverse all downloaded clone files in CLONE dir.
890
    /// If it does not exist in local tablet dir, link the file to local tablet dir
891
    /// And save all linked files in linked_success_files.
892
0
    for (const auto& [clone_file_type, clone_file] : clone_file_names) {
893
0
        if (clone_file_type == CloneFileType::DATA &&
894
0
            data_local_file_names.find(clone_file) != data_local_file_names.end()) {
895
0
            VLOG_NOTICE << "find same file when clone, skip it. "
896
0
                        << "tablet=" << tablet->tablet_id() << ", clone_file=" << clone_file;
897
0
            continue;
898
0
        }
899
0
        if (clone_file_type == CloneFileType::ROW_BINLOG &&
900
0
            row_binlog_local_file_names.find(clone_file) != row_binlog_local_file_names.end()) {
901
0
            VLOG_NOTICE << "find same row binlog file when clone, skip it. "
902
0
                        << "tablet=" << tablet->tablet_id() << ", clone_file=" << clone_file;
903
0
            continue;
904
0
        }
905
906
        /// if binlog exist in clone dir and md5sum equal, then skip link file
907
0
        bool skip_link_file = false;
908
0
        std::string to;
909
0
        if (clone_file_type == CloneFileType::CCR_BINLOG) {
910
0
            if (!contain_binlog) {
911
0
                LOG(WARNING) << "clone binlog file, but not contain binlog metas. "
912
0
                             << "tablet=" << tablet->tablet_id() << ", clone_file=" << clone_file;
913
0
                break;
914
0
            }
915
916
0
            if (auto&& result =
917
0
                        check_dest_binlog_valid(tablet_dir, clone_dir, clone_file, &skip_link_file);
918
0
                result) {
919
0
                to = std::move(result.value());
920
0
            } else {
921
0
                status = std::move(result.error());
922
0
                return status;
923
0
            }
924
0
        } else {
925
0
            auto& local_dir =
926
0
                    clone_file_type == CloneFileType::ROW_BINLOG ? row_binlog_dir : tablet_dir;
927
0
            to = fmt::format("{}/{}", local_dir, clone_file);
928
0
        }
929
930
0
        if (!skip_link_file) {
931
0
            auto& clone_file_dir =
932
0
                    clone_file_type == CloneFileType::ROW_BINLOG ? row_binlog_clone_dir : clone_dir;
933
0
            auto from = fmt::format("{}/{}", clone_file_dir, clone_file);
934
0
            status = io::global_local_filesystem()->link_file(from, to);
935
0
            if (!status.ok()) {
936
0
                return status;
937
0
            }
938
0
            linked_success_files.emplace_back(std::move(to));
939
0
        }
940
0
    }
941
0
    if (contain_binlog) {
942
0
        status = tablet->ingest_binlog_metas(&rowset_binlog_metas_pb);
943
0
        if (!status.ok()) {
944
0
            return status;
945
0
        }
946
0
    }
947
948
    // clone and compaction operation should be performed sequentially
949
0
    std::lock_guard base_compaction_lock(tablet->get_base_compaction_lock());
950
0
    std::lock_guard cumulative_compaction_lock(tablet->get_cumulative_compaction_lock());
951
0
    std::lock_guard cold_compaction_lock(tablet->get_cold_compaction_lock());
952
0
    std::lock_guard build_inverted_index_lock(tablet->get_build_inverted_index_lock());
953
0
    std::lock_guard<std::mutex> push_lock(tablet->get_push_lock());
954
0
    std::lock_guard<std::mutex> rwlock(tablet->get_rowset_update_lock());
955
0
    std::lock_guard wrlock(tablet->get_header_lock());
956
0
    SCOPED_SIMPLE_TRACE_IF_TIMEOUT(TRACE_TABLET_LOCK_THRESHOLD);
957
0
    if (is_incremental_clone) {
958
0
        status = _finish_incremental_clone(tablet, cloned_tablet_meta, version, copy_row_binlog);
959
0
    } else {
960
0
        status = _finish_full_clone(tablet, cloned_tablet_meta, copy_row_binlog);
961
0
    }
962
963
    // if full clone success, need to update cumulative layer point
964
0
    if (!is_incremental_clone && status.ok()) {
965
0
        tablet->set_cumulative_layer_point(Tablet::K_INVALID_CUMULATIVE_POINT);
966
0
    }
967
968
    // clear clone dir
969
0
    return status;
970
0
}
971
972
/// This method will do:
973
/// 1. Get missing version from local tablet again and check if they exist in cloned tablet.
974
/// 2. Revise the local tablet meta to add all incremental cloned rowset's meta.
975
Status EngineCloneTask::_finish_incremental_clone(Tablet* tablet,
976
                                                  const TabletMetaSharedPtr& cloned_tablet_meta,
977
0
                                                  int64_t version, bool copy_row_binlog) {
978
0
    LOG(INFO) << "begin to finish incremental clone. tablet=" << tablet->tablet_id()
979
0
              << ", visible_version=" << version
980
0
              << ", cloned_tablet_replica_id=" << cloned_tablet_meta->replica_id();
981
982
    /// Get missing versions again from local tablet.
983
    /// We got it before outside the lock, so it has to be got again.
984
0
    Versions missed_versions = tablet->get_missed_versions_unlocked(version);
985
0
    VLOG_NOTICE << "get missed versions again when finish incremental clone. "
986
0
                << "tablet=" << tablet->tablet_id() << ", clone version=" << version
987
0
                << ", missed_versions_size=" << missed_versions.size();
988
989
    // check missing versions exist in clone src
990
0
    std::vector<RowsetSharedPtr> rowsets_to_clone;
991
0
    for (Version nested_version : missed_versions) {
992
0
        auto rs_meta = cloned_tablet_meta->acquire_rs_meta_by_version(nested_version);
993
0
        if (rs_meta == nullptr) {
994
0
            return Status::InternalError("missed version {} is not found in cloned tablet meta",
995
0
                                         nested_version.to_string());
996
0
        }
997
0
        RowsetSharedPtr rs;
998
0
        RETURN_IF_ERROR(tablet->create_rowset(rs_meta, &rs));
999
0
        rowsets_to_clone.push_back(std::move(rs));
1000
0
        if (copy_row_binlog) {
1001
0
            rs_meta = cloned_tablet_meta->acquire_row_binlog_rs_meta_by_version(nested_version);
1002
0
            if (rs_meta == nullptr) {
1003
0
                return Status::InternalError(
1004
0
                        "missed version {} row binlog is not found in cloned tablet meta",
1005
0
                        nested_version.to_string());
1006
0
            }
1007
0
            RETURN_IF_ERROR(tablet->create_rowset(rs_meta, &rs));
1008
0
            rowsets_to_clone.push_back(std::move(rs));
1009
0
        }
1010
0
    }
1011
1012
0
    if (copy_row_binlog && tablet->enable_unique_key_merge_on_write()) {
1013
0
        tablet->tablet_meta()->binlog_delvec().merge(cloned_tablet_meta->binlog_delvec());
1014
0
    }
1015
1016
    /// clone_data to tablet
1017
    /// For incremental clone, nothing will be deleted.
1018
    /// So versions_to_delete is empty.
1019
0
    return tablet->revise_tablet_meta(rowsets_to_clone, {}, true, copy_row_binlog);
1020
0
}
1021
1022
/// This method will do:
1023
/// 1. Compare the version of local tablet and cloned tablet to decide which version to keep
1024
/// 2. Revise the local tablet meta
1025
Status EngineCloneTask::_finish_full_clone(Tablet* tablet,
1026
                                           const TabletMetaSharedPtr& cloned_tablet_meta,
1027
0
                                           bool copy_row_binlog) {
1028
0
    Version cloned_max_version = cloned_tablet_meta->max_version();
1029
0
    LOG(INFO) << "begin to finish full clone. tablet=" << tablet->tablet_id()
1030
0
              << ", cloned_max_version=" << cloned_max_version;
1031
1032
    // Compare the version of local tablet and cloned tablet.
1033
    // For example:
1034
    // clone version is 8
1035
    //
1036
    //      local tablet: [0-1] [2-5] [6-6] [7-7] [9-10]
1037
    //      clone tablet: [0-1] [2-4] [5-6] [7-8]
1038
    //
1039
    // after compare, the version mark with "x" will be deleted
1040
    //
1041
    //      local tablet: [0-1]x [2-5]x [6-6]x [7-7]x [9-10]
1042
    //      clone tablet: [0-1]  [2-4]  [5-6]  [7-8]
1043
1044
0
    std::vector<RowsetSharedPtr> to_delete;
1045
0
    std::vector<RowsetSharedPtr> to_add;
1046
0
    for (auto& [v, rs] : tablet->rowset_map()) {
1047
        // if local version cross src latest, clone failed
1048
        // if local version is : 0-0, 1-1, 2-10, 12-14, 15-15,16-16
1049
        // cloned max version is 13-13, this clone is failed, because could not
1050
        // fill local data by using cloned data.
1051
        // It should not happen because if there is a hole, the following delta will not
1052
        // do compaction.
1053
0
        if (v.first <= cloned_max_version.second && v.second > cloned_max_version.second) {
1054
0
            return Status::InternalError(
1055
0
                    "version cross src latest. cloned_max_version={}, local_version={}",
1056
0
                    cloned_max_version.second, v.to_string());
1057
0
        }
1058
0
        if (v.second <= cloned_max_version.second) {
1059
0
            to_delete.push_back(rs);
1060
0
        } else {
1061
            // cooldowned rowsets MUST be continuous, so rowsets whose version > missed version MUST be local rowset
1062
0
            DCHECK(rs->is_local());
1063
0
        }
1064
0
    }
1065
0
    if (copy_row_binlog) {
1066
0
        for (auto& [v, rs] : tablet->row_binlog_rowset_map()) {
1067
0
            if (v.first <= cloned_max_version.second && v.second > cloned_max_version.second) {
1068
0
                return Status::InternalError(
1069
0
                        "row binlog version cross src latest. cloned_max_version={}, "
1070
0
                        "local_version={}",
1071
0
                        cloned_max_version.second, v.to_string());
1072
0
            }
1073
0
            if (v.second <= cloned_max_version.second) {
1074
0
                to_delete.push_back(rs);
1075
0
            } else {
1076
0
                DCHECK(rs->is_local());
1077
0
            }
1078
0
        }
1079
0
    }
1080
1081
0
    to_add.reserve(cloned_tablet_meta->all_rs_metas().size() +
1082
0
                   cloned_tablet_meta->all_row_binlog_rs_metas().size());
1083
0
    for (const auto& [_, rs_meta] : cloned_tablet_meta->all_rs_metas()) {
1084
0
        RowsetSharedPtr rs;
1085
0
        RETURN_IF_ERROR(tablet->create_rowset(rs_meta, &rs));
1086
0
        to_add.push_back(std::move(rs));
1087
0
    }
1088
0
    if (copy_row_binlog) {
1089
0
        for (const auto& [_, rs_meta] : cloned_tablet_meta->all_row_binlog_rs_metas()) {
1090
0
            RowsetSharedPtr rs;
1091
0
            RETURN_IF_ERROR(tablet->create_rowset(rs_meta, &rs));
1092
0
            to_add.push_back(std::move(rs));
1093
0
        }
1094
0
    }
1095
0
    {
1096
0
        std::shared_lock cooldown_conf_rlock(tablet->get_cooldown_conf_lock());
1097
0
        if (tablet->cooldown_conf_unlocked().cooldown_replica_id == tablet->replica_id()) {
1098
            // If this replica is cooldown replica, MUST generate a new `cooldown_meta_id` to avoid use `cooldown_meta_id`
1099
            // generated in old cooldown term which may lead to such situation:
1100
            // Replica A is cooldown replica, cooldown_meta_id=2,
1101
            // Replica B: cooldown_replica=A, cooldown_meta_id=1
1102
            // Replica A: full clone Replica A, cooldown_meta_id=1, but remote cooldown_meta is still with cooldown_meta_id=2
1103
            // After tablet report. FE finds all replicas' cooldowned data is consistent
1104
            // Replica A: confirm_unused_remote_files, delete some cooldowned data of cooldown_meta_id=2
1105
            // Replica B: follow_cooldown_data, cooldown_meta_id=2, data lost
1106
0
            tablet->tablet_meta()->set_cooldown_meta_id(UniqueId::gen_uid());
1107
0
        } else {
1108
0
            tablet->tablet_meta()->set_cooldown_meta_id(cloned_tablet_meta->cooldown_meta_id());
1109
0
        }
1110
0
    }
1111
0
    if (tablet->enable_unique_key_merge_on_write()) {
1112
0
        tablet->tablet_meta()->delete_bitmap().merge(cloned_tablet_meta->delete_bitmap());
1113
0
        if (copy_row_binlog) {
1114
0
            tablet->tablet_meta()->binlog_delvec().merge(cloned_tablet_meta->binlog_delvec());
1115
0
        }
1116
0
    }
1117
0
    return tablet->revise_tablet_meta(to_add, to_delete, false, copy_row_binlog);
1118
    // TODO(plat1ko): write cooldown meta to remote if this replica is cooldown replica
1119
0
}
1120
} // namespace doris