Coverage Report

Created: 2026-07-23 11:19

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