Coverage Report

Created: 2026-08-18 15:40

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/io/fs/s3_file_system.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 "io/fs/s3_file_system.h"
19
20
#include <fmt/format.h>
21
22
#include <cstddef>
23
24
#include "common/compiler_util.h" // IWYU pragma: keep
25
// IWYU pragma: no_include <bits/chrono.h>
26
#include <aws/core/utils/threading/Executor.h>
27
#include <aws/s3/S3Client.h>
28
29
#include <chrono> // IWYU pragma: keep
30
#include <filesystem>
31
#include <fstream> // IWYU pragma: keep
32
#include <future>
33
#include <memory>
34
35
#include "common/config.h"
36
#include "common/logging.h"
37
#include "common/status.h"
38
#include "cpp/obj-client/obj_storage_client.h"
39
#include "cpp/obj-client/s3_common.h"
40
#include "cpp/sync_point.h"
41
#include "io/fs/err_utils.h"
42
#include "io/fs/file_system.h"
43
#include "io/fs/file_writer.h"
44
#include "io/fs/local_file_system.h"
45
#include "io/fs/remote_file_system.h"
46
#include "io/fs/s3_file_reader.h"
47
#include "io/fs/s3_file_writer.h"
48
#include "runtime/exec_env.h"
49
#include "runtime/thread_context.h"
50
#include "util/s3_uri.h"
51
#include "util/s3_util.h"
52
53
namespace doris::io {
54
namespace {
55
constexpr std::string_view OSS_PRIVATE_ENDPOINT_SUFFIX = "-internal.aliyuncs.com";
56
constexpr int LEN_OF_OSS_PRIVATE_SUFFIX = 9; // length of "-internal"
57
58
#ifndef CHECK_S3_CLIENT
59
#define CHECK_S3_CLIENT(client)                                 \
60
2.09k
    if (!client) {                                              \
61
0
        return Status::InvalidArgument("init s3 client error"); \
62
0
    }
63
#endif
64
65
2.09k
Result<std::string> get_key(const Path& full_path) {
66
    // FIXME(plat1ko): Check bucket in full path and support relative path
67
2.09k
    S3URI uri(full_path.native());
68
2.09k
    RETURN_IF_ERROR_RESULT(uri.parse());
69
2.09k
    return uri.get_key();
70
2.09k
}
71
72
} // namespace
73
74
72
ObjClientHolder::ObjClientHolder(S3ClientConf conf) : _conf(std::move(conf)) {}
75
76
71
ObjClientHolder::~ObjClientHolder() = default;
77
78
12
Status ObjClientHolder::init() {
79
12
    _client = DORIS_TRY(S3ClientFactory::instance().create(_conf));
80
12
    return Status::OK();
81
12
}
82
83
1
Status ObjClientHolder::reset(const S3ClientConf& conf) {
84
1
    S3ClientConf reset_conf;
85
1
    {
86
1
        std::shared_lock lock(_mtx);
87
1
        reset_conf = _conf;
88
1
        reset_conf.ak = conf.ak;
89
1
        reset_conf.sk = conf.sk;
90
1
        reset_conf.token = conf.token;
91
1
        reset_conf.bucket = conf.bucket;
92
1
        reset_conf.connect_timeout_ms = conf.connect_timeout_ms;
93
1
        reset_conf.max_connections = conf.max_connections;
94
1
        reset_conf.request_timeout_ms = conf.request_timeout_ms;
95
1
        reset_conf.use_virtual_addressing = conf.use_virtual_addressing;
96
1
        reset_conf.is_internal_bucket = conf.is_internal_bucket;
97
98
1
        reset_conf.role_arn = conf.role_arn;
99
1
        reset_conf.external_id = conf.external_id;
100
1
        reset_conf.cred_provider_type = conf.cred_provider_type;
101
102
        // Compare full-field equality of the merged conf, not get_hash(): the hash is
103
        // an XOR of crc32s and distinct configurations can collide, which would skip a
104
        // required client rebuild (e.g. a credential update).
105
1
        if (reset_conf == _conf) {
106
0
            return Status::OK(); // Same conf
107
0
        }
108
1
    }
109
110
1
    auto client = DORIS_TRY(S3ClientFactory::instance().create(reset_conf));
111
112
1
    LOG(WARNING) << "reset s3 client with new conf: " << conf.to_string();
113
114
1
    {
115
1
        std::lock_guard lock(_mtx);
116
1
        _client = std::move(client);
117
1
        _conf = std::move(reset_conf);
118
1
    }
119
120
1
    return Status::OK();
121
1
}
122
123
Result<int64_t> ObjClientHolder::object_file_size(const std::string& bucket,
124
5
                                                  const std::string& key) const {
125
5
    auto client = get();
126
5
    if (!client) {
127
0
        return ResultError(Status::InvalidArgument("init s3 client error"));
128
0
    }
129
130
5
    auto resp = client->head_object({
131
5
            .bucket = bucket,
132
5
            .key = key,
133
5
    });
134
135
5
    if (resp.resp.status.code != ErrorCode::OK) {
136
3
        return ResultError(std::move(Status(resp.resp.status.code, std::move(resp.resp.status.msg))
137
3
                                             .append(fmt::format("failed to head s3 file {}",
138
3
                                                                 full_s3_path(bucket, key)))));
139
3
    }
140
141
2
    return resp.file_size;
142
5
}
143
144
3
std::string ObjClientHolder::full_s3_path(std::string_view bucket, std::string_view key) const {
145
3
    return fmt::format("{}/{}/{}", _conf.endpoint, bucket, key);
146
3
}
147
148
0
std::string S3FileSystem::full_s3_path(std::string_view key) const {
149
0
    return _client->full_s3_path(_bucket, key);
150
0
}
151
152
11
Result<std::shared_ptr<S3FileSystem>> S3FileSystem::create(S3Conf s3_conf, std::string id) {
153
11
    std::shared_ptr<S3FileSystem> fs(new S3FileSystem(std::move(s3_conf), std::move(id)));
154
11
    RETURN_IF_ERROR_RESULT(fs->init());
155
11
    return fs;
156
11
}
157
158
S3FileSystem::S3FileSystem(S3Conf s3_conf, std::string id)
159
11
        : RemoteFileSystem(s3_conf.prefix, std::move(id), FileSystemType::S3),
160
11
          _bucket(std::move(s3_conf.bucket)),
161
11
          _prefix(std::move(s3_conf.prefix)),
162
11
          _client(std::make_shared<ObjClientHolder>(std::move(s3_conf.client_conf))) {
163
    // FIXME(plat1ko): Normalize prefix
164
    // remove the first and last '/'
165
11
    if (!_prefix.empty()) {
166
11
        size_t start = _prefix.find_first_not_of('/');
167
11
        if (start == std::string::npos) {
168
0
            _prefix = "";
169
11
        } else {
170
11
            size_t end = _prefix.find_last_not_of('/');
171
11
            if (start > 0 || end < _prefix.size() - 1) {
172
0
                _prefix = _prefix.substr(start, end - start + 1);
173
0
            }
174
11
        }
175
11
    }
176
11
}
177
178
11
Status S3FileSystem::init() {
179
11
    return _client->init();
180
11
}
181
182
10
S3FileSystem::~S3FileSystem() = default;
183
184
Status S3FileSystem::create_file_impl(const Path& file, FileWriterPtr* writer,
185
2.08k
                                      const FileWriterOptions* opts) {
186
2.08k
    auto client = _client->get();
187
2.08k
    CHECK_S3_CLIENT(client);
188
2.08k
    auto key = DORIS_TRY(get_key(file));
189
2.08k
    *writer = std::make_unique<S3FileWriter>(_client, _bucket, std::move(key), opts);
190
2.08k
    return Status::OK();
191
2.08k
}
192
193
Status S3FileSystem::open_file_internal(const Path& file, FileReaderSPtr* reader,
194
3
                                        const FileReaderOptions& opts) {
195
3
    TEST_SYNC_POINT_CALLBACK("S3FileSystem::open_file_internal", &file, &opts);
196
3
    auto key = DORIS_TRY(get_key(file));
197
3
    *reader = DORIS_TRY(S3FileReader::create(_client, _bucket, key, opts.file_size, nullptr));
198
0
    return Status::OK();
199
3
}
200
201
0
Status S3FileSystem::create_directory_impl(const Path& dir, bool failed_if_exists) {
202
0
    return Status::OK();
203
0
}
204
205
0
Status S3FileSystem::delete_file_impl(const Path& file) {
206
0
    auto client = _client->get();
207
0
    CHECK_S3_CLIENT(client);
208
209
0
    auto key = DORIS_TRY(get_key(file));
210
211
0
    auto resp = client->delete_object({.bucket = _bucket, .key = key});
212
213
0
    if (resp.status.code == ErrorCode::OK || resp.status.code == ErrorCode::NOT_FOUND) {
214
0
        return Status::OK();
215
0
    }
216
0
    return std::move(Status(resp.status.code, std::move(resp.status.msg))
217
0
                             .append(fmt::format("failed to delete file {}", full_s3_path(key))));
218
0
}
219
220
0
Status S3FileSystem::delete_directory_impl(const Path& dir) {
221
0
    auto client = _client->get();
222
0
    CHECK_S3_CLIENT(client);
223
224
0
    auto prefix = DORIS_TRY(get_key(dir));
225
0
    if (!prefix.empty() && prefix.back() != '/') {
226
0
        prefix.push_back('/');
227
0
    }
228
229
0
    ObjStoragePath delete_path {
230
0
            .path = full_s3_path(prefix),
231
0
            .bucket = _bucket,
232
0
            .prefix = prefix,
233
0
    };
234
0
    auto resp = delete_objects_recursively(std::move(client), delete_path);
235
0
    return {resp.status.code, std::move(resp.status.msg)};
236
0
}
237
238
0
Status S3FileSystem::batch_delete_impl(const std::vector<Path>& remote_files) {
239
0
    auto client = _client->get();
240
0
    CHECK_S3_CLIENT(client);
241
242
    // `DeleteObjectsRequest` can only contain 1000 keys at most.
243
0
    constexpr size_t max_delete_batch = 1000;
244
0
    auto path_iter = remote_files.begin();
245
246
0
    do {
247
0
        std::vector<std::string> objects;
248
0
        auto path_begin = path_iter;
249
0
        for (; path_iter != remote_files.end() && (path_iter - path_begin < max_delete_batch);
250
0
             ++path_iter) {
251
0
            auto key = DORIS_TRY(get_key(*path_iter));
252
0
            objects.emplace_back(std::move(key));
253
0
        }
254
0
        if (objects.empty()) {
255
0
            return Status::OK();
256
0
        }
257
        // clang-format off
258
0
        if (auto resp = client->delete_objects( {.bucket = _bucket,}, std::move(objects)); resp.status.code != ErrorCode::OK) {
259
0
            return {resp.status.code, std::move(resp.status.msg)};
260
0
        }
261
        // clang-format on
262
0
    } while (path_iter != remote_files.end());
263
264
0
    return Status::OK();
265
0
}
266
267
4
Status S3FileSystem::exists_impl(const Path& path, bool* res) const {
268
4
    auto client = _client->get();
269
4
    CHECK_S3_CLIENT(client);
270
4
    auto key = DORIS_TRY(get_key(path));
271
272
4
    VLOG_DEBUG << "key:" << key << " path:" << path;
273
274
4
    auto resp = client->head_object({.bucket = _bucket, .key = key});
275
276
4
    if (resp.resp.status.code == ErrorCode::OK) {
277
0
        *res = true;
278
4
    } else if (resp.resp.status.code == ErrorCode::NOT_FOUND) {
279
4
        *res = false;
280
4
    } else {
281
0
        return std::move(
282
0
                Status(resp.resp.status.code, std::move(resp.resp.status.msg))
283
0
                        .append(fmt::format(" failed to check exists {}", full_s3_path(key))));
284
0
    }
285
4
    return Status::OK();
286
4
}
287
288
2
Status S3FileSystem::file_size_impl(const Path& file, int64_t* file_size) const {
289
2
    auto key = DORIS_TRY(get_key(file));
290
2
    *file_size = DORIS_TRY(_client->object_file_size(_bucket, key));
291
2
    return Status::OK();
292
2
}
293
294
Status S3FileSystem::list_impl(const Path& dir, bool only_file, std::vector<FileInfo>* files,
295
0
                               bool* exists) {
296
    // For object storage, this path is always not exist.
297
    // So we ignore this property and set exists to true.
298
0
    *exists = true;
299
0
    auto client = _client->get();
300
0
    CHECK_S3_CLIENT(client);
301
0
    auto prefix = DORIS_TRY(get_key(dir));
302
0
    if (!prefix.empty() && prefix.back() != '/') {
303
0
        prefix.push_back('/');
304
0
    }
305
306
0
    std::vector<ObjectMeta> objects;
307
0
    auto resp = client->list_objects({.bucket = _bucket, .prefix = prefix}, &objects);
308
0
    if (!resp.ok()) {
309
0
        files->clear();
310
0
        return {resp.status.code, std::move(resp.status.msg)};
311
0
    }
312
0
    files->reserve(files->size() + objects.size());
313
0
    for (auto& obj : objects) {
314
0
        obj.key.erase(0, prefix.size());
315
0
        bool is_dir = obj.key.empty() || obj.key.back() == '/';
316
0
        files->emplace_back(FileInfo {
317
0
                .file_name = std::move(obj.key), .file_size = obj.size, .is_file = !is_dir});
318
0
    }
319
320
0
    return Status::OK();
321
0
}
322
323
0
Status S3FileSystem::rename_impl(const Path& orig_name, const Path& new_name) {
324
0
    return Status::NotSupported("S3FileSystem::rename_impl");
325
0
}
326
327
0
Status S3FileSystem::upload_impl(const Path& local_file, const Path& remote_file) {
328
0
    auto client = _client->get();
329
0
    CHECK_S3_CLIENT(client);
330
331
0
    auto key = DORIS_TRY(get_key(remote_file));
332
0
    auto start = std::chrono::steady_clock::now();
333
0
    FileWriterPtr obj_writer;
334
0
    RETURN_IF_ERROR(create_file_impl(key, &obj_writer, nullptr));
335
0
    FileReaderSPtr local_reader;
336
0
    RETURN_IF_ERROR(io::global_local_filesystem()->open_file(local_file, &local_reader));
337
0
    size_t local_buffer_size = config::s3_file_system_local_upload_buffer_size;
338
0
    std::unique_ptr<char[]> write_buffer =
339
0
            std::make_unique_for_overwrite<char[]>(local_buffer_size);
340
0
    size_t cur_read = 0;
341
0
    while (cur_read < local_reader->size()) {
342
0
        size_t bytes_read = 0;
343
0
        RETURN_IF_ERROR(local_reader->read_at(
344
0
                cur_read, Slice {write_buffer.get(), local_buffer_size}, &bytes_read));
345
0
        RETURN_IF_ERROR(obj_writer->append({write_buffer.get(), bytes_read}));
346
0
        cur_read += bytes_read;
347
0
    }
348
0
    RETURN_IF_ERROR(obj_writer->close());
349
0
    auto duration = std::chrono::duration<float>(std::chrono::steady_clock::now() - start);
350
351
0
    auto size = local_reader->size();
352
0
    LOG(INFO) << "Upload " << local_file.native() << " to " << full_s3_path(key)
353
0
              << ", duration=" << duration.count() << ", bytes=" << size;
354
355
0
    return Status::OK();
356
0
}
357
358
Status S3FileSystem::batch_upload_impl(const std::vector<Path>& local_files,
359
0
                                       const std::vector<Path>& remote_files) {
360
0
    auto client = _client->get();
361
0
    CHECK_S3_CLIENT(client);
362
363
0
    if (local_files.size() != remote_files.size()) {
364
0
        return Status::InvalidArgument("local_files.size({}) != remote_files.size({})",
365
0
                                       local_files.size(), remote_files.size());
366
0
    }
367
368
0
    std::vector<FileWriterPtr> obj_writers(local_files.size());
369
370
0
    auto upload_task = [&, this](size_t idx) {
371
0
        SCOPED_ATTACH_TASK(ExecEnv::GetInstance()->s3_file_buffer_tracker());
372
0
        const auto& local_file = local_files[idx];
373
0
        const auto& remote_file = remote_files[idx];
374
0
        auto& obj_writer = obj_writers[idx];
375
0
        auto key = DORIS_TRY(get_key(remote_file));
376
0
        LOG(INFO) << "Start to upload " << local_file.native() << " to " << full_s3_path(key);
377
0
        RETURN_IF_ERROR(create_file_impl(key, &obj_writer, nullptr));
378
0
        FileReaderSPtr local_reader;
379
0
        RETURN_IF_ERROR(io::global_local_filesystem()->open_file(local_file, &local_reader));
380
0
        size_t local_buffer_size = config::s3_file_system_local_upload_buffer_size;
381
0
        std::unique_ptr<char[]> write_buffer =
382
0
                std::make_unique_for_overwrite<char[]>(local_buffer_size);
383
0
        size_t cur_read = 0;
384
0
        while (cur_read < local_reader->size()) {
385
0
            size_t bytes_read = 0;
386
0
            RETURN_IF_ERROR(local_reader->read_at(
387
0
                    cur_read, Slice {write_buffer.get(), local_buffer_size}, &bytes_read));
388
0
            RETURN_IF_ERROR((*obj_writer).append({write_buffer.get(), bytes_read}));
389
0
            cur_read += bytes_read;
390
0
        }
391
0
        RETURN_IF_ERROR((*obj_writer).close());
392
0
        return Status::OK();
393
0
    };
394
395
0
    Status s = Status::OK();
396
0
    std::vector<std::future<Status>> futures;
397
0
    for (int i = 0; i < local_files.size(); ++i) {
398
0
        auto task = std::make_shared<std::packaged_task<Status(size_t idx)>>(upload_task);
399
0
        futures.emplace_back(task->get_future());
400
0
        auto st = ExecEnv::GetInstance()->s3_file_system_thread_pool()->submit_func(
401
0
                [t = std::move(task), idx = i]() mutable { (*t)(idx); });
402
        // We shouldn't return immediately since the previous submitted tasks might still be running in the thread pool
403
0
        if (!st.ok()) {
404
0
            s = st;
405
0
            break;
406
0
        }
407
0
    }
408
0
    for (auto&& f : futures) {
409
0
        auto cur_s = f.get();
410
0
        if (!cur_s.ok()) {
411
0
            s = std::move(cur_s);
412
0
        }
413
0
    }
414
0
    return s;
415
0
}
416
417
0
Status S3FileSystem::download_impl(const Path& remote_file, const Path& local_file) {
418
0
    auto client = _client->get();
419
0
    CHECK_S3_CLIENT(client);
420
0
    auto key = DORIS_TRY(get_key(remote_file));
421
0
    int64_t size;
422
0
    RETURN_IF_ERROR(file_size(remote_file, &size));
423
0
    std::unique_ptr<char[]> buf = std::make_unique_for_overwrite<char[]>(size);
424
0
    size_t bytes_read = 0;
425
    // clang-format off
426
0
    auto resp = client->get_object( {.bucket = _bucket, .key = key,},
427
0
            buf.get(), 0, size, &bytes_read);
428
    // clang-format on
429
0
    if (resp.status.code != ErrorCode::OK) {
430
0
        return {resp.status.code, std::move(resp.status.msg)};
431
0
    }
432
0
    Aws::OFStream local_file_s;
433
0
    local_file_s.open(local_file, std::ios::out | std::ios::binary);
434
0
    if (local_file_s.good()) {
435
0
        local_file_s << StringViewStream(buf.get(), size).rdbuf();
436
0
    } else {
437
0
        return localfs_error(errno, fmt::format("failed to write file {}", local_file.native()));
438
0
    }
439
440
0
    return Status::OK();
441
0
}
442
443
// oss has public endpoint and private endpoint, is_public_endpoint determines
444
// whether to return a public endpoint.
445
std::string S3FileSystem::generate_presigned_url(const Path& path, int64_t expiration_secs,
446
0
                                                 bool is_public_endpoint) const {
447
0
    std::string key = fmt::format("{}/{}", _prefix, path.native());
448
0
    std::shared_ptr<ObjStorageClient> client;
449
0
    if (is_public_endpoint &&
450
0
        _client->s3_client_conf().endpoint.ends_with(OSS_PRIVATE_ENDPOINT_SUFFIX)) {
451
0
        auto new_s3_conf = _client->s3_client_conf();
452
0
        new_s3_conf.endpoint.erase(
453
0
                _client->s3_client_conf().endpoint.size() - OSS_PRIVATE_ENDPOINT_SUFFIX.size(),
454
0
                LEN_OF_OSS_PRIVATE_SUFFIX);
455
0
        auto client_result = S3ClientFactory::instance().create(new_s3_conf);
456
0
        if (!client_result) {
457
0
            LOG(WARNING) << "failed to create S3 client for presigned URL: "
458
0
                         << client_result.error();
459
0
            return {};
460
0
        }
461
0
        client = std::move(client_result).value();
462
0
    } else {
463
0
        client = _client->get();
464
0
    }
465
0
    return client->generate_presigned_url({.bucket = _bucket, .key = key, .prefix = ""},
466
0
                                          expiration_secs);
467
0
}
468
469
} // namespace doris::io