Coverage Report

Created: 2026-07-21 03:42

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