VRS
A file format for sensor data.
Loading...
Searching...
No Matches
AsyncDiskFileChunk.h
1/*
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#pragma once
18
19#include <vrs/DiskFile.h>
20
21#if VRS_ASYNC_DISKFILE_SUPPORTED()
22
23#include <cassert>
24#include <cstdio>
25
26// POSIX AIO (aio_write/aio_error/aio_return) is available on Linux/Mac but not Android NDK.
27// When AIO is not available, fallback to PSync (O_DIRECT + pwrite) which bypasses page cache
28// without needing POSIX AIO.
29#define POSIX_AIO_SUPPORTED() (IS_MAC_PLATFORM() || IS_LINUX_PLATFORM())
30
31#if IS_WINDOWS_PLATFORM()
32#define VC_EXTRALEAN
33#include <Windows.h>
34#elif POSIX_AIO_SUPPORTED()
35#include <aio.h>
36#include <fcntl.h>
37#include <unistd.h>
38#else
39#include <fcntl.h>
40#include <unistd.h>
41#endif
42
43#include <atomic>
44#include <condition_variable>
45#include <deque>
46#include <functional>
47#include <map>
48#include <memory>
49#include <string>
50
51#include <vrs/ErrorCode.h>
52#include <vrs/VrsExport.h>
53#include <vrs/os/Platform.h>
54
55#define VRS_DISKFILECHUNK "AsyncDiskFileChunk"
56
57namespace vrs {
58
59#if IS_WINDOWS_PLATFORM()
60// Windows doesn't normally define these.
61using ssize_t = int64_t;
62#define O_DIRECT 0x80000000U
63
64struct VRS_API AsyncWindowsHandle {
65 AsyncWindowsHandle() : h_(INVALID_HANDLE_VALUE) {}
66 AsyncWindowsHandle(HANDLE h) : h_(h) {}
67 AsyncWindowsHandle(AsyncWindowsHandle&& rhs) : h_(rhs.h_) {
68 rhs.h_ = INVALID_HANDLE_VALUE;
69 }
70 AsyncWindowsHandle(AsyncWindowsHandle& rhs) : h_(rhs.h_) {}
71 AsyncWindowsHandle& operator=(AsyncWindowsHandle&& rhs) {
72 h_ = rhs.h_;
73 rhs.h_ = INVALID_HANDLE_VALUE;
74 return *this;
75 }
76
77 bool isOpened() const;
78 int open(const std::string& path, const char* modes, int flags);
79 int close();
80 int pwrite(const void* buf, size_t count, int64_t offset, size_t& outWriteSize);
81 int read(void* buf, size_t count, int64_t offset, size_t& outReadSize);
82 int truncate(int64_t newSize);
83 int seek(int64_t pos, int origin, int64_t& outFilepos);
84
85 private:
86 int _readwrite(bool readNotWrite, void* buf, size_t count, int64_t offset, size_t& outSize);
87
88 public:
89 HANDLE h_ = INVALID_HANDLE_VALUE;
90 std::mutex mtx_;
91};
92using AsyncHandle = AsyncWindowsHandle;
93#else
94struct VRS_API AsyncFileDescriptor {
95 static constexpr int INVALID_FILE_DESCRIPTOR = -1;
96
97 AsyncFileDescriptor() = default;
98 explicit AsyncFileDescriptor(int fd) : fd_(fd) {}
99 AsyncFileDescriptor(AsyncFileDescriptor&& rhs) noexcept : fd_(rhs.fd_) {
100 rhs.fd_ = INVALID_FILE_DESCRIPTOR;
101 }
102 AsyncFileDescriptor(const AsyncFileDescriptor& rhs) noexcept = delete;
103 AsyncFileDescriptor& operator=(AsyncFileDescriptor&& rhs) noexcept {
104 fd_ = rhs.fd_;
105 rhs.fd_ = INVALID_FILE_DESCRIPTOR;
106 return *this;
107 }
108 AsyncFileDescriptor& operator=(const AsyncFileDescriptor& rhs) = delete;
109
110 bool operator==(int fd) const {
111 return fd_ == fd;
112 }
113
114 int open(const std::string& path, const char* modes, int flags);
115 [[nodiscard]] bool isOpened() const;
116 int read(void* ptr, size_t bufferSize, size_t offset, size_t& outReadSize);
117 int truncate(int64_t newSize);
118 int seek(int64_t pos, int origin, int64_t& outFilepos);
119 int pwrite(const void* buf, size_t count, off_t offset, size_t& written);
120 int close();
121
122 int fd_ = INVALID_FILE_DESCRIPTOR;
123};
124using AsyncHandle = AsyncFileDescriptor;
125#endif
126
127class VRS_API AlignedBuffer {
128 private:
129 void* aligned_buffer_ = nullptr;
130 size_t capacity_ = 0;
131 size_t size_ = 0;
132
133 public:
134 AlignedBuffer(size_t size, size_t memalign, size_t lenalign);
135 virtual ~AlignedBuffer();
136
137 [[nodiscard]] inline size_t size() const {
138 return size_;
139 }
140 [[nodiscard]] inline size_t capacity() const {
141 return capacity_;
142 }
143 [[nodiscard]] inline bool empty() const {
144 return !size();
145 }
146 [[nodiscard]] inline bool full() const {
147 return size() == capacity();
148 }
149
150 void free();
151 void clear();
152 [[nodiscard]] inline void* data() const {
153 return aligned_buffer_;
154 }
155 [[nodiscard]] inline char* bdata() const {
156 return reinterpret_cast<char*>(aligned_buffer_);
157 }
158 [[nodiscard]] ssize_t add(const void* buffer, size_t size);
159};
160
161class AsyncBuffer;
162#if IS_WINDOWS_PLATFORM()
163struct VRS_API AsyncOVERLAPPED {
164 OVERLAPPED ov;
165 // Allows the completion routine to recover a pointer to the containing AsyncBuffer
166 AsyncBuffer* self;
167};
168#endif
169
170class VRS_API AsyncBuffer : public AlignedBuffer {
171 public:
172 using complete_write_callback = std::function<void(ssize_t io_return, int io_errno)>;
173
174 AsyncBuffer(size_t size, size_t memalign, size_t lenalign)
175 : AlignedBuffer(size, memalign, lenalign) {}
176 ~AsyncBuffer() override = default;
177
178 void complete_write(ssize_t io_return, int io_errno);
179 [[nodiscard]] int
180 start_write(const AsyncHandle& file, int64_t offset, complete_write_callback on_complete);
181
182 private:
183#if IS_WINDOWS_PLATFORM()
184 AsyncOVERLAPPED ov_;
185 static void CompletedWriteRoutine(DWORD dwErr, DWORD cbBytesWritten, LPOVERLAPPED lpOverlapped);
186#elif POSIX_AIO_SUPPORTED()
187 struct aiocb aiocb_{};
188 static void SigEvNotifyFunction(union sigval val);
189#endif
190 complete_write_callback on_complete_ = nullptr;
191};
192
193class VRS_API AsyncDiskFileChunk {
194 public:
195 AsyncDiskFileChunk() = default;
196 AsyncDiskFileChunk(std::string path, int64_t offset, int64_t size)
197 : path_{std::move(path)}, offset_{offset}, size_{size} {}
198 AsyncDiskFileChunk(AsyncDiskFileChunk&& other) noexcept;
199
200 // Prevent copying
201 AsyncDiskFileChunk(const AsyncDiskFileChunk& other) noexcept = delete;
202 AsyncDiskFileChunk& operator=(const AsyncDiskFileChunk& other) noexcept = delete;
203 AsyncDiskFileChunk& operator=(AsyncDiskFileChunk&& rhs) noexcept = delete;
204
205 ~AsyncDiskFileChunk();
206
207 int create(const std::string& newpath, const FileSpec::Extras& options);
208 int open(bool readOnly, const FileSpec::Extras& options);
209 int close();
210 int rewind();
211 [[nodiscard]] bool eof() const;
212 bool isOpened();
213 int write(const void* buffer, size_t count, size_t& outWrittenSize);
214 void setSize(int64_t newSize);
215 int flush();
216 int truncate(int64_t newSize);
217 int read(void* buffer, size_t count, size_t& outReadSize);
218 [[nodiscard]] int64_t getSize() const;
219 [[nodiscard]] bool contains(int64_t fileOffset) const;
220 int tell(int64_t& outFilepos) const;
221 int seek(int64_t pos, int origin);
222 [[nodiscard]] const std::string& getPath() const;
223 void setOffset(int64_t newOffset);
224 [[nodiscard]] int64_t getOffset() const;
225
226 enum class IoEngine {
227 Sync,
228 AIO,
229 PSync,
230 };
231
232 private:
233 struct QueuedWrite {
234 AsyncBuffer* buffer_;
235 // N.B. QueuedWrite's are guaranteed to be flushed before the associated file descriptor is
236 // close, so storing this via reference is safe.
237 const AsyncHandle& file_;
238 off_t offset_;
239 AsyncBuffer::complete_write_callback callback_;
240 QueuedWrite(
241 AsyncBuffer* buffer,
242 AsyncHandle& file,
243 off_t offset,
244 AsyncBuffer::complete_write_callback callback)
245 : buffer_(buffer), file_(file), offset_(offset), callback_(std::move(callback)) {}
246 };
247
248 int flushWriteBuffer();
249 int ensureOpenNonDirect();
250 int ensureOpenDirect();
251 int ensureOpen_(int requested_flags);
252 void complete_write(AsyncBuffer* buffer, ssize_t io_return, int io_errno);
253 AsyncBuffer* get_free_buffer_locked(std::unique_lock<std::mutex>& lock);
254 AsyncBuffer* get_free_buffer();
255 void free_buffer(AsyncBuffer*& buffer);
256 void free_buffer_locked(std::unique_lock<std::mutex>& lock, AsyncBuffer*& buffer);
257 void pump_buffers();
258 void pump_buffers_locked();
259 int alloc_write_buffers();
260 int free_write_buffers();
261 int init_parameters(const FileSpec::Extras& options);
262
263 AsyncHandle file_{};
264 std::string path_; // path of this chunk
265 int64_t offset_{}; // offset of this chunk in the file
266 int64_t size_{}; // size of the chunk
267
268 // Keeps track of the current read/write position in the file of the current buffer.
269 int64_t file_position_ = 0;
270
271 const char* file_mode_ = nullptr;
272 // Keeps track of the flags currently in force for the opened fd_. Typically a subset of the
273 // supported_flags_
274 int current_flags_ = 0;
275 // The flags supported by the underlying path_ file
276 int supported_flags_ = 0;
277
278 // Protects the following members from the writing thread as well as the asyncio callback
279 // thread(s). Note that this lock is not really required on Windows, as the callbacks are
280 // delivered on the dispatching thread when it's in an alertable state.
281 std::mutex buffers_mutex_;
282 // Used to notify a waiting writing thread that a buffer was freed.
283 std::condition_variable buffer_freed_cv_;
284 // The list of free buffers
285 std::vector<AsyncBuffer*> buffers_free_;
286 // The list of buffers to be written. Drained by pump_buffers()
287 std::deque<QueuedWrite> buffers_queued_;
288 // A count of the number of buffers waiting on async completions
289 //
290 // This could be a std::atomic<size_t>, but the current implementation has to take the lock
291 // anyway to manage the list of buffers_free_, so don't bother.
292 size_t buffers_writing_ = 0;
293 // A list of all the buffers to keep them alive when they are being written (no longer in any
294 // other queue)
295 std::vector<std::unique_ptr<AsyncBuffer>> buffers_;
296 // The current buffer (if any) being filled by calls to `write()`. It will either be queued
297 // for async write by `write()`, or written out by `flushWriteBuffer()`
298 AsyncBuffer* current_buffer_ = nullptr;
299 // If != SUCCESS, represents errors that were signaled by async writes completing. Typically
300 // returned to the caller as the result of another, later operation (e.g. another write after
301 // the failure, or a call to flushWriteBuffer(), etc)
302 std::atomic<int> async_error_ = SUCCESS;
303
304 // Operational parameters initialized from the FileSpec extra params/options at create/open
305 // time. These can be tuned by the user via uri parameters.
306 IoEngine ioengine_ = IoEngine::AIO;
307 bool use_directio_ = true;
308 // How many asyncio buffers to allocate and fill
309 size_t num_buffers_ = 0;
310 // The size of each individual buffer
311 size_t buffer_size_ = 0;
312 // The maximum number of simultaneous async_write operations allowed
313 size_t iodepth_ = 4;
314 // The requested alignment of buffer lengths and file offsets
315 size_t offset_align_ = 0;
316 // The requested length of memory alignment
317 size_t mem_align_ = 0;
318};
319
320} // namespace vrs
321
322#endif
int write(const string &cacheFile, const set< StreamId > &streamIds, const map< string, string > &fileTags, const map< StreamId, StreamTags > &streamTags, const vector< IndexRecord::RecordInfo > &recordIndex, bool fileHasIndex)
Definition FileDetailsCache.cpp:225
int read(const string &cacheFile, set< StreamId > &outStreamIds, map< string, string > &outFileTags, map< StreamId, StreamTags > &outStreamTags, vector< IndexRecord::RecordInfo > &outRecordIndex, bool &outFileHasIndex)
Definition FileDetailsCache.cpp:266
Definition Compressor.cpp:113