Coverage Report

Created: 2025-05-22 12:52

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