Coverage Report

Created: 2025-07-24 00:20

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/root/doris/be/src/runtime/snapshot_loader.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 "runtime/snapshot_loader.h"
19
20
// IWYU pragma: no_include <bthread/errno.h>
21
#include <absl/strings/str_split.h>
22
#include <errno.h> // IWYU pragma: keep
23
#include <fmt/format.h>
24
#include <gen_cpp/AgentService_types.h>
25
#include <gen_cpp/FrontendService.h>
26
#include <gen_cpp/FrontendService_types.h>
27
#include <gen_cpp/HeartbeatService_types.h>
28
#include <gen_cpp/PlanNodes_types.h>
29
#include <gen_cpp/Status_types.h>
30
#include <gen_cpp/Types_types.h>
31
32
#include <algorithm>
33
#include <cstddef>
34
#include <cstring>
35
#include <filesystem>
36
#include <istream>
37
#include <unordered_map>
38
#include <utility>
39
40
#include "common/cast_set.h"
41
#include "common/config.h"
42
#include "common/logging.h"
43
#include "http/http_client.h"
44
#include "io/fs/broker_file_system.h"
45
#include "io/fs/file_system.h"
46
#include "io/fs/hdfs_file_system.h"
47
#include "io/fs/local_file_system.h"
48
#include "io/fs/path.h"
49
#include "io/fs/remote_file_system.h"
50
#include "io/fs/s3_file_system.h"
51
#include "io/hdfs_builder.h"
52
#include "olap/data_dir.h"
53
#include "olap/snapshot_manager.h"
54
#include "olap/storage_engine.h"
55
#include "olap/tablet.h"
56
#include "olap/tablet_manager.h"
57
#include "runtime/client_cache.h"
58
#include "runtime/exec_env.h"
59
#include "util/s3_uri.h"
60
#include "util/s3_util.h"
61
#include "util/thrift_rpc_helper.h"
62
63
namespace doris {
64
#include "common/compile_check_begin.h"
65
66
struct LocalFileStat {
67
    uint64_t size;
68
    std::string md5;
69
};
70
71
struct RemoteFileStat {
72
    std::string url;
73
    std::string md5;
74
    uint64_t size;
75
};
76
77
class SnapshotHttpDownloader {
78
public:
79
    SnapshotHttpDownloader(const TRemoteTabletSnapshot& remote_tablet_snapshot,
80
                           TabletSharedPtr tablet, SnapshotLoader& snapshot_loader)
81
1
            : _tablet(std::move(tablet)),
82
1
              _snapshot_loader(snapshot_loader),
83
1
              _local_tablet_id(remote_tablet_snapshot.local_tablet_id),
84
1
              _remote_tablet_id(remote_tablet_snapshot.remote_tablet_id),
85
1
              _local_path(remote_tablet_snapshot.local_snapshot_path),
86
1
              _remote_path(remote_tablet_snapshot.remote_snapshot_path),
87
1
              _remote_be_addr(remote_tablet_snapshot.remote_be_addr) {
88
1
        auto& token = remote_tablet_snapshot.remote_token;
89
1
        auto& remote_be_addr = remote_tablet_snapshot.remote_be_addr;
90
91
        // HEAD http://172.16.0.14:6781/api/_tablet/_download?token=e804dd27-86da-4072-af58-70724075d2a4&file=/home/ubuntu/doris_master/output/be/storage/snapshot/20230410102306.9.180/
92
1
        _base_url = fmt::format("http://{}:{}/api/_tablet/_download?token={}&channel=ingest_binlog",
93
1
                                remote_be_addr.hostname, remote_be_addr.port, token);
94
1
    }
95
1
    ~SnapshotHttpDownloader() = default;
96
    SnapshotHttpDownloader(const SnapshotHttpDownloader&) = delete;
97
    SnapshotHttpDownloader& operator=(const SnapshotHttpDownloader&) = delete;
98
99
0
    void set_report_progress_callback(std::function<Status()> report_progress) {
100
0
        _report_progress_callback = std::move(report_progress);
101
0
    }
102
103
1
    size_t get_download_file_num() { return _need_download_files.size(); }
104
105
    Status download();
106
107
private:
108
    constexpr static int kDownloadFileMaxRetry = 3;
109
110
    // Load existing files from local snapshot path, compute the md5sum of the files
111
    // if enable_download_md5sum_check is true
112
    Status _load_existing_files();
113
114
    // List remote files from remote be, and find the hdr file
115
    Status _list_remote_files();
116
117
    // Download hdr file from remote be to a tmp file
118
    Status _download_hdr_file();
119
120
    // Link same rowset files by compare local hdr file and remote hdr file
121
    // if the local files are copied from the remote rowset, link them as the
122
    // remote rowset files, to avoid the duplicated downloading.
123
    Status _link_same_rowset_files();
124
125
    // Get all remote file stats, excluding the hdr file.
126
    Status _get_remote_file_stats();
127
128
    // Compute the need download files according to the local files md5sum (if enable_download_md5sum_check is true)
129
    void _get_need_download_files();
130
131
    // Download all need download files
132
    Status _download_files();
133
134
    // Install remote hdr file to local snapshot path from the tmp file
135
    Status _install_remote_hdr_file();
136
137
    // Delete orphan files, which are not in remote
138
    Status _delete_orphan_files();
139
140
    // Download a file from remote be to local path with the file stat
141
    Status _download_http_file(DataDir* data_dir, const std::string& remote_file_url,
142
                               const std::string& local_file_path,
143
                               const RemoteFileStat& remote_filestat);
144
145
    // Get the file stat from remote be
146
    Status _get_http_file_stat(const std::string& remote_file_url, RemoteFileStat* file_stat);
147
148
    TabletSharedPtr _tablet;
149
    SnapshotLoader& _snapshot_loader;
150
    std::function<Status()> _report_progress_callback;
151
152
    std::string _base_url;
153
    int64_t _local_tablet_id;
154
    int64_t _remote_tablet_id;
155
    const std::string& _local_path;
156
    const std::string& _remote_path;
157
    const TNetworkAddress& _remote_be_addr;
158
159
    std::string _local_hdr_filename;
160
    std::string _remote_hdr_filename;
161
    std::vector<std::string> _remote_file_list;
162
    std::unordered_map<std::string, LocalFileStat> _local_files;
163
    std::unordered_map<std::string, RemoteFileStat> _remote_files;
164
165
    std::string _tmp_hdr_file;
166
    RemoteFileStat _remote_hdr_filestat;
167
    std::vector<std::string> _need_download_files;
168
};
169
170
3
static std::string get_loaded_tag_path(const std::string& snapshot_path) {
171
3
    return snapshot_path + "/LOADED";
172
3
}
173
174
1
static Status write_loaded_tag(const std::string& snapshot_path, int64_t tablet_id) {
175
1
    std::unique_ptr<io::FileWriter> writer;
176
1
    std::string file = get_loaded_tag_path(snapshot_path);
177
1
    RETURN_IF_ERROR(io::global_local_filesystem()->create_file(file, &writer));
178
1
    return writer->close();
179
1
}
180
181
Status upload_with_checksum(io::RemoteFileSystem& fs, std::string_view local_path,
182
0
                            std::string_view remote_path, std::string_view checksum) {
183
0
    auto full_remote_path = fmt::format("{}.{}", remote_path, checksum);
184
0
    switch (fs.type()) {
185
0
    case io::FileSystemType::HDFS:
186
0
    case io::FileSystemType::BROKER: {
187
0
        std::string temp = fmt::format("{}.part", remote_path);
188
0
        RETURN_IF_ERROR(fs.upload(local_path, temp));
189
0
        RETURN_IF_ERROR(fs.rename(temp, full_remote_path));
190
0
        break;
191
0
    }
192
0
    case io::FileSystemType::S3:
193
0
        RETURN_IF_ERROR(fs.upload(local_path, full_remote_path));
194
0
        break;
195
0
    default:
196
0
        throw doris::Exception(
197
0
                Status::FatalError("unknown fs type: {}", static_cast<int>(fs.type())));
198
0
    }
199
0
    return Status::OK();
200
0
}
201
202
18
bool _end_with(std::string_view str, std::string_view match) {
203
18
    return str.size() >= match.size() &&
204
18
           str.compare(str.size() - match.size(), match.size(), match) == 0;
205
18
}
206
207
Status SnapshotHttpDownloader::_get_http_file_stat(const std::string& remote_file_url,
208
2
                                                   RemoteFileStat* file_stat) {
209
2
    uint64_t file_size = 0;
210
2
    std::string file_md5;
211
2
    auto get_file_stat_cb = [&remote_file_url, &file_size, &file_md5](HttpClient* client) {
212
2
        int64_t timeout_ms = config::download_binlog_meta_timeout_ms;
213
2
        std::string url = remote_file_url;
214
2
        if (config::enable_download_md5sum_check) {
215
            // compute md5sum is time-consuming, so we set a longer timeout
216
0
            timeout_ms = config::download_binlog_meta_timeout_ms * 3;
217
0
            url = fmt::format("{}&acquire_md5=true", remote_file_url);
218
0
        }
219
2
        RETURN_IF_ERROR(client->init(url));
220
2
        client->set_timeout_ms(timeout_ms);
221
2
        RETURN_IF_ERROR(client->head());
222
2
        RETURN_IF_ERROR(client->get_content_length(&file_size));
223
2
        if (config::enable_download_md5sum_check) {
224
0
            RETURN_IF_ERROR(client->get_content_md5(&file_md5));
225
0
        }
226
2
        return Status::OK();
227
2
    };
228
2
    RETURN_IF_ERROR(HttpClient::execute_with_retry(kDownloadFileMaxRetry, 1, get_file_stat_cb));
229
2
    file_stat->url = remote_file_url;
230
2
    file_stat->size = file_size;
231
2
    file_stat->md5 = std::move(file_md5);
232
2
    return Status::OK();
233
2
}
234
235
Status SnapshotHttpDownloader::_download_http_file(DataDir* data_dir,
236
                                                   const std::string& remote_file_url,
237
                                                   const std::string& local_file_path,
238
1
                                                   const RemoteFileStat& remote_filestat) {
239
1
    auto file_size = remote_filestat.size;
240
1
    const auto& remote_file_md5 = remote_filestat.md5;
241
242
    // check disk capacity
243
1
    if (data_dir->reach_capacity_limit(file_size)) {
244
0
        return Status::Error<ErrorCode::EXCEEDED_LIMIT>(
245
0
                "reach the capacity limit of path {}, file_size={}", data_dir->path(), file_size);
246
0
    }
247
248
1
    uint64_t estimate_timeout = file_size / config::download_low_speed_limit_kbps / 1024;
249
1
    if (estimate_timeout < config::download_low_speed_time) {
250
1
        estimate_timeout = config::download_low_speed_time;
251
1
    }
252
253
1
    LOG(INFO) << "clone begin to download file from: " << remote_file_url
254
1
              << " to: " << local_file_path << ". size(B): " << file_size
255
1
              << ", timeout(s): " << estimate_timeout;
256
257
1
    auto download_cb = [&remote_file_url, &remote_file_md5, estimate_timeout, &local_file_path,
258
1
                        file_size](HttpClient* client) {
259
1
        RETURN_IF_ERROR(client->init(remote_file_url));
260
1
        client->set_timeout_ms(estimate_timeout * 1000);
261
1
        RETURN_IF_ERROR(client->download(local_file_path));
262
263
1
        std::error_code ec;
264
        // Check file length
265
1
        uint64_t local_file_size = std::filesystem::file_size(local_file_path, ec);
266
1
        if (ec) {
267
0
            LOG(WARNING) << "download file error" << ec.message();
268
0
            return Status::IOError("can't retrive file_size of {}, due to {}", local_file_path,
269
0
                                   ec.message());
270
0
        }
271
1
        if (local_file_size != file_size) {
272
0
            LOG(WARNING) << "download file length error"
273
0
                         << ", remote_path=" << remote_file_url << ", file_size=" << file_size
274
0
                         << ", local_file_size=" << local_file_size;
275
0
            return Status::InternalError("downloaded file size is not equal");
276
0
        }
277
278
1
        if (!remote_file_md5.empty()) { // keep compatibility
279
0
            std::string local_file_md5;
280
0
            RETURN_IF_ERROR(
281
0
                    io::global_local_filesystem()->md5sum(local_file_path, &local_file_md5));
282
0
            if (local_file_md5 != remote_file_md5) {
283
0
                LOG(WARNING) << "download file md5 error"
284
0
                             << ", remote_file_url=" << remote_file_url
285
0
                             << ", local_file_path=" << local_file_path
286
0
                             << ", remote_file_md5=" << remote_file_md5
287
0
                             << ", local_file_md5=" << local_file_md5;
288
0
                return Status::RuntimeError(
289
0
                        "download file {} md5 is not equal, local={}, remote={}", remote_file_url,
290
0
                        local_file_md5, remote_file_md5);
291
0
            }
292
0
        }
293
294
1
        return io::global_local_filesystem()->permission(local_file_path,
295
1
                                                         io::LocalFileSystem::PERMS_OWNER_RW);
296
1
    };
297
1
    auto status = HttpClient::execute_with_retry(kDownloadFileMaxRetry, 1, download_cb);
298
1
    if (!status.ok()) {
299
0
        LOG(WARNING) << "failed to download file from " << remote_file_url
300
0
                     << ", status: " << status.to_string();
301
0
        return status;
302
0
    }
303
304
1
    return Status::OK();
305
1
}
306
307
1
Status SnapshotHttpDownloader::_load_existing_files() {
308
1
    std::vector<std::string> existing_files;
309
1
    RETURN_IF_ERROR(_snapshot_loader._get_existing_files_from_local(_local_path, &existing_files));
310
2
    for (auto& local_file : existing_files) {
311
        // add file size
312
2
        std::string local_file_path = _local_path + "/" + local_file;
313
2
        std::error_code ec;
314
2
        uint64_t local_file_size = std::filesystem::file_size(local_file_path, ec);
315
2
        if (ec) {
316
0
            LOG(WARNING) << "download file error, can't retrive file_size of " << local_file_path
317
0
                         << ", due to " << ec.message();
318
0
            return Status::IOError("can't retrive file_size of {}, due to {}", local_file_path,
319
0
                                   ec.message());
320
0
        }
321
322
        // get md5sum
323
2
        std::string md5;
324
2
        if (config::enable_download_md5sum_check) {
325
0
            auto status = io::global_local_filesystem()->md5sum(local_file_path, &md5);
326
0
            if (!status.ok()) {
327
0
                LOG(WARNING) << "download file error, local file " << local_file_path
328
0
                             << " md5sum: " << status.to_string();
329
0
                return status;
330
0
            }
331
0
        }
332
2
        _local_files[local_file] = {local_file_size, md5};
333
334
        // get hdr file
335
2
        if (local_file.ends_with(".hdr")) {
336
1
            _local_hdr_filename = local_file;
337
1
        }
338
2
    }
339
340
1
    return Status::OK();
341
1
}
342
343
1
Status SnapshotHttpDownloader::_list_remote_files() {
344
    // get all these use http download action
345
    // http://172.16.0.14:6781/api/_tablet/_download?token=e804dd27-86da-4072-af58-70724075d2a4&file=/home/ubuntu/doris_master/output/be/storage/snapshot/20230410102306.9.180//2774718/217609978/2774718.hdr
346
1
    std::string remote_url_prefix = fmt::format("{}&file={}", _base_url, _remote_path);
347
348
1
    LOG(INFO) << "list remote files: " << remote_url_prefix << ", job: " << _snapshot_loader._job_id
349
1
              << ", task id: " << _snapshot_loader._task_id << ", remote be: " << _remote_be_addr;
350
351
1
    std::string remote_file_list_str;
352
1
    auto list_files_cb = [&remote_url_prefix, &remote_file_list_str](HttpClient* client) {
353
1
        RETURN_IF_ERROR(client->init(remote_url_prefix));
354
1
        client->set_timeout_ms(config::download_binlog_meta_timeout_ms);
355
1
        return client->execute(&remote_file_list_str);
356
1
    };
357
1
    RETURN_IF_ERROR(HttpClient::execute_with_retry(kDownloadFileMaxRetry, 1, list_files_cb));
358
359
1
    _remote_file_list = absl::StrSplit(remote_file_list_str, "\n", absl::SkipWhitespace());
360
361
    // find hdr file
362
1
    auto hdr_file =
363
1
            std::find_if(_remote_file_list.begin(), _remote_file_list.end(),
364
1
                         [](const std::string& filename) { return _end_with(filename, ".hdr"); });
365
1
    if (hdr_file == _remote_file_list.end()) {
366
0
        std::string msg =
367
0
                fmt::format("can't find hdr file in remote snapshot path: {}", _remote_path);
368
0
        LOG(WARNING) << msg;
369
0
        return Status::RuntimeError(std::move(msg));
370
0
    }
371
1
    _remote_hdr_filename = *hdr_file;
372
1
    _remote_file_list.erase(hdr_file);
373
374
1
    return Status::OK();
375
1
}
376
377
1
Status SnapshotHttpDownloader::_download_hdr_file() {
378
1
    RemoteFileStat remote_hdr_stat;
379
1
    std::string remote_hdr_file_url =
380
1
            fmt::format("{}&file={}/{}", _base_url, _remote_path, _remote_hdr_filename);
381
1
    auto status = _get_http_file_stat(remote_hdr_file_url, &remote_hdr_stat);
382
1
    if (!status.ok()) {
383
0
        LOG(WARNING) << "failed to get remote hdr file stat: " << remote_hdr_file_url
384
0
                     << ", error: " << status.to_string();
385
0
        return status;
386
0
    }
387
388
1
    std::string hdr_filename = _remote_hdr_filename + ".tmp";
389
1
    std::string hdr_file = _local_path + "/" + hdr_filename;
390
1
    status = _download_http_file(_tablet->data_dir(), remote_hdr_file_url, hdr_file,
391
1
                                 remote_hdr_stat);
392
1
    if (!status.ok()) {
393
0
        LOG(WARNING) << "failed to download remote hdr file: " << remote_hdr_file_url
394
0
                     << ", error: " << status.to_string();
395
0
        return status;
396
0
    }
397
1
    _tmp_hdr_file = hdr_file;
398
1
    _remote_hdr_filestat = remote_hdr_stat;
399
1
    return Status::OK();
400
1
}
401
402
1
Status SnapshotHttpDownloader::_link_same_rowset_files() {
403
1
    std::string local_hdr_file_path = _local_path + "/" + _local_hdr_filename;
404
405
    // load local tablet meta
406
1
    TabletMetaPB local_tablet_meta;
407
1
    auto status = TabletMeta::load_from_file(local_hdr_file_path, &local_tablet_meta);
408
1
    if (!status.ok()) {
409
        // This file might broken because of the partial downloading.
410
0
        LOG(WARNING) << "failed to load local tablet meta: " << local_hdr_file_path
411
0
                     << ", skip link same rowset files, error: " << status.to_string();
412
0
        return Status::OK();
413
0
    }
414
415
    // load remote tablet meta
416
1
    TabletMetaPB remote_tablet_meta;
417
1
    status = TabletMeta::load_from_file(_tmp_hdr_file, &remote_tablet_meta);
418
1
    if (!status.ok()) {
419
0
        LOG(WARNING) << "failed to load remote tablet meta: " << _tmp_hdr_file
420
0
                     << ", error: " << status.to_string();
421
0
        return status;
422
0
    }
423
424
1
    LOG(INFO) << "link rowset files by compare " << _local_hdr_filename << " and "
425
1
              << _remote_hdr_filename;
426
427
1
    std::unordered_map<std::string, const RowsetMetaPB&> remote_rowset_metas;
428
2
    for (const auto& rowset_meta : remote_tablet_meta.rs_metas()) {
429
2
        if (rowset_meta.has_resource_id()) { // skip remote rowset
430
0
            continue;
431
0
        }
432
2
        remote_rowset_metas.insert({rowset_meta.rowset_id_v2(), rowset_meta});
433
2
    }
434
435
1
    std::unordered_map<std::string, const RowsetMetaPB&> local_rowset_metas;
436
2
    for (const auto& rowset_meta : local_tablet_meta.rs_metas()) {
437
2
        if (rowset_meta.has_resource_id()) {
438
0
            continue;
439
0
        }
440
2
        local_rowset_metas.insert({rowset_meta.rowset_id_v2(), rowset_meta});
441
2
    }
442
443
2
    for (const auto& local_rowset_meta : local_tablet_meta.rs_metas()) {
444
2
        if (local_rowset_meta.has_resource_id() || !local_rowset_meta.has_source_rowset_id()) {
445
2
            continue;
446
2
        }
447
448
0
        auto remote_rowset_meta = remote_rowset_metas.find(local_rowset_meta.source_rowset_id());
449
0
        if (remote_rowset_meta == remote_rowset_metas.end()) {
450
0
            continue;
451
0
        }
452
453
0
        const auto& remote_rowset_id = remote_rowset_meta->first;
454
0
        const auto& remote_rowset_meta_pb = remote_rowset_meta->second;
455
0
        const auto& local_rowset_id = local_rowset_meta.rowset_id_v2();
456
0
        auto remote_tablet_id = remote_rowset_meta_pb.tablet_id();
457
0
        if (local_rowset_meta.start_version() != remote_rowset_meta_pb.start_version() ||
458
0
            local_rowset_meta.end_version() != remote_rowset_meta_pb.end_version()) {
459
0
            continue;
460
0
        }
461
462
0
        LOG(INFO) << "rowset " << local_rowset_id << " was downloaded from remote tablet "
463
0
                  << remote_tablet_id << " rowset " << remote_rowset_id
464
0
                  << ", directly link files instead of downloading";
465
466
        // Since the rowset meta are the same, we can link the local rowset files as
467
        // the downloaded remote rowset files.
468
0
        for (const auto& [local_file, local_filestat] : _local_files) {
469
0
            if (!local_file.starts_with(local_rowset_id)) {
470
0
                continue;
471
0
            }
472
473
0
            std::string remote_file = local_file;
474
0
            remote_file.replace(0, local_rowset_id.size(), remote_rowset_id);
475
0
            std::string local_file_path = _local_path + "/" + local_file;
476
0
            std::string remote_file_path = _local_path + "/" + remote_file;
477
478
0
            bool exist = true;
479
0
            RETURN_IF_ERROR(io::global_local_filesystem()->exists(remote_file_path, &exist));
480
0
            if (exist) {
481
0
                continue;
482
0
            }
483
484
0
            LOG(INFO) << "link file from " << local_file_path << " to " << remote_file_path;
485
0
            if (!io::global_local_filesystem()->link_file(local_file_path, remote_file_path)) {
486
0
                std::string msg = fmt::format("link file failed from {} to {}, err: {}",
487
0
                                              local_file_path, remote_file_path, strerror(errno));
488
0
                LOG(WARNING) << msg;
489
0
                return Status::InternalError(std::move(msg));
490
0
            }
491
492
0
            _local_files[remote_file] = local_filestat;
493
0
        }
494
0
    }
495
496
2
    for (const auto& remote_rowset_meta : remote_tablet_meta.rs_metas()) {
497
2
        if (remote_rowset_meta.has_resource_id() || !remote_rowset_meta.has_source_rowset_id()) {
498
0
            continue;
499
0
        }
500
501
2
        auto local_rowset_meta = local_rowset_metas.find(remote_rowset_meta.source_rowset_id());
502
2
        if (local_rowset_meta == local_rowset_metas.end()) {
503
0
            continue;
504
0
        }
505
506
2
        const auto& local_rowset_id = local_rowset_meta->first;
507
2
        const auto& local_rowset_meta_pb = local_rowset_meta->second;
508
2
        const auto& remote_rowset_id = remote_rowset_meta.rowset_id_v2();
509
2
        auto local_tablet_id = local_rowset_meta_pb.tablet_id();
510
511
2
        if (remote_rowset_meta.start_version() != local_rowset_meta_pb.start_version() ||
512
2
            remote_rowset_meta.end_version() != local_rowset_meta_pb.end_version()) {
513
0
            continue;
514
0
        }
515
516
2
        LOG(INFO) << "remote rowset " << remote_rowset_id << " was derived from local tablet "
517
2
                  << local_tablet_id << " rowset " << local_rowset_id
518
2
                  << ", skip downloading these files";
519
520
2
        for (const auto& remote_file : _remote_file_list) {
521
2
            if (!remote_file.starts_with(remote_rowset_id)) {
522
1
                continue;
523
1
            }
524
525
1
            std::string local_file = remote_file;
526
1
            local_file.replace(0, remote_rowset_id.size(), local_rowset_id);
527
1
            std::string local_file_path = _local_path + "/" + local_file;
528
1
            std::string remote_file_path = _local_path + "/" + remote_file;
529
530
1
            bool exist = false;
531
1
            RETURN_IF_ERROR(io::global_local_filesystem()->exists(remote_file_path, &exist));
532
1
            if (exist) {
533
0
                continue;
534
0
            }
535
536
1
            LOG(INFO) << "link file from " << local_file_path << " to " << remote_file_path;
537
1
            if (!io::global_local_filesystem()->link_file(local_file_path, remote_file_path)) {
538
0
                std::string msg = fmt::format("link file failed from {} to {}, err: {}",
539
0
                                              local_file_path, remote_file_path, strerror(errno));
540
0
                LOG(WARNING) << msg;
541
0
                return Status::InternalError(std::move(msg));
542
1
            } else {
543
1
                auto it = _local_files.find(local_file);
544
1
                if (it != _local_files.end()) {
545
1
                    _local_files[remote_file] = it->second;
546
1
                } else {
547
0
                    std::string msg =
548
0
                            fmt::format("local file {} don't exist in _local_files, err: {}",
549
0
                                        local_file, strerror(errno));
550
0
                    LOG(WARNING) << msg;
551
0
                    return Status::InternalError(std::move(msg));
552
0
                }
553
1
            }
554
1
        }
555
2
    }
556
1
    return Status::OK();
557
1
}
558
559
1
Status SnapshotHttpDownloader::_get_remote_file_stats() {
560
1
    for (const auto& filename : _remote_file_list) {
561
1
        if (_report_progress_callback) {
562
0
            RETURN_IF_ERROR(_report_progress_callback());
563
0
        }
564
565
1
        std::string remote_file_url =
566
1
                fmt::format("{}&file={}/{}", _base_url, _remote_path, filename);
567
568
1
        RemoteFileStat remote_filestat;
569
1
        RETURN_IF_ERROR(_get_http_file_stat(remote_file_url, &remote_filestat));
570
1
        _remote_files[filename] = remote_filestat;
571
1
    }
572
573
1
    return Status::OK();
574
1
}
575
576
1
void SnapshotHttpDownloader::_get_need_download_files() {
577
1
    for (const auto& [remote_file, remote_filestat] : _remote_files) {
578
1
        LOG(INFO) << "remote file: " << remote_file << ", size: " << remote_filestat.size
579
1
                  << ", md5: " << remote_filestat.md5;
580
1
        auto it = _local_files.find(remote_file);
581
1
        if (it == _local_files.end()) {
582
0
            _need_download_files.emplace_back(remote_file);
583
0
            continue;
584
0
        }
585
586
1
        if (auto& local_filestat = it->second; local_filestat.size != remote_filestat.size) {
587
0
            _need_download_files.emplace_back(remote_file);
588
0
            continue;
589
0
        }
590
591
1
        if (auto& local_filestat = it->second; local_filestat.md5 != remote_filestat.md5) {
592
0
            _need_download_files.emplace_back(remote_file);
593
0
            continue;
594
0
        }
595
596
1
        LOG(INFO) << fmt::format("file {} already exists, skip download url {}", remote_file,
597
1
                                 remote_filestat.url);
598
1
    }
599
1
}
600
601
0
Status SnapshotHttpDownloader::_download_files() {
602
0
    DataDir* data_dir = _tablet->data_dir();
603
604
0
    uint64_t total_file_size = 0;
605
0
    MonotonicStopWatch watch(true);
606
0
    for (auto& filename : _need_download_files) {
607
0
        if (_report_progress_callback) {
608
0
            RETURN_IF_ERROR(_report_progress_callback());
609
0
        }
610
611
0
        auto& remote_filestat = _remote_files[filename];
612
0
        auto file_size = remote_filestat.size;
613
0
        auto& remote_file_url = remote_filestat.url;
614
0
        auto& remote_file_md5 = remote_filestat.md5;
615
616
0
        std::string local_filename;
617
0
        RETURN_IF_ERROR(
618
0
                _snapshot_loader._replace_tablet_id(filename, _local_tablet_id, &local_filename));
619
0
        std::string local_file_path = _local_path + "/" + local_filename;
620
621
0
        RETURN_IF_ERROR(
622
0
                _download_http_file(data_dir, remote_file_url, local_file_path, remote_filestat));
623
0
        total_file_size += file_size;
624
625
        // local_files always keep the updated local files
626
0
        _local_files[filename] = LocalFileStat {file_size, remote_file_md5};
627
0
    }
628
629
0
    uint64_t total_time_ms = watch.elapsed_time() / 1000 / 1000;
630
0
    total_time_ms = total_time_ms > 0 ? total_time_ms : 0;
631
0
    double copy_rate = 0.0;
632
0
    if (total_time_ms > 0) {
633
0
        copy_rate =
634
0
                static_cast<double>(total_file_size) / static_cast<double>(total_time_ms) / 1000.0;
635
0
    }
636
0
    LOG(INFO) << fmt::format(
637
0
            "succeed to copy remote tablet {} to local tablet {}, total downloading {} files, "
638
0
            "total file size: {} B, cost: {} ms, rate: {} MB/s",
639
0
            _remote_tablet_id, _local_tablet_id, _need_download_files.size(), total_file_size,
640
0
            total_time_ms, copy_rate);
641
642
0
    return Status::OK();
643
0
}
644
645
1
Status SnapshotHttpDownloader::_install_remote_hdr_file() {
646
1
    std::string local_hdr_filename;
647
1
    RETURN_IF_ERROR(_snapshot_loader._replace_tablet_id(_remote_hdr_filename, _local_tablet_id,
648
1
                                                        &local_hdr_filename));
649
1
    std::string local_hdr_file_path = _local_path + "/" + local_hdr_filename;
650
651
1
    auto status = io::global_local_filesystem()->rename(_tmp_hdr_file, local_hdr_file_path);
652
1
    if (!status.ok()) {
653
0
        LOG(WARNING) << "failed to install remote hdr file from: " << _tmp_hdr_file << " to"
654
0
                     << local_hdr_file_path << ", error: " << status.to_string();
655
0
        return Status::RuntimeError("failed install remote hdr file {} from tmp {}, error: {}",
656
0
                                    local_hdr_file_path, _tmp_hdr_file, status.to_string());
657
0
    }
658
659
    // also save the hdr file into remote files.
660
1
    _remote_files[_remote_hdr_filename] = _remote_hdr_filestat;
661
662
1
    return Status::OK();
663
1
}
664
665
1
Status SnapshotHttpDownloader::_delete_orphan_files() {
666
    // local_files: contain all remote files and local files
667
    // finally, delete local files which are not in remote
668
3
    for (const auto& [local_file, local_filestat] : _local_files) {
669
        // replace the tablet id in local file name with the remote tablet id,
670
        // in order to compare the file name.
671
3
        std::string new_name;
672
3
        Status st = _snapshot_loader._replace_tablet_id(local_file, _remote_tablet_id, &new_name);
673
3
        if (!st.ok()) {
674
0
            LOG(WARNING) << "failed to replace tablet id. unknown local file: " << st
675
0
                         << ". ignore it";
676
0
            continue;
677
0
        }
678
3
        VLOG_CRITICAL << "new file name after replace tablet id: " << new_name;
679
3
        const auto& find = _remote_files.find(new_name);
680
3
        if (find != _remote_files.end()) {
681
2
            continue;
682
2
        }
683
684
        // delete
685
1
        std::string full_local_file = _local_path + "/" + local_file;
686
1
        LOG(INFO) << "begin to delete local snapshot file: " << full_local_file
687
1
                  << ", it does not exist in remote";
688
1
        if (remove(full_local_file.c_str()) != 0) {
689
0
            LOG(WARNING) << "failed to delete unknown local file: " << full_local_file
690
0
                         << ", error: " << strerror(errno) << ", file size: " << local_filestat.size
691
0
                         << ", ignore it";
692
0
        }
693
1
    }
694
1
    return Status::OK();
695
1
}
696
697
1
Status SnapshotHttpDownloader::download() {
698
    // Take a lock to protect the local snapshot path.
699
1
    auto local_snapshot_guard = LocalSnapshotLock::instance().acquire(_local_path);
700
701
    // Step 1: Validate local tablet snapshot paths
702
1
    bool res = true;
703
1
    RETURN_IF_ERROR(io::global_local_filesystem()->is_directory(_local_path, &res));
704
1
    if (!res) {
705
0
        std::string msg =
706
0
                fmt::format("snapshot path is not directory or does not exist: {}", _local_path);
707
0
        LOG(WARNING) << msg;
708
0
        return Status::RuntimeError(std::move(msg));
709
0
    }
710
711
    // Step 2: get all local files
712
1
    RETURN_IF_ERROR(_load_existing_files());
713
714
    // Step 3: Validate remote tablet snapshot paths && remote files map
715
1
    RETURN_IF_ERROR(_list_remote_files());
716
717
    // Step 4: download hdr file to a tmp file
718
1
    RETURN_IF_ERROR(_download_hdr_file());
719
720
    // Step 5: link same rowset files, if local tablet meta file exists
721
1
    if (!_local_hdr_filename.empty()) {
722
1
        RETURN_IF_ERROR(_link_same_rowset_files());
723
1
    }
724
725
    // Step 6: get all remote file stats
726
1
    RETURN_IF_ERROR(_get_remote_file_stats());
727
728
    // Step 7: get all need download files & download them
729
1
    _get_need_download_files();
730
1
    if (!_need_download_files.empty()) {
731
0
        RETURN_IF_ERROR(_download_files());
732
0
    }
733
734
    // Step 8: install remote hdr file from tmp file
735
1
    RETURN_IF_ERROR(_install_remote_hdr_file());
736
737
    // Step 9: delete orphan files
738
1
    RETURN_IF_ERROR(_delete_orphan_files());
739
740
1
    return Status::OK();
741
1
}
742
743
SnapshotLoader::SnapshotLoader(StorageEngine& engine, ExecEnv* env, int64_t job_id, int64_t task_id,
744
                               const TNetworkAddress& broker_addr,
745
                               const std::map<std::string, std::string>& prop)
746
4
        : _engine(engine),
747
4
          _env(env),
748
4
          _job_id(job_id),
749
4
          _task_id(task_id),
750
4
          _broker_addr(broker_addr),
751
4
          _prop(prop) {
752
4
    _resource_ctx = ResourceContext::create_shared();
753
4
    TUniqueId tid;
754
4
    tid.hi = _job_id;
755
4
    tid.lo = _task_id;
756
4
    _resource_ctx->task_controller()->set_task_id(tid);
757
4
    std::shared_ptr<MemTrackerLimiter> mem_tracker = MemTrackerLimiter::create_shared(
758
4
            MemTrackerLimiter::Type::OTHER,
759
4
            fmt::format("SnapshotLoader#Id={}", ((UniqueId)tid).to_string()));
760
4
    _resource_ctx->memory_context()->set_mem_tracker(mem_tracker);
761
4
}
762
763
0
Status SnapshotLoader::init(TStorageBackendType::type type, const std::string& location) {
764
0
    if (TStorageBackendType::type::S3 == type) {
765
0
        S3Conf s3_conf;
766
0
        S3URI s3_uri(location);
767
0
        RETURN_IF_ERROR(s3_uri.parse());
768
0
        RETURN_IF_ERROR(S3ClientFactory::convert_properties_to_s3_conf(_prop, s3_uri, &s3_conf));
769
0
        _remote_fs =
770
0
                DORIS_TRY(io::S3FileSystem::create(std::move(s3_conf), io::FileSystem::TMP_FS_ID));
771
0
    } else if (TStorageBackendType::type::HDFS == type) {
772
0
        THdfsParams hdfs_params = parse_properties(_prop);
773
0
        _remote_fs = DORIS_TRY(io::HdfsFileSystem::create(hdfs_params, hdfs_params.fs_name,
774
0
                                                          io::FileSystem::TMP_FS_ID, nullptr));
775
0
    } else if (TStorageBackendType::type::BROKER == type) {
776
0
        std::shared_ptr<io::BrokerFileSystem> fs;
777
0
        _remote_fs = DORIS_TRY(
778
0
                io::BrokerFileSystem::create(_broker_addr, _prop, io::FileSystem::TMP_FS_ID));
779
0
    } else {
780
0
        return Status::InternalError("Unknown storage type: {}", type);
781
0
    }
782
0
    return Status::OK();
783
0
}
784
785
4
SnapshotLoader::~SnapshotLoader() = default;
786
787
Status SnapshotLoader::upload(const std::map<std::string, std::string>& src_to_dest_path,
788
0
                              std::map<int64_t, std::vector<std::string>>* tablet_files) {
789
0
    if (!_remote_fs) {
790
0
        return Status::InternalError("Storage backend not initialized.");
791
0
    }
792
0
    LOG(INFO) << "begin to upload snapshot files. num: " << src_to_dest_path.size()
793
0
              << ", broker addr: " << _broker_addr << ", job: " << _job_id << ", task" << _task_id;
794
795
    // check if job has already been cancelled
796
0
    int tmp_counter = 1;
797
0
    RETURN_IF_ERROR(_report_every(0, &tmp_counter, 0, 0, TTaskType::type::UPLOAD));
798
799
0
    Status status = Status::OK();
800
    // 1. validate local tablet snapshot paths
801
0
    RETURN_IF_ERROR(_check_local_snapshot_paths(src_to_dest_path, true));
802
803
    // 2. for each src path, upload it to remote storage
804
    // we report to frontend for every 10 files, and we will cancel the job if
805
    // the job has already been cancelled in frontend.
806
0
    int report_counter = 0;
807
0
    int total_num = doris::cast_set<int>(src_to_dest_path.size());
808
0
    int finished_num = 0;
809
0
    for (const auto& iter : src_to_dest_path) {
810
0
        const std::string& src_path = iter.first;
811
0
        const std::string& dest_path = iter.second;
812
813
        // Take a lock to protect the local snapshot path.
814
0
        auto local_snapshot_guard = LocalSnapshotLock::instance().acquire(src_path);
815
816
0
        int64_t tablet_id = 0;
817
0
        int32_t schema_hash = 0;
818
0
        RETURN_IF_ERROR(
819
0
                _get_tablet_id_and_schema_hash_from_file_path(src_path, &tablet_id, &schema_hash));
820
821
        // 2.1 get existing files from remote path
822
0
        std::map<std::string, FileStat> remote_files;
823
0
        RETURN_IF_ERROR(_list_with_checksum(dest_path, &remote_files));
824
825
0
        for (auto& tmp : remote_files) {
826
0
            VLOG_CRITICAL << "get remote file: " << tmp.first << ", checksum: " << tmp.second.md5;
827
0
        }
828
829
        // 2.2 list local files
830
0
        std::vector<std::string> local_files;
831
0
        std::vector<std::string> local_files_with_checksum;
832
0
        RETURN_IF_ERROR(_get_existing_files_from_local(src_path, &local_files));
833
834
        // 2.3 iterate local files
835
0
        for (auto& local_file : local_files) {
836
0
            RETURN_IF_ERROR(_report_every(10, &report_counter, finished_num, total_num,
837
0
                                          TTaskType::type::UPLOAD));
838
839
            // calc md5sum of localfile
840
0
            std::string md5sum;
841
0
            RETURN_IF_ERROR(
842
0
                    io::global_local_filesystem()->md5sum(src_path + "/" + local_file, &md5sum));
843
0
            VLOG_CRITICAL << "get file checksum: " << local_file << ": " << md5sum;
844
0
            local_files_with_checksum.push_back(local_file + "." + md5sum);
845
846
            // check if this local file need upload
847
0
            bool need_upload = false;
848
0
            auto find = remote_files.find(local_file);
849
0
            if (find != remote_files.end()) {
850
0
                if (md5sum != find->second.md5) {
851
                    // remote storage file exist, but with different checksum
852
0
                    LOG(WARNING) << "remote file checksum is invalid. remote: " << find->first
853
0
                                 << ", local: " << md5sum;
854
                    // TODO(cmy): save these files and delete them later
855
0
                    need_upload = true;
856
0
                }
857
0
            } else {
858
0
                need_upload = true;
859
0
            }
860
861
0
            if (!need_upload) {
862
0
                VLOG_CRITICAL << "file exist in remote path, no need to upload: " << local_file;
863
0
                continue;
864
0
            }
865
866
            // upload
867
0
            std::string remote_path = dest_path + '/' + local_file;
868
0
            std::string local_path = src_path + '/' + local_file;
869
0
            RETURN_IF_ERROR(upload_with_checksum(*_remote_fs, local_path, remote_path, md5sum));
870
0
        } // end for each tablet's local files
871
872
0
        tablet_files->emplace(tablet_id, local_files_with_checksum);
873
0
        finished_num++;
874
0
        LOG(INFO) << "finished to write tablet to remote. local path: " << src_path
875
0
                  << ", remote path: " << dest_path;
876
0
    } // end for each tablet path
877
878
0
    LOG(INFO) << "finished to upload snapshots. job: " << _job_id << ", task id: " << _task_id;
879
0
    return status;
880
0
}
881
882
/*
883
 * Download snapshot files from remote.
884
 * After downloaded, the local dir should contains all files existing in remote,
885
 * may also contains several useless files.
886
 */
887
Status SnapshotLoader::download(const std::map<std::string, std::string>& src_to_dest_path,
888
0
                                std::vector<int64_t>* downloaded_tablet_ids) {
889
0
    if (!_remote_fs) {
890
0
        return Status::InternalError("Storage backend not initialized.");
891
0
    }
892
0
    LOG(INFO) << "begin to download snapshot files. num: " << src_to_dest_path.size()
893
0
              << ", broker addr: " << _broker_addr << ", job: " << _job_id
894
0
              << ", task id: " << _task_id;
895
896
    // check if job has already been cancelled
897
0
    int tmp_counter = 1;
898
0
    RETURN_IF_ERROR(_report_every(0, &tmp_counter, 0, 0, TTaskType::type::DOWNLOAD));
899
900
0
    Status status = Status::OK();
901
    // 1. validate local tablet snapshot paths
902
0
    RETURN_IF_ERROR(_check_local_snapshot_paths(src_to_dest_path, false));
903
904
    // 2. for each src path, download it to local storage
905
0
    int report_counter = 0;
906
0
    int total_num = doris::cast_set<int>(src_to_dest_path.size());
907
0
    int finished_num = 0;
908
0
    for (const auto& iter : src_to_dest_path) {
909
0
        const std::string& remote_path = iter.first;
910
0
        const std::string& local_path = iter.second;
911
912
        // Take a lock to protect the local snapshot path.
913
0
        auto local_snapshot_guard = LocalSnapshotLock::instance().acquire(local_path);
914
915
0
        int64_t local_tablet_id = 0;
916
0
        int32_t schema_hash = 0;
917
0
        RETURN_IF_ERROR(_get_tablet_id_and_schema_hash_from_file_path(local_path, &local_tablet_id,
918
0
                                                                      &schema_hash));
919
0
        if (downloaded_tablet_ids != nullptr) {
920
0
            downloaded_tablet_ids->push_back(local_tablet_id);
921
0
        }
922
923
0
        int64_t remote_tablet_id;
924
0
        RETURN_IF_ERROR(_get_tablet_id_from_remote_path(remote_path, &remote_tablet_id));
925
0
        VLOG_CRITICAL << "get local tablet id: " << local_tablet_id
926
0
                      << ", schema hash: " << schema_hash
927
0
                      << ", remote tablet id: " << remote_tablet_id;
928
929
        // 2.1. get local files
930
0
        std::vector<std::string> local_files;
931
0
        RETURN_IF_ERROR(_get_existing_files_from_local(local_path, &local_files));
932
933
        // 2.2. get remote files
934
0
        std::map<std::string, FileStat> remote_files;
935
0
        RETURN_IF_ERROR(_list_with_checksum(remote_path, &remote_files));
936
0
        if (remote_files.empty()) {
937
0
            std::stringstream ss;
938
0
            ss << "get nothing from remote path: " << remote_path;
939
0
            LOG(WARNING) << ss.str();
940
0
            return Status::InternalError(ss.str());
941
0
        }
942
943
0
        TabletSharedPtr tablet = _engine.tablet_manager()->get_tablet(local_tablet_id);
944
0
        if (tablet == nullptr) {
945
0
            std::stringstream ss;
946
0
            ss << "failed to get local tablet: " << local_tablet_id;
947
0
            LOG(WARNING) << ss.str();
948
0
            return Status::InternalError(ss.str());
949
0
        }
950
0
        DataDir* data_dir = tablet->data_dir();
951
952
0
        for (auto& remote_iter : remote_files) {
953
0
            RETURN_IF_ERROR(_report_every(10, &report_counter, finished_num, total_num,
954
0
                                          TTaskType::type::DOWNLOAD));
955
956
0
            bool need_download = false;
957
0
            const std::string& remote_file = remote_iter.first;
958
0
            const FileStat& file_stat = remote_iter.second;
959
0
            auto find = std::find(local_files.begin(), local_files.end(), remote_file);
960
0
            if (find == local_files.end()) {
961
                // remote file does not exist in local, download it
962
0
                need_download = true;
963
0
            } else {
964
0
                if (_end_with(remote_file, ".hdr")) {
965
                    // this is a header file, download it.
966
0
                    need_download = true;
967
0
                } else {
968
                    // check checksum
969
0
                    std::string local_md5sum;
970
0
                    Status st = io::global_local_filesystem()->md5sum(
971
0
                            local_path + "/" + remote_file, &local_md5sum);
972
0
                    if (!st.ok()) {
973
0
                        LOG(WARNING) << "failed to get md5sum of local file: " << remote_file
974
0
                                     << ". msg: " << st << ". download it";
975
0
                        need_download = true;
976
0
                    } else {
977
0
                        VLOG_CRITICAL << "get local file checksum: " << remote_file << ": "
978
0
                                      << local_md5sum;
979
0
                        if (file_stat.md5 != local_md5sum) {
980
                            // file's checksum does not equal, download it.
981
0
                            need_download = true;
982
0
                        }
983
0
                    }
984
0
                }
985
0
            }
986
987
0
            if (!need_download) {
988
0
                LOG(INFO) << "remote file already exist in local, no need to download."
989
0
                          << ", file: " << remote_file;
990
0
                continue;
991
0
            }
992
993
            // begin to download
994
0
            std::string full_remote_file = remote_path + "/" + remote_file + "." + file_stat.md5;
995
0
            std::string local_file_name;
996
            // we need to replace the tablet_id in remote file name with local tablet id
997
0
            RETURN_IF_ERROR(_replace_tablet_id(remote_file, local_tablet_id, &local_file_name));
998
0
            std::string full_local_file = local_path + "/" + local_file_name;
999
0
            LOG(INFO) << "begin to download from " << full_remote_file << " to " << full_local_file;
1000
0
            size_t file_len = file_stat.size;
1001
1002
            // check disk capacity
1003
0
            if (data_dir->reach_capacity_limit(file_len)) {
1004
0
                return Status::Error<ErrorCode::EXCEEDED_LIMIT>(
1005
0
                        "reach the capacity limit of path {}, file_size={}", data_dir->path(),
1006
0
                        file_len);
1007
0
            }
1008
            // remove file which will be downloaded now.
1009
            // this file will be added to local_files if it be downloaded successfully.
1010
0
            if (find != local_files.end()) {
1011
0
                local_files.erase(find);
1012
0
            }
1013
0
            RETURN_IF_ERROR(_remote_fs->download(full_remote_file, full_local_file));
1014
1015
            // 3. check md5 of the downloaded file
1016
0
            std::string downloaded_md5sum;
1017
0
            RETURN_IF_ERROR(
1018
0
                    io::global_local_filesystem()->md5sum(full_local_file, &downloaded_md5sum));
1019
0
            VLOG_CRITICAL << "get downloaded file checksum: " << full_local_file << ": "
1020
0
                          << downloaded_md5sum;
1021
0
            if (downloaded_md5sum != file_stat.md5) {
1022
0
                std::stringstream ss;
1023
0
                ss << "invalid md5 of downloaded file: " << full_local_file
1024
0
                   << ", expected: " << file_stat.md5 << ", get: " << downloaded_md5sum;
1025
0
                LOG(WARNING) << ss.str();
1026
0
                return Status::InternalError(ss.str());
1027
0
            }
1028
1029
            // local_files always keep the updated local files
1030
0
            local_files.push_back(local_file_name);
1031
0
            LOG(INFO) << "finished to download file via broker. file: " << full_local_file
1032
0
                      << ", length: " << file_len;
1033
0
        } // end for all remote files
1034
1035
        // finally, delete local files which are not in remote
1036
0
        for (const auto& local_file : local_files) {
1037
            // replace the tablet id in local file name with the remote tablet id,
1038
            // in order to compare the file name.
1039
0
            std::string new_name;
1040
0
            Status st = _replace_tablet_id(local_file, remote_tablet_id, &new_name);
1041
0
            if (!st.ok()) {
1042
0
                LOG(WARNING) << "failed to replace tablet id. unknown local file: " << st
1043
0
                             << ". ignore it";
1044
0
                continue;
1045
0
            }
1046
0
            VLOG_CRITICAL << "new file name after replace tablet id: " << new_name;
1047
0
            const auto& find = remote_files.find(new_name);
1048
0
            if (find != remote_files.end()) {
1049
0
                continue;
1050
0
            }
1051
1052
            // delete
1053
0
            std::string full_local_file = local_path + "/" + local_file;
1054
0
            VLOG_CRITICAL << "begin to delete local snapshot file: " << full_local_file
1055
0
                          << ", it does not exist in remote";
1056
0
            if (remove(full_local_file.c_str()) != 0) {
1057
0
                LOG(WARNING) << "failed to delete unknown local file: " << full_local_file
1058
0
                             << ", ignore it";
1059
0
            }
1060
0
        }
1061
1062
0
        finished_num++;
1063
0
    } // end for src_to_dest_path
1064
1065
0
    LOG(INFO) << "finished to download snapshots. job: " << _job_id << ", task id: " << _task_id;
1066
0
    return status;
1067
0
}
1068
1069
Status SnapshotLoader::remote_http_download(
1070
        const std::vector<TRemoteTabletSnapshot>& remote_tablet_snapshots,
1071
1
        std::vector<int64_t>* downloaded_tablet_ids) {
1072
    // check if job has already been cancelled
1073
1074
#ifndef BE_TEST
1075
    int tmp_counter = 1;
1076
    RETURN_IF_ERROR(_report_every(0, &tmp_counter, 0, 0, TTaskType::type::DOWNLOAD));
1077
#endif
1078
1
    Status status = Status::OK();
1079
1080
1
    for (const auto& remote_tablet_snapshot : remote_tablet_snapshots) {
1081
1
        auto local_tablet_id = remote_tablet_snapshot.local_tablet_id;
1082
1
        const auto& local_path = remote_tablet_snapshot.local_snapshot_path;
1083
1
        const auto& remote_path = remote_tablet_snapshot.remote_snapshot_path;
1084
1085
1
        LOG(INFO) << fmt::format(
1086
1
                "download snapshots via http. job: {}, task id: {}, local dir: {}, remote dir: {}",
1087
1
                _job_id, _task_id, local_path, remote_path);
1088
1089
1
        TabletSharedPtr tablet = _engine.tablet_manager()->get_tablet(local_tablet_id);
1090
1
        if (tablet == nullptr) {
1091
0
            std::string msg = fmt::format("failed to get local tablet: {}", local_tablet_id);
1092
0
            LOG(WARNING) << msg;
1093
0
            return Status::RuntimeError(std::move(msg));
1094
0
        }
1095
1096
1
        if (downloaded_tablet_ids != nullptr) {
1097
1
            downloaded_tablet_ids->push_back(local_tablet_id);
1098
1
        }
1099
1100
1
        SnapshotHttpDownloader downloader(remote_tablet_snapshot, std::move(tablet), *this);
1101
#ifndef BE_TEST
1102
        int report_counter = 0;
1103
        int finished_num = 0;
1104
        int total_num = doris::cast_set<int>(remote_tablet_snapshots.size());
1105
        downloader.set_report_progress_callback(
1106
                [this, &report_counter, &finished_num, &total_num]() {
1107
                    return _report_every(10, &report_counter, finished_num, total_num,
1108
                                         TTaskType::type::DOWNLOAD);
1109
                });
1110
#endif
1111
1112
1
        RETURN_IF_ERROR(downloader.download());
1113
1
        _set_http_download_files_num(downloader.get_download_file_num());
1114
1115
#ifndef BE_TEST
1116
        ++finished_num;
1117
#endif
1118
1
    }
1119
1120
1
    LOG(INFO) << "finished to download snapshots. job: " << _job_id << ", task id: " << _task_id;
1121
1
    return status;
1122
1
}
1123
1124
// move the snapshot files in snapshot_path
1125
// to tablet_path
1126
// If overwrite, just replace the tablet_path with snapshot_path,
1127
// else: (TODO)
1128
//
1129
// MUST hold tablet's header lock, push lock, cumulative lock and base compaction lock
1130
Status SnapshotLoader::move(const std::string& snapshot_path, TabletSharedPtr tablet,
1131
2
                            bool overwrite) {
1132
    // Take a lock to protect the local snapshot path.
1133
2
    auto local_snapshot_guard = LocalSnapshotLock::instance().acquire(snapshot_path);
1134
1135
2
    auto tablet_path = tablet->tablet_path();
1136
2
    auto store_path = tablet->data_dir()->path();
1137
2
    LOG(INFO) << "begin to move snapshot files. from: " << snapshot_path << ", to: " << tablet_path
1138
2
              << ", store: " << store_path << ", job: " << _job_id << ", task id: " << _task_id;
1139
1140
2
    Status status = Status::OK();
1141
1142
    // validate snapshot_path and tablet_path
1143
2
    int64_t snapshot_tablet_id = 0;
1144
2
    int32_t snapshot_schema_hash = 0;
1145
2
    RETURN_IF_ERROR(_get_tablet_id_and_schema_hash_from_file_path(
1146
2
            snapshot_path, &snapshot_tablet_id, &snapshot_schema_hash));
1147
1148
2
    int64_t tablet_id = 0;
1149
2
    int32_t schema_hash = 0;
1150
2
    RETURN_IF_ERROR(
1151
2
            _get_tablet_id_and_schema_hash_from_file_path(tablet_path, &tablet_id, &schema_hash));
1152
1153
2
    if (tablet_id != snapshot_tablet_id || schema_hash != snapshot_schema_hash) {
1154
0
        std::stringstream ss;
1155
0
        ss << "path does not match. snapshot: " << snapshot_path
1156
0
           << ", tablet path: " << tablet_path;
1157
0
        LOG(WARNING) << ss.str();
1158
0
        return Status::InternalError(ss.str());
1159
0
    }
1160
1161
2
    DataDir* store = _engine.get_store(store_path);
1162
2
    if (store == nullptr) {
1163
0
        std::stringstream ss;
1164
0
        ss << "failed to get store by path: " << store_path;
1165
0
        LOG(WARNING) << ss.str();
1166
0
        return Status::InternalError(ss.str());
1167
0
    }
1168
1169
2
    if (!std::filesystem::exists(tablet_path)) {
1170
0
        std::stringstream ss;
1171
0
        ss << "tablet path does not exist: " << tablet_path;
1172
0
        LOG(WARNING) << ss.str();
1173
0
        return Status::InternalError(ss.str());
1174
0
    }
1175
1176
2
    if (!std::filesystem::exists(snapshot_path)) {
1177
0
        std::stringstream ss;
1178
0
        ss << "snapshot path does not exist: " << snapshot_path;
1179
0
        LOG(WARNING) << ss.str();
1180
0
        return Status::InternalError(ss.str());
1181
0
    }
1182
1183
2
    std::string loaded_tag_path = get_loaded_tag_path(snapshot_path);
1184
2
    bool already_loaded = false;
1185
2
    RETURN_IF_ERROR(io::global_local_filesystem()->exists(loaded_tag_path, &already_loaded));
1186
2
    if (already_loaded) {
1187
1
        LOG(INFO) << "snapshot path already moved: " << snapshot_path;
1188
1
        return Status::OK();
1189
1
    }
1190
1191
    // rename the rowset ids and tabletid info in rowset meta
1192
1
    auto res = _engine.snapshot_mgr()->convert_rowset_ids(snapshot_path, tablet_id,
1193
1
                                                          tablet->replica_id(), tablet->table_id(),
1194
1
                                                          tablet->partition_id(), schema_hash);
1195
1
    if (!res.has_value()) [[unlikely]] {
1196
0
        auto err_msg =
1197
0
                fmt::format("failed to convert rowsetids in snapshot: {}, tablet path: {}, err: {}",
1198
0
                            snapshot_path, tablet_path, res.error());
1199
0
        LOG(WARNING) << err_msg;
1200
0
        return Status::InternalError(err_msg);
1201
0
    }
1202
1203
1
    if (!overwrite) {
1204
0
        throw Exception(Status::FatalError("only support overwrite now"));
1205
0
    }
1206
1207
    // Medium migration/clone/checkpoint/compaction may change or check the
1208
    // files and tablet meta, so we need to take these locks.
1209
1
    std::unique_lock migration_lock(tablet->get_migration_lock(), std::try_to_lock);
1210
1
    std::unique_lock base_compact_lock(tablet->get_base_compaction_lock(), std::try_to_lock);
1211
1
    std::unique_lock cumu_compact_lock(tablet->get_cumulative_compaction_lock(), std::try_to_lock);
1212
1
    std::unique_lock cold_compact_lock(tablet->get_cold_compaction_lock(), std::try_to_lock);
1213
1
    std::unique_lock build_idx_lock(tablet->get_build_inverted_index_lock(), std::try_to_lock);
1214
1
    std::unique_lock meta_store_lock(tablet->get_meta_store_lock(), std::try_to_lock);
1215
1
    if (!migration_lock.owns_lock() || !base_compact_lock.owns_lock() ||
1216
1
        !cumu_compact_lock.owns_lock() || !cold_compact_lock.owns_lock() ||
1217
1
        !build_idx_lock.owns_lock() || !meta_store_lock.owns_lock()) {
1218
        // This error should be retryable
1219
0
        auto obtain_lock_status =
1220
0
                Status::ObtainLockFailed("failed to get tablet locks, tablet: {}", tablet_id);
1221
0
        LOG(WARNING) << obtain_lock_status << ", snapshot path: " << snapshot_path
1222
0
                     << ", tablet path: " << tablet_path;
1223
0
        return obtain_lock_status;
1224
0
    }
1225
1226
1
    std::vector<std::string> snapshot_files;
1227
1
    RETURN_IF_ERROR(_get_existing_files_from_local(snapshot_path, &snapshot_files));
1228
1229
    // FIXME: the below logic will demage the tablet files if failed in the middle.
1230
1231
    // 1. simply delete the old dir and replace it with the snapshot dir
1232
1
    try {
1233
        // This remove seems soft enough, because we already get
1234
        // tablet id and schema hash from this path, which
1235
        // means this path is a valid path.
1236
1
        std::filesystem::remove_all(tablet_path);
1237
1
        VLOG_CRITICAL << "remove dir: " << tablet_path;
1238
1
        std::filesystem::create_directory(tablet_path);
1239
1
        VLOG_CRITICAL << "re-create dir: " << tablet_path;
1240
1
    } catch (const std::filesystem::filesystem_error& e) {
1241
0
        std::stringstream ss;
1242
0
        ss << "failed to move tablet path: " << tablet_path << ". err: " << e.what();
1243
0
        LOG(WARNING) << ss.str();
1244
0
        return Status::InternalError(ss.str());
1245
0
    }
1246
1247
    // link files one by one
1248
    // files in snapshot dir will be moved in snapshot clean process
1249
1
    std::vector<std::string> linked_files;
1250
2
    for (auto& file : snapshot_files) {
1251
2
        auto full_src_path = fmt::format("{}/{}", snapshot_path, file);
1252
2
        auto full_dest_path = fmt::format("{}/{}", tablet_path, file);
1253
2
        if (link(full_src_path.c_str(), full_dest_path.c_str()) != 0) {
1254
0
            LOG(WARNING) << "failed to link file from " << full_src_path << " to " << full_dest_path
1255
0
                         << ", err: " << std::strerror(errno);
1256
1257
            // clean the already linked files
1258
0
            for (auto& linked_file : linked_files) {
1259
0
                remove(linked_file.c_str());
1260
0
            }
1261
1262
0
            return Status::InternalError("move tablet failed");
1263
0
        }
1264
2
        linked_files.push_back(full_dest_path);
1265
2
        VLOG_CRITICAL << "link file from " << full_src_path << " to " << full_dest_path;
1266
2
    }
1267
1268
    // snapshot loader not need to change tablet uid
1269
    // fixme: there is no header now and can not call load_one_tablet here
1270
    // reload header
1271
1
    Status ost = _engine.tablet_manager()->load_tablet_from_dir(store, tablet_id, schema_hash,
1272
1
                                                                tablet_path, true);
1273
1
    if (!ost.ok()) {
1274
0
        std::stringstream ss;
1275
0
        ss << "failed to reload header of tablet: " << tablet_id;
1276
0
        LOG(WARNING) << ss.str();
1277
0
        return Status::InternalError(ss.str());
1278
0
    }
1279
1280
    // mark the snapshot path as loaded
1281
1
    RETURN_IF_ERROR(write_loaded_tag(snapshot_path, tablet_id));
1282
1283
1
    LOG(INFO) << "finished to reload header of tablet: " << tablet_id;
1284
1285
1
    return status;
1286
1
}
1287
1288
Status SnapshotLoader::_replace_tablet_id(const std::string& file_name, int64_t tablet_id,
1289
8
                                          std::string* new_file_name) {
1290
    // eg:
1291
    // 10007.hdr
1292
    // 10007_2_2_0_0.idx
1293
    // 10007_2_2_0_0.dat
1294
8
    if (_end_with(file_name, ".hdr")) {
1295
3
        std::stringstream ss;
1296
3
        ss << tablet_id << ".hdr";
1297
3
        *new_file_name = ss.str();
1298
3
        return Status::OK();
1299
5
    } else if (_end_with(file_name, ".idx") || _end_with(file_name, ".dat")) {
1300
4
        *new_file_name = file_name;
1301
4
        return Status::OK();
1302
4
    } else {
1303
1
        return Status::InternalError("invalid tablet file name: {}", file_name);
1304
1
    }
1305
8
}
1306
1307
Status SnapshotLoader::_get_tablet_id_and_schema_hash_from_file_path(const std::string& src_path,
1308
                                                                     int64_t* tablet_id,
1309
6
                                                                     int32_t* schema_hash) {
1310
    // path should be like: /path/.../tablet_id/schema_hash
1311
    // we try to extract tablet_id from path
1312
6
    size_t pos = src_path.find_last_of("/");
1313
6
    if (pos == std::string::npos || pos == src_path.length() - 1) {
1314
1
        return Status::InternalError("failed to get tablet id from path: {}", src_path);
1315
1
    }
1316
1317
5
    std::string schema_hash_str = src_path.substr(pos + 1);
1318
5
    std::stringstream ss1;
1319
5
    ss1 << schema_hash_str;
1320
5
    ss1 >> *schema_hash;
1321
1322
    // skip schema hash part
1323
5
    size_t pos2 = src_path.find_last_of("/", pos - 1);
1324
5
    if (pos2 == std::string::npos) {
1325
0
        return Status::InternalError("failed to get tablet id from path: {}", src_path);
1326
0
    }
1327
1328
5
    std::string tablet_str = src_path.substr(pos2 + 1, pos - pos2);
1329
5
    std::stringstream ss2;
1330
5
    ss2 << tablet_str;
1331
5
    ss2 >> *tablet_id;
1332
1333
5
    VLOG_CRITICAL << "get tablet id " << *tablet_id << ", schema hash: " << *schema_hash
1334
0
                  << " from path: " << src_path;
1335
5
    return Status::OK();
1336
5
}
1337
1338
Status SnapshotLoader::_check_local_snapshot_paths(
1339
4
        const std::map<std::string, std::string>& src_to_dest_path, bool check_src) {
1340
4
    bool res = true;
1341
4
    for (const auto& pair : src_to_dest_path) {
1342
4
        std::string path;
1343
4
        if (check_src) {
1344
2
            path = pair.first;
1345
2
        } else {
1346
2
            path = pair.second;
1347
2
        }
1348
1349
4
        RETURN_IF_ERROR(io::global_local_filesystem()->is_directory(path, &res));
1350
2
        if (!res) {
1351
0
            std::stringstream ss;
1352
0
            ss << "snapshot path is not directory or does not exist: " << path;
1353
0
            LOG(WARNING) << ss.str();
1354
0
            return Status::RuntimeError(ss.str());
1355
0
        }
1356
2
    }
1357
4
    LOG(INFO) << "all local snapshot paths are existing. num: " << src_to_dest_path.size();
1358
2
    return Status::OK();
1359
4
}
1360
1361
Status SnapshotLoader::_get_existing_files_from_local(const std::string& local_path,
1362
3
                                                      std::vector<std::string>* local_files) {
1363
3
    bool exists = true;
1364
3
    std::vector<io::FileInfo> files;
1365
3
    RETURN_IF_ERROR(io::global_local_filesystem()->list(local_path, true, &files, &exists));
1366
4
    for (auto& file : files) {
1367
4
        local_files->push_back(file.file_name);
1368
4
    }
1369
3
    LOG(INFO) << "finished to list files in local path: " << local_path
1370
3
              << ", file num: " << local_files->size();
1371
3
    return Status::OK();
1372
3
}
1373
1374
Status SnapshotLoader::_get_tablet_id_from_remote_path(const std::string& remote_path,
1375
1
                                                       int64_t* tablet_id) {
1376
    // eg:
1377
    // bos://xxx/../__tbl_10004/__part_10003/__idx_10004/__10005
1378
1
    size_t pos = remote_path.find_last_of("_");
1379
1
    if (pos == std::string::npos) {
1380
0
        return Status::InternalError("invalid remove file path: {}", remote_path);
1381
0
    }
1382
1383
1
    std::string tablet_id_str = remote_path.substr(pos + 1);
1384
1
    std::stringstream ss;
1385
1
    ss << tablet_id_str;
1386
1
    ss >> *tablet_id;
1387
1388
1
    return Status::OK();
1389
1
}
1390
1391
// only return CANCELLED if FE return that job is cancelled.
1392
// otherwise, return OK
1393
Status SnapshotLoader::_report_every(int report_threshold, int* counter, int32_t finished_num,
1394
0
                                     int32_t total_num, TTaskType::type type) {
1395
0
    ++*counter;
1396
0
    if (*counter <= report_threshold) {
1397
0
        return Status::OK();
1398
0
    }
1399
1400
0
    LOG(INFO) << "report to frontend. job id: " << _job_id << ", task id: " << _task_id
1401
0
              << ", finished num: " << finished_num << ", total num:" << total_num;
1402
1403
0
    TNetworkAddress master_addr = _env->cluster_info()->master_fe_addr;
1404
1405
0
    TSnapshotLoaderReportRequest request;
1406
0
    request.job_id = _job_id;
1407
0
    request.task_id = _task_id;
1408
0
    request.task_type = type;
1409
0
    request.__set_finished_num(finished_num);
1410
0
    request.__set_total_num(total_num);
1411
0
    TStatus report_st;
1412
1413
0
    Status rpcStatus = ThriftRpcHelper::rpc<FrontendServiceClient>(
1414
0
            master_addr.hostname, master_addr.port,
1415
0
            [&request, &report_st](FrontendServiceConnection& client) {
1416
0
                client->snapshotLoaderReport(report_st, request);
1417
0
            },
1418
0
            10000);
1419
1420
0
    if (!rpcStatus.ok()) {
1421
        // rpc failed, ignore
1422
0
        return Status::OK();
1423
0
    }
1424
1425
    // reset
1426
0
    *counter = 0;
1427
0
    if (report_st.status_code == TStatusCode::CANCELLED) {
1428
0
        LOG(INFO) << "job is cancelled. job id: " << _job_id << ", task id: " << _task_id;
1429
0
        return Status::Cancelled("Cancelled");
1430
0
    }
1431
0
    return Status::OK();
1432
0
}
1433
1434
Status SnapshotLoader::_list_with_checksum(const std::string& dir,
1435
0
                                           std::map<std::string, FileStat>* md5_files) {
1436
0
    bool exists = true;
1437
0
    std::vector<io::FileInfo> files;
1438
0
    RETURN_IF_ERROR(_remote_fs->list(dir, true, &files, &exists));
1439
0
    for (auto& tmp_file : files) {
1440
0
        io::Path path(tmp_file.file_name);
1441
0
        std::string file_name = path.filename();
1442
0
        size_t pos = file_name.find_last_of(".");
1443
0
        if (pos == std::string::npos || pos == file_name.size() - 1) {
1444
            // Not found checksum separator, ignore this file
1445
0
            continue;
1446
0
        }
1447
0
        FileStat stat = {std::string(file_name, 0, pos), std::string(file_name, pos + 1),
1448
0
                         tmp_file.file_size};
1449
0
        md5_files->emplace(std::string(file_name, 0, pos), stat);
1450
0
    }
1451
1452
0
    return Status::OK();
1453
0
}
1454
#include "common/compile_check_end.h"
1455
1456
} // end namespace doris