Coverage Report

Created: 2026-07-23 15:00

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