Coverage Report

Created: 2026-08-14 13:56

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/io/fs/s3_file_writer.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_writer.h"
19
20
#include <aws/s3/model/CompletedPart.h>
21
#include <bvar/recorder.h>
22
#include <bvar/reducer.h>
23
#include <bvar/window.h>
24
#include <fmt/core.h>
25
#include <glog/logging.h>
26
27
#include <sstream>
28
#include <tuple>
29
#include <utility>
30
31
#include "common/config.h"
32
#include "common/status.h"
33
#include "cpp/sync_point.h"
34
#include "io/cache/block_file_cache.h"
35
#include "io/cache/block_file_cache_factory.h"
36
#include "io/cache/file_block.h"
37
#include "io/cache/file_cache_common.h"
38
#include "io/fs/file_writer.h"
39
#include "io/fs/path.h"
40
#include "io/fs/s3_file_bufferpool.h"
41
#include "io/fs/s3_file_system.h"
42
#include "io/fs/s3_obj_storage_client.h"
43
#include "runtime/exec_env.h"
44
#include "util/debug_points.h"
45
#include "util/s3_util.h"
46
#include "util/stopwatch.hpp"
47
48
namespace doris::io {
49
50
bvar::Adder<uint64_t> s3_file_writer_total("s3_file_writer_total_num");
51
bvar::Adder<uint64_t> s3_bytes_written_total("s3_file_writer_bytes_written");
52
bvar::Adder<uint64_t> s3_file_created_total("s3_file_writer_file_created");
53
bvar::Adder<uint64_t> s3_file_being_written("s3_file_writer_file_being_written");
54
bvar::Adder<uint64_t> s3_file_writer_async_close_queuing("s3_file_writer_async_close_queuing");
55
bvar::Adder<uint64_t> s3_file_writer_async_close_processing(
56
        "s3_file_writer_async_close_processing");
57
bvar::IntRecorder s3_file_writer_first_append_to_close_ms_recorder;
58
bvar::Window<bvar::IntRecorder> s3_file_writer_first_append_to_close_ms_window(
59
        "s3_file_writer_first_append_to_close_ms",
60
        &s3_file_writer_first_append_to_close_ms_recorder, /*window_size=*/10);
61
62
S3FileWriter::S3FileWriter(std::shared_ptr<ObjClientHolder> client, std::string bucket,
63
                           std::string key, const FileWriterOptions* opts)
64
2.09k
        : _obj_storage_path_opts({.path = fmt::format("s3://{}/{}", bucket, key),
65
2.09k
                                  .bucket = std::move(bucket),
66
2.09k
                                  .key = std::move(key)}),
67
2.09k
          _used_by_s3_committer(opts ? opts->used_by_s3_committer : false),
68
2.09k
          _obj_client(std::move(client)) {
69
2.09k
    s3_file_writer_total << 1;
70
2.09k
    s3_file_being_written << 1;
71
2.09k
    Aws::Http::SetCompliantRfc3986Encoding(true);
72
73
2.09k
    init_cache_builder(opts, _obj_storage_path_opts.path);
74
2.09k
}
75
76
2.09k
S3FileWriter::~S3FileWriter() {
77
2.09k
    if (_async_close_pack != nullptr) {
78
        // For thread safety
79
0
        std::ignore = _async_close_pack->future.get();
80
0
        _async_close_pack = nullptr;
81
2.09k
    } else {
82
        // Consider one situation where the file writer is destructed after it submit at least one async task
83
        // without calling close(), then there exists one occasion where the async task is executed right after
84
        // the correspoding S3 file writer is already destructed
85
2.09k
        _wait_until_finish(fmt::format("wait s3 file {} upload to be finished",
86
2.09k
                                       _obj_storage_path_opts.path.native()));
87
2.09k
    }
88
    // Deferred uploads are reported to FE for cleanup. Uploads that never reach FE are left to
89
    // the provider lifecycle policy, so destroying a writer must not mutate provider state here.
90
2.09k
    if (state() == State::OPENED && !_failed) {
91
1.01k
        s3_bytes_written_total << _bytes_appended;
92
1.01k
    }
93
2.09k
    s3_file_being_written << -1;
94
2.09k
}
95
96
48
Status S3FileWriter::_create_multi_upload_request() {
97
48
    LOG(INFO) << "create_multi_upload_request " << _obj_storage_path_opts.path.native();
98
48
    const auto& client = _obj_client->get();
99
48
    if (nullptr == client) {
100
0
        return Status::InternalError<false>("invalid obj storage client");
101
0
    }
102
48
    auto resp = client->create_multipart_upload(_obj_storage_path_opts);
103
48
    if (resp.resp.status.code == ErrorCode::OK) {
104
47
        _obj_storage_path_opts.upload_id = resp.upload_id;
105
47
    }
106
48
    return {resp.resp.status.code, std::move(resp.resp.status.msg)};
107
48
}
108
109
3.16k
void S3FileWriter::_wait_until_finish(std::string_view task_name) {
110
3.16k
    auto timeout_duration = config::s3_file_writer_log_interval_second;
111
3.16k
    auto msg = fmt::format(
112
3.16k
            "{} multipart upload already takes {} seconds, bucket={}, key={}, upload_id={}",
113
3.16k
            task_name, timeout_duration, _obj_storage_path_opts.bucket,
114
3.16k
            _obj_storage_path_opts.path.native(),
115
3.16k
            _obj_storage_path_opts.upload_id.has_value() ? *_obj_storage_path_opts.upload_id : "");
116
3.16k
    timespec current_time;
117
    // We don't need high accuracy here, so we use time(nullptr)
118
    // since it's the fastest way to get current time(second)
119
3.16k
    auto current_time_second = time(nullptr);
120
3.16k
    current_time.tv_sec = current_time_second + timeout_duration;
121
3.16k
    current_time.tv_nsec = 0;
122
    // bthread::countdown_event::timed_wait() should use absolute time
123
3.16k
    while (0 != _countdown_event.timed_wait(current_time)) {
124
0
        current_time.tv_sec += timeout_duration;
125
0
        LOG(WARNING) << msg;
126
0
    }
127
3.16k
}
128
129
1.09k
Status S3FileWriter::close(bool non_block) {
130
1.09k
    if (state() == State::CLOSED) {
131
0
        return Status::InternalError("S3FileWriter already closed, file path {}, file key {}",
132
0
                                     _obj_storage_path_opts.path.native(),
133
0
                                     _obj_storage_path_opts.key);
134
0
    }
135
1.09k
    if (state() == State::ASYNC_CLOSING) {
136
16
        if (non_block) {
137
0
            return Status::InternalError("Don't submit async close multi times");
138
0
        }
139
16
        CHECK(_async_close_pack != nullptr);
140
16
        _st = _async_close_pack->future.get();
141
16
        _async_close_pack = nullptr;
142
        // We should wait for all the pre async task to be finished
143
16
        _state = State::CLOSED;
144
        // The next time we call close() with no matter non_block true or false, it would always return the
145
        // '_st' value because this writer is already closed.
146
16
        if (!non_block && _st.ok()) {
147
11
            _record_close_latency();
148
11
        }
149
16
        return _st;
150
16
    }
151
1.07k
    if (non_block) {
152
1.01k
        _state = State::ASYNC_CLOSING;
153
1.01k
        _async_close_pack = std::make_unique<AsyncCloseStatusPack>();
154
1.01k
        _async_close_pack->future = _async_close_pack->promise.get_future();
155
1.01k
        s3_file_writer_async_close_queuing << 1;
156
1.01k
        Status submit_status = Status::OK();
157
1.01k
        DBUG_EXECUTE_IF("S3FileWriter.close.submit_async_close.inject_error", {
158
1.01k
            submit_status = Status::IOError("S3FileWriter.close.submit_async_close.inject_error");
159
1.01k
        });
160
1.01k
        if (submit_status.ok()) {
161
1.01k
            submit_status =
162
1.01k
                    ExecEnv::GetInstance()->non_block_close_thread_pool()->submit_func([&]() {
163
1.01k
                        s3_file_writer_async_close_queuing << -1;
164
1.01k
                        s3_file_writer_async_close_processing << 1;
165
1.01k
                        _st = _close_impl();
166
1.01k
                        _async_close_pack->promise.set_value(_st);
167
1.01k
                        s3_file_writer_async_close_processing << -1;
168
1.01k
                    });
169
1.01k
        }
170
1.01k
        if (!submit_status.ok()) {
171
0
            s3_file_writer_async_close_queuing << -1;
172
0
            LOG(WARNING) << "failed to submit async close for "
173
0
                         << _obj_storage_path_opts.path.native()
174
0
                         << ", fallback to sync close, status=" << submit_status;
175
0
            _st = _close_impl();
176
0
            _async_close_pack->promise.set_value(_st);
177
0
            return _st;
178
0
        }
179
1.01k
        return Status::OK();
180
1.01k
    }
181
59
    _st = _close_impl();
182
59
    _state = State::CLOSED;
183
59
    if (!non_block && _st.ok()) {
184
57
        _record_close_latency();
185
57
    }
186
59
    return _st;
187
1.07k
}
188
189
1.06k
void S3FileWriter::_record_close_latency() {
190
1.06k
    if (_close_latency_recorded || !_first_append_timestamp.has_value()) {
191
1
        return;
192
1
    }
193
1.06k
    auto now = std::chrono::steady_clock::now();
194
1.06k
    auto latency_ms =
195
1.06k
            std::chrono::duration_cast<std::chrono::milliseconds>(now - *_first_append_timestamp)
196
1.06k
                    .count();
197
1.06k
    s3_file_writer_first_append_to_close_ms_recorder << latency_ms;
198
1.06k
    if (auto* sampler = s3_file_writer_first_append_to_close_ms_recorder.get_sampler()) {
199
1.06k
        sampler->take_sample();
200
1.06k
    }
201
1.06k
    _close_latency_recorded = true;
202
1.06k
}
203
204
1.00k
Status S3FileWriter::try_finish_close() {
205
1.00k
    if (state() == State::CLOSED) {
206
0
        return _st;
207
0
    }
208
1.00k
    if (state() != State::ASYNC_CLOSING) {
209
0
        return Status::NotSupported("S3FileWriter is not async closing");
210
0
    }
211
1.00k
    CHECK(_async_close_pack != nullptr);
212
1.00k
    if (_async_close_pack->future.wait_for(std::chrono::seconds(0)) != std::future_status::ready) {
213
0
        return Status::NeedSendAgain("async close is not finished");
214
0
    }
215
1.00k
    _st = _async_close_pack->future.get();
216
1.00k
    _async_close_pack = nullptr;
217
1.00k
    _state = State::CLOSED;
218
1.00k
    if (_st.ok()) {
219
1.00k
        _record_close_latency();
220
1.00k
    }
221
1.00k
    return _st;
222
1.00k
}
223
224
1.27k
bool S3FileWriter::_complete_part_task_callback(Status s) {
225
1.27k
    bool ret = false;
226
1.27k
    if (!s.ok()) [[unlikely]] {
227
3
        VLOG_NOTICE << "failed at key: " << _obj_storage_path_opts.key
228
0
                    << ", status: " << s.to_string();
229
3
        std::unique_lock<std::mutex> _lck {_completed_lock};
230
3
        _failed = true;
231
3
        ret = true;
232
3
        _st = std::move(s);
233
3
    }
234
    // After the signal, there is a scenario where the previous invocation of _wait_until_finish
235
    // returns to the caller, and subsequently, the S3 file writer is destructed.
236
    // This means that accessing _failed afterwards would result in a heap use after free vulnerability.
237
1.27k
    _countdown_event.signal();
238
1.27k
    return ret;
239
1.27k
}
240
241
1.28k
Status S3FileWriter::_build_upload_buffer() {
242
1.28k
    auto builder = FileBufferBuilder();
243
1.28k
    builder.set_type(BufferType::UPLOAD)
244
1.28k
            .set_upload_callback([part_num = _cur_part_num, this](UploadFileBuffer& buf) {
245
250
                _upload_one_part(part_num, buf);
246
250
            })
247
1.28k
            .set_file_offset(_bytes_appended)
248
1.28k
            .set_sync_after_complete_task([this](auto&& PH1) {
249
1.27k
                return _complete_part_task_callback(std::forward<decltype(PH1)>(PH1));
250
1.27k
            })
251
1.52k
            .set_is_cancelled([this]() { return _failed.load(); });
252
1.28k
    if (_cache_builder != nullptr) {
253
        // We would load the data into file cache asynchronously which indicates
254
        // that this instance of S3FileWriter might have been destructed when we
255
        // try to do writing into file cache, so we make the lambda capture the variable
256
        // we need by value to extend their lifetime
257
4
        int64_t id = get_tablet_id(_obj_storage_path_opts.path.native()).value_or(0);
258
4
        builder.set_allocate_file_blocks_holder([builder = *_cache_builder,
259
4
                                                 offset = _bytes_appended,
260
4
                                                 tablet_id = id]() -> FileBlocksHolderPtr {
261
4
            return builder.allocate_cache_holder(offset, config::s3_write_buffer_size, tablet_id);
262
4
        });
263
4
    }
264
1.28k
    RETURN_IF_ERROR(builder.build(&_pending_buf));
265
1.28k
    auto* buf = dynamic_cast<UploadFileBuffer*>(_pending_buf.get());
266
1.28k
    DCHECK(buf != nullptr);
267
1.28k
    return Status::OK();
268
1.28k
}
269
270
1.28k
Status S3FileWriter::_submit_upload_buffer(const std::shared_ptr<FileBuffer>& buf) {
271
1.28k
    _countdown_event.add_count();
272
1.28k
    DBUG_EXECUTE_IF("S3FileWriter.submit_upload_buffer.inject_error", {
273
1.28k
        auto st = Status::IOError("S3FileWriter.submit_upload_buffer.inject_error");
274
1.28k
        _complete_part_task_callback(st);
275
1.28k
        return st;
276
1.28k
    });
277
1.28k
    auto st = FileBuffer::submit(buf);
278
1.28k
    if (!st.ok()) [[unlikely]] {
279
0
        _complete_part_task_callback(st);
280
0
    }
281
1.28k
    return st;
282
1.28k
}
283
284
1.07k
Status S3FileWriter::_close_impl() {
285
1.07k
    VLOG_DEBUG << "S3FileWriter::close, path: " << _obj_storage_path_opts.path.native();
286
287
1.07k
    DBUG_EXECUTE_IF("S3FileWriter._close_impl.inject_error", {
288
1.07k
        if (_obj_storage_path_opts.key.ends_with(".dat")) {
289
1.07k
            return Status::IOError("S3FileWriter._close_impl.inject_error");
290
1.07k
        }
291
1.07k
    });
292
293
1.07k
    if (_cur_part_num == 1 && _pending_buf) { // data size is less than config::s3_write_buffer_size
294
1.02k
        RETURN_IF_ERROR(_set_upload_to_remote_less_than_buffer_size());
295
1.02k
    }
296
297
1.07k
    if (_bytes_appended == 0) {
298
3
        DCHECK_EQ(_cur_part_num, 1);
299
        // No data written, but need to create an empty file
300
3
        RETURN_IF_ERROR(_build_upload_buffer());
301
3
        if (!_used_by_s3_committer) {
302
3
            auto* pending_buf = dynamic_cast<UploadFileBuffer*>(_pending_buf.get());
303
3
            pending_buf->set_upload_to_remote([this](UploadFileBuffer& buf) { _put_object(buf); });
304
3
        } else {
305
0
            RETURN_IF_ERROR(_create_multi_upload_request());
306
0
        }
307
3
    }
308
309
1.07k
    if (_pending_buf != nullptr) { // there is remaining data in buffer need to be uploaded
310
1.06k
        auto st = _submit_upload_buffer(_pending_buf);
311
1.06k
        _pending_buf = nullptr;
312
1.06k
        if (!st.ok()) {
313
0
            _wait_until_finish("pending buffer submit failed");
314
0
            return st;
315
0
        }
316
1.06k
    }
317
318
1.07k
    RETURN_IF_ERROR(_complete());
319
1.07k
    SYNC_POINT_RETURN_WITH_VALUE("s3_file_writer::close", Status());
320
321
1.06k
    return Status::OK();
322
1.06k
}
323
324
10.4k
Status S3FileWriter::appendv(const Slice* data, size_t data_cnt) {
325
10.4k
    if (state() != State::OPENED) [[unlikely]] {
326
0
        return Status::InternalError("append to closed file: {}",
327
0
                                     _obj_storage_path_opts.path.native());
328
0
    }
329
330
10.4k
    if (!_first_append_timestamp.has_value()) {
331
1.07k
        _first_append_timestamp = std::chrono::steady_clock::now();
332
1.07k
    }
333
334
10.4k
    size_t buffer_size = config::s3_write_buffer_size;
335
10.4k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("s3_file_writer::appenv", Status());
336
20.9k
    for (size_t i = 0; i < data_cnt; i++) {
337
10.5k
        size_t data_size = data[i].get_size();
338
21.2k
        for (size_t pos = 0, data_size_to_append = 0; pos < data_size; pos += data_size_to_append) {
339
10.7k
            if (_failed) {
340
0
                return _st;
341
0
            }
342
10.7k
            if (!_pending_buf) {
343
1.28k
                RETURN_IF_ERROR(_build_upload_buffer());
344
1.28k
            }
345
            // we need to make sure all parts except the last one to be 5MB or more
346
            // and shouldn't be larger than buf
347
10.7k
            data_size_to_append = std::min(data_size - pos, _pending_buf->get_file_offset() +
348
10.7k
                                                                    buffer_size - _bytes_appended);
349
350
            // if the buffer has memory buf inside, the data would be written into memory first then S3 then file cache
351
            // it would be written to cache then S3 if the buffer doesn't have memory preserved
352
10.7k
            RETURN_IF_ERROR(_pending_buf->append_data(
353
10.7k
                    Slice {data[i].get_data() + pos, data_size_to_append}));
354
10.7k
            TEST_SYNC_POINT_CALLBACK("s3_file_writer::appenv_1", &_pending_buf, _cur_part_num);
355
356
            // If this is the last part and the data size is less than s3_write_buffer_size,
357
            // the pending_buf will be handled by _close_impl() and _complete()
358
            // If this is the last part and the data size is equal to s3_write_buffer_size,
359
            // the pending_buf is handled here and submitted. it will be waited by _complete()
360
10.7k
            if (_pending_buf->get_size() == buffer_size) {
361
                // only create multiple upload request when the data size is
362
                // larger or equal to s3_write_buffer_size than one memory buffer
363
215
                if (_cur_part_num == 1) {
364
48
                    RETURN_IF_ERROR(_create_multi_upload_request());
365
48
                }
366
214
                _cur_part_num++;
367
214
                auto st = _submit_upload_buffer(_pending_buf);
368
214
                _pending_buf = nullptr;
369
214
                RETURN_IF_ERROR(st);
370
214
            }
371
10.7k
            _bytes_appended += data_size_to_append;
372
10.7k
        }
373
10.5k
    }
374
10.4k
    return Status::OK();
375
10.4k
}
376
377
250
void S3FileWriter::_upload_one_part(int part_num, UploadFileBuffer& buf) {
378
250
    VLOG_DEBUG << "upload_one_part " << _obj_storage_path_opts.path.native()
379
0
               << " part=" << part_num;
380
250
    if (buf.is_cancelled()) {
381
0
        LOG_INFO("file {} skip part {} because previous failure {}",
382
0
                 _obj_storage_path_opts.path.native(), part_num, _st);
383
0
        return;
384
0
    }
385
250
    const auto& client = _obj_client->get();
386
250
    if (nullptr == client) {
387
0
        LOG_WARNING("failed to upload part, key={}, part_num={} bacause of null obj client",
388
0
                    _obj_storage_path_opts.key, part_num);
389
0
        buf.set_status(Status::InternalError<false>("invalid obj storage client"));
390
0
        return;
391
0
    }
392
250
    auto resp = client->upload_part(_obj_storage_path_opts, buf.get_string_view_data(), part_num);
393
250
    if (resp.resp.status.code != ErrorCode::OK) {
394
1
        LOG_WARNING("failed to upload part, key={}, part_num={}, status={}",
395
1
                    _obj_storage_path_opts.key, part_num, resp.resp.status.msg);
396
1
        buf.set_status(Status(resp.resp.status.code, std::move(resp.resp.status.msg)));
397
1
        return;
398
1
    }
399
249
    s3_bytes_written_total << buf.get_size();
400
401
249
    ObjectCompleteMultiPart completed_part {
402
249
            part_num, resp.etag.has_value() ? std::move(resp.etag.value()) : ""};
403
404
249
    std::unique_lock<std::mutex> lck {_completed_lock};
405
249
    _completed_parts.emplace_back(std::move(completed_part));
406
249
}
407
408
// if enabled check
409
// 1. issue a head object request for existence check
410
// 2. check the file size
411
Status check_after_upload(ObjStorageClient* client, const ObjectStorageResponse& upload_res,
412
                          const ObjectStoragePathOptions& path_opt, int64_t bytes_appended,
413
1.06k
                          const std::string& put_or_comp) {
414
1.06k
    if (!config::enable_s3_object_check_after_upload) return Status::OK();
415
416
1.06k
    auto head_res = client->head_object(path_opt);
417
418
    // clang-format off
419
1.06k
    auto err_msg = [&]() {
420
0
        std::stringstream ss;
421
0
        ss << "failed to check object after upload=" << put_or_comp
422
0
            << " file_path=" << path_opt.path.native()
423
0
            << fmt::format(" {}_err=", put_or_comp) << upload_res.status.msg
424
0
            << fmt::format(" {}_code=", put_or_comp) << upload_res.status.code
425
0
            << fmt::format(" {}_http_code=", put_or_comp) << upload_res.http_code
426
0
            << fmt::format(" {}_request_id=", put_or_comp) << upload_res.request_id
427
0
            << " head_err=" << head_res.resp.status.msg
428
0
            << " head_code=" << head_res.resp.status.code
429
0
            << " head_http_code=" << head_res.resp.http_code
430
0
            << " head_request_id=" << head_res.resp.request_id;
431
0
        return ss.str();
432
0
    };
433
    // clang-format on
434
435
    // TODO(gavin): make it fail by injection
436
1.06k
    TEST_SYNC_POINT_CALLBACK("S3FileWriter::check_after_load", &head_res);
437
1.06k
    if (head_res.resp.status.code != ErrorCode::OK && head_res.resp.http_code != 200) {
438
0
        LOG(WARNING) << "failed to issue head object after upload, " << err_msg();
439
0
        DCHECK(false) << "failed to issue head object after upload, " << err_msg();
440
        // FIXME(gavin): we should retry if this HEAD fails?
441
0
        return Status::IOError(
442
0
                "failed to issue head object after upload, status_code={}, http_code={}, err={}",
443
0
                head_res.resp.status.code, head_res.resp.http_code, head_res.resp.status.msg);
444
0
    }
445
1.06k
    if (head_res.file_size != bytes_appended) {
446
0
        LOG(WARNING) << "failed to check size after upload, expected_size=" << bytes_appended
447
0
                     << " actual_size=" << head_res.file_size << err_msg();
448
0
        DCHECK_EQ(bytes_appended, head_res.file_size)
449
0
                << "failed to check size after upload," << err_msg();
450
0
        return Status::IOError(
451
0
                "failed to check object size after upload, expected_size={} actual_size={}",
452
0
                bytes_appended, head_res.file_size);
453
0
    }
454
1.06k
    return Status::OK();
455
1.06k
}
456
457
1.07k
Status S3FileWriter::_complete() {
458
1.07k
    const auto& client = _obj_client->get();
459
1.07k
    if (nullptr == client) {
460
0
        return Status::InternalError<false>("invalid obj storage client");
461
0
    }
462
1.07k
    if (_failed) {
463
0
        _wait_until_finish("early quit");
464
0
        return _st;
465
0
    }
466
    // When the part num is only one, it means the data is less than 5MB so we can just put it.
467
1.07k
    if (_cur_part_num == 1) {
468
1.02k
        _wait_until_finish("PutObject");
469
1.02k
        return _st;
470
1.02k
    }
471
    // Wait multipart load and finish.
472
46
    _wait_until_finish("Complete");
473
46
    TEST_SYNC_POINT_CALLBACK("S3FileWriter::_complete:1",
474
46
                             std::make_pair(&_failed, &_completed_parts));
475
46
    if (_used_by_s3_committer) {    // S3 committer will complete multipart upload file on FE side.
476
0
        s3_file_created_total << 1; // Assume that it will be created successfully
477
0
        return Status::OK();
478
0
    }
479
480
    // check number of parts
481
46
    int64_t expected_num_parts1 = (_bytes_appended / config::s3_write_buffer_size) +
482
46
                                  !!(_bytes_appended % config::s3_write_buffer_size);
483
46
    int64_t expected_num_parts2 =
484
46
            (_bytes_appended % config::s3_write_buffer_size) ? _cur_part_num : _cur_part_num - 1;
485
46
    DCHECK_EQ(expected_num_parts1, expected_num_parts2)
486
0
            << " bytes_appended=" << _bytes_appended << " cur_part_num=" << _cur_part_num
487
0
            << " s3_write_buffer_size=" << config::s3_write_buffer_size;
488
46
    if (_failed || _completed_parts.size() != static_cast<size_t>(expected_num_parts1) ||
489
46
        expected_num_parts1 != expected_num_parts2) {
490
3
        _st = Status::InternalError(
491
3
                "failed to complete multipart upload, error status={} failed={} #complete_parts={} "
492
3
                "#expected_parts={} "
493
3
                "completed_parts_list={} file_path={} file_size={} has left buffer not uploaded={}",
494
3
                _st, _failed, _completed_parts.size(), expected_num_parts1, _dump_completed_part(),
495
3
                _obj_storage_path_opts.path.native(), _bytes_appended, _pending_buf != nullptr);
496
3
        LOG(WARNING) << _st;
497
3
        return _st;
498
3
    }
499
    // make sure _completed_parts are ascending order
500
43
    std::sort(_completed_parts.begin(), _completed_parts.end(),
501
588
              [](auto& p1, auto& p2) { return p1.part_num < p2.part_num; });
502
43
    TEST_SYNC_POINT_CALLBACK("S3FileWriter::_complete:2", &_completed_parts);
503
43
    LOG(INFO) << "complete_multipart_upload " << _obj_storage_path_opts.path.native()
504
43
              << " size=" << _bytes_appended << " number_parts=" << _completed_parts.size()
505
43
              << " s3_write_buffer_size=" << config::s3_write_buffer_size;
506
43
    auto resp = client->complete_multipart_upload(_obj_storage_path_opts, _completed_parts);
507
43
    if (resp.status.code != ErrorCode::OK) {
508
2
        LOG_WARNING("failed to complete multipart upload, err={}, file_path={}", resp.status.msg,
509
2
                    _obj_storage_path_opts.path.native());
510
2
        return {resp.status.code, std::move(resp.status.msg)};
511
2
    }
512
513
41
    RETURN_IF_ERROR(check_after_upload(client.get(), resp, _obj_storage_path_opts, _bytes_appended,
514
41
                                       "complete_multipart"));
515
516
41
    s3_file_created_total << 1;
517
41
    return Status::OK();
518
41
}
519
520
1.02k
Status S3FileWriter::_set_upload_to_remote_less_than_buffer_size() {
521
1.02k
    auto* buf = dynamic_cast<UploadFileBuffer*>(_pending_buf.get());
522
1.02k
    DCHECK(buf != nullptr);
523
1.02k
    if (_used_by_s3_committer) {
524
        // If used_by_s3_committer, we always use multi-parts uploading.
525
0
        buf->set_upload_to_remote([part_num = _cur_part_num, this](UploadFileBuffer& buf) {
526
0
            _upload_one_part(part_num, buf);
527
0
        });
528
0
        DCHECK(_cur_part_num == 1);
529
0
        RETURN_IF_ERROR(_create_multi_upload_request());
530
1.02k
    } else {
531
        // if we only need to upload one file less than 5MB, we can just
532
        // call PutObject to reduce the network IO
533
1.02k
        buf->set_upload_to_remote([this](UploadFileBuffer& b) { _put_object(b); });
534
1.02k
    }
535
1.02k
    return Status::OK();
536
1.02k
}
537
538
1.02k
void S3FileWriter::_put_object(UploadFileBuffer& buf) {
539
1.02k
    MonotonicStopWatch timer;
540
1.02k
    timer.start();
541
542
1.02k
    if (state() == State::CLOSED) {
543
0
        DCHECK(state() != State::CLOSED)
544
0
                << "state=" << (int)state() << " path=" << _obj_storage_path_opts.path.native();
545
0
        LOG_WARNING("failed to put object because file closed, file path {}",
546
0
                    _obj_storage_path_opts.path.native());
547
0
        buf.set_status(Status::InternalError<false>("try to put closed file"));
548
0
        return;
549
0
    }
550
1.02k
    const auto& client = _obj_client->get();
551
1.02k
    if (nullptr == client) {
552
0
        buf.set_status(Status::InternalError<false>("invalid obj storage client"));
553
0
        return;
554
0
    }
555
1.02k
    TEST_SYNC_POINT_RETURN_WITH_VOID("S3FileWriter::_put_object", this, &buf);
556
1.01k
    auto resp = client->put_object(_obj_storage_path_opts, buf.get_string_view_data());
557
1.01k
    timer.stop();
558
559
1.01k
    if (resp.status.code != ErrorCode::OK) {
560
0
        LOG_WARNING("failed to put object, put object failed because {}, file path {}, time={}ms",
561
0
                    resp.status.msg, _obj_storage_path_opts.path.native(),
562
0
                    timer.elapsed_time_milliseconds());
563
0
        buf.set_status({resp.status.code, std::move(resp.status.msg)});
564
0
        return;
565
0
    }
566
567
1.01k
    auto st = check_after_upload(client.get(), resp, _obj_storage_path_opts, _bytes_appended,
568
1.01k
                                 "put_object");
569
1.01k
    if (!st.ok()) {
570
0
        buf.set_status(st);
571
0
        return;
572
0
    }
573
574
1.01k
    LOG(INFO) << "put_object " << _obj_storage_path_opts.path.native()
575
1.01k
              << " size=" << _bytes_appended << " time=" << timer.elapsed_time_milliseconds()
576
1.01k
              << "ms";
577
1.01k
    s3_file_created_total << 1;
578
1.01k
    s3_bytes_written_total << buf.get_size();
579
1.01k
}
580
581
3
std::string S3FileWriter::_dump_completed_part() const {
582
3
    std::stringstream ss;
583
3
    ss << "part_numbers:";
584
3
    for (const auto& part : _completed_parts) {
585
2
        ss << " " << part.part_num;
586
2
    }
587
3
    return ss.str();
588
3
}
589
590
} // namespace doris::io