Coverage Report

Created: 2026-04-13 08:21

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/io/fs/local_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/local_file_writer.h"
19
20
// IWYU pragma: no_include <bthread/errno.h>
21
#include <errno.h> // IWYU pragma: keep
22
#include <fcntl.h>
23
#include <glog/logging.h>
24
#include <sys/uio.h>
25
#include <unistd.h>
26
27
#include <algorithm>
28
#include <cstring>
29
#include <ostream>
30
#include <utility>
31
32
// IWYU pragma: no_include <opentelemetry/common/threadlocal.h>
33
#include "common/cast_set.h"
34
#include "common/compiler_util.h" // IWYU pragma: keep
35
#include "common/macros.h"
36
#include "common/metrics/doris_metrics.h"
37
#include "common/status.h"
38
#include "cpp/sync_point.h"
39
#include "io/fs/err_utils.h"
40
#include "io/fs/file_writer.h"
41
#include "io/fs/local_file_system.h"
42
#include "io/fs/path.h"
43
#include "storage/data_dir.h"
44
#include "util/debug_points.h"
45
46
namespace doris::io {
47
namespace {
48
49
38.4k
Status sync_dir(const io::Path& dirname) {
50
38.4k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("sync_dir", Status::IOError(""));
51
38.4k
    int fd;
52
38.4k
    RETRY_ON_EINTR(fd, ::open(dirname.c_str(), O_DIRECTORY | O_RDONLY));
53
38.4k
    if (-1 == fd) {
54
0
        return localfs_error(errno, fmt::format("failed to open {}", dirname.native()));
55
0
    }
56
46.0k
    Defer defer {[fd] { ::close(fd); }};
57
#ifdef __APPLE__
58
    if (fcntl(fd, F_FULLFSYNC) < 0) {
59
        return localfs_error(errno, fmt::format("failed to sync {}", dirname.native()));
60
    }
61
#else
62
38.4k
    if (0 != ::fdatasync(fd)) {
63
0
        return localfs_error(errno, fmt::format("failed to sync {}", dirname.native()));
64
0
    }
65
38.4k
#endif
66
38.4k
    return Status::OK();
67
38.4k
}
68
69
} // namespace
70
71
LocalFileWriter::LocalFileWriter(Path path, int fd, bool sync_data)
72
168k
        : _path(std::move(path)), _fd(fd), _sync_data(sync_data) {
73
168k
    DorisMetrics::instance()->local_file_open_writing->increment(1);
74
168k
    DorisMetrics::instance()->local_file_writer_total->increment(1);
75
168k
}
76
77
255k
size_t LocalFileWriter::bytes_appended() const {
78
255k
    return _bytes_appended;
79
255k
}
80
81
167k
LocalFileWriter::~LocalFileWriter() {
82
167k
    if (_state == State::OPENED) {
83
23
        _abort();
84
23
    }
85
167k
    DorisMetrics::instance()->local_file_open_writing->increment(-1);
86
167k
    DorisMetrics::instance()->file_created_total->increment(1);
87
167k
    DorisMetrics::instance()->local_bytes_written_total->increment(_bytes_appended);
88
167k
}
89
90
175k
Status LocalFileWriter::close(bool non_block) {
91
175k
    if (_state == State::CLOSED) {
92
0
        return Status::InternalError("LocalFileWriter already closed, file path {}",
93
0
                                     _path.native());
94
0
    }
95
175k
    if (_state == State::ASYNC_CLOSING) {
96
7.06k
        if (non_block) {
97
0
            return Status::InternalError("Don't submit async close multi times");
98
0
        }
99
        // Actucally the first time call to close(true) would return the value of _finalize, if it returned one
100
        // error status then the code would never call the second close(true)
101
7.06k
        _state = State::CLOSED;
102
7.06k
        return Status::OK();
103
7.06k
    }
104
168k
    if (non_block) {
105
7.07k
        _state = State::ASYNC_CLOSING;
106
161k
    } else {
107
161k
        _state = State::CLOSED;
108
161k
    }
109
168k
    return _close(_sync_data);
110
175k
}
111
112
23
void LocalFileWriter::_abort() {
113
23
    auto st = _close(false);
114
23
    if (!st.ok()) [[unlikely]] {
115
0
        LOG(WARNING) << "close file failed when abort file writer: " << st;
116
0
    }
117
23
    st = io::global_local_filesystem()->delete_file(_path);
118
23
    if (!st.ok()) [[unlikely]] {
119
0
        LOG(WARNING) << "delete file failed when abort file writer: " << st;
120
0
    }
121
23
}
122
123
250k
Status LocalFileWriter::appendv(const Slice* data, size_t data_cnt) {
124
250k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("LocalFileWriter::appendv",
125
250k
                                      Status::IOError("inject io error"));
126
250k
    if (_state != State::OPENED) [[unlikely]] {
127
0
        return Status::InternalError("append to closed file: {}", _path.native());
128
0
    }
129
250k
    _dirty = true;
130
131
    // Convert the results into the iovec vector to request
132
    // and calculate the total bytes requested.
133
250k
    size_t bytes_req = 0;
134
250k
    std::vector<iovec> iov(data_cnt);
135
537k
    for (size_t i = 0; i < data_cnt; i++) {
136
286k
        const Slice& result = data[i];
137
286k
        bytes_req += result.size;
138
286k
        iov[i] = {result.data, result.size};
139
286k
    }
140
141
250k
    size_t completed_iov = 0;
142
250k
    size_t n_left = bytes_req;
143
250k
    while (n_left > 0) {
144
        // Never request more than IOV_MAX in one request.
145
250k
        size_t iov_count = std::min(data_cnt - completed_iov, static_cast<size_t>(IOV_MAX));
146
250k
        ssize_t res;
147
250k
        RETRY_ON_EINTR(res, SYNC_POINT_HOOK_RETURN_VALUE(::writev(_fd, iov.data() + completed_iov,
148
250k
                                                                  cast_set<int32_t>(iov_count)),
149
250k
                                                         "LocalFileWriter::writev", _fd));
150
250k
        DBUG_EXECUTE_IF("LocalFileWriter::appendv.io_error", {
151
250k
            auto sub_path = dp->param<std::string>("sub_path", "");
152
250k
            if ((sub_path.empty() && _path.filename().compare(kTestFilePath)) ||
153
250k
                (!sub_path.empty() && _path.native().find(sub_path) != std::string::npos)) {
154
250k
                res = -1;
155
250k
                errno = EIO;
156
250k
                LOG(WARNING) << Status::IOError("debug write io error: {}", _path.native());
157
250k
            }
158
250k
        });
159
250k
        if (UNLIKELY(res < 0)) {
160
0
            return localfs_error(errno, fmt::format("failed to write {}", _path.native()));
161
0
        }
162
163
250k
        if (LIKELY(res == n_left)) {
164
            // All requested bytes were read. This is almost always the case.
165
250k
            n_left = 0;
166
250k
            break;
167
250k
        }
168
        // Adjust iovec vector based on bytes read for the next request.
169
0
        ssize_t bytes_rem = res;
170
0
        for (size_t i = completed_iov; i < data_cnt; i++) {
171
0
            if (bytes_rem >= iov[i].iov_len) {
172
                // The full length of this iovec was written.
173
0
                completed_iov++;
174
0
                bytes_rem -= iov[i].iov_len;
175
0
            } else {
176
                // Partially wrote this result.
177
                // Adjust the iov_len and iov_base to write only the missing data.
178
0
                iov[i].iov_base = static_cast<uint8_t*>(iov[i].iov_base) + bytes_rem;
179
0
                iov[i].iov_len -= bytes_rem;
180
0
                break; // Don't need to adjust remaining iovec's.
181
0
            }
182
0
        }
183
0
        n_left -= res;
184
0
    }
185
250k
    DCHECK_EQ(0, n_left);
186
250k
    _bytes_appended += bytes_req;
187
250k
    return Status::OK();
188
250k
}
189
190
// TODO(ByteYue): Refactor this function as FileWriter::flush()
191
0
Status LocalFileWriter::_finalize() {
192
0
    TEST_SYNC_POINT_RETURN_WITH_VALUE("LocalFileWriter::finalize",
193
0
                                      Status::IOError("inject io error"));
194
0
    if (_state == State::OPENED) [[unlikely]] {
195
0
        return Status::InternalError("finalize closed file: {}", _path.native());
196
0
    }
197
198
0
    if (_dirty) {
199
0
#if defined(__linux__)
200
0
        int flags = SYNC_FILE_RANGE_WRITE;
201
0
        if (sync_file_range(_fd, 0, 0, flags) < 0) {
202
0
            return localfs_error(errno, fmt::format("failed to finalize {}", _path.native()));
203
0
        }
204
0
#endif
205
0
    }
206
0
    return Status::OK();
207
0
}
208
209
155k
Status LocalFileWriter::_close(bool sync) {
210
214k
    auto fd_reclaim_func = [&](Status st) {
211
214k
        if (_fd > 0 && 0 != ::close(_fd)) {
212
0
            return localfs_error(errno, fmt::format("failed to {}, along with failed to close {}",
213
0
                                                    st, _path.native()));
214
0
        }
215
214k
        _fd = -1;
216
214k
        return st;
217
214k
    };
218
155k
    if (sync && config::sync_file_on_close) {
219
38.4k
        if (_dirty) {
220
#ifdef __APPLE__
221
            if (fcntl(_fd, F_FULLFSYNC) < 0) [[unlikely]] {
222
                return fd_reclaim_func(
223
                        localfs_error(errno, fmt::format("failed to sync {}", _path.native())));
224
            }
225
#else
226
38.4k
            if (0 != ::fdatasync(_fd)) [[unlikely]] {
227
0
                return fd_reclaim_func(
228
0
                        localfs_error(errno, fmt::format("failed to sync {}", _path.native())));
229
0
            }
230
38.4k
#endif
231
38.4k
            _dirty = false;
232
38.4k
        }
233
38.4k
        RETURN_IF_ERROR(fd_reclaim_func(sync_dir(_path.parent_path())));
234
38.4k
    }
235
236
155k
    DBUG_EXECUTE_IF("LocalFileWriter.close.failed", {
237
        // spare '.testfile' to make bad disk checker happy
238
155k
        if (_path.filename().compare(kTestFilePath)) {
239
155k
            return fd_reclaim_func(
240
155k
                    Status::IOError("cannot close {}: {}", _path.native(), std::strerror(errno)));
241
155k
        }
242
155k
    });
243
244
155k
    TEST_SYNC_POINT_RETURN_WITH_VALUE("LocalFileWriter::close", Status::IOError("inject io error"));
245
155k
    return fd_reclaim_func(Status::OK());
246
155k
}
247
248
} // namespace doris::io