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 POSIX_AIO_SUPPORTED()
60#if IS_LINUX_PLATFORM()
61// On 32-bit Linux, struct aiocb holds its file offset as a 32-bit off_t unless the whole build
62// sets _FILE_OFFSET_BITS=64. Use the explicit 64-bit control block, the same way
63// AsyncFileDescriptor uses lseek64 and pread64, so the layout of AsyncBuffer does not depend on
64// the feature macros of the code that includes this header.
65using AioControlBlock = aiocb64;
66#else
67using AioControlBlock = aiocb;
68#endif
69#endif
70
71#if IS_WINDOWS_PLATFORM()
72// Windows doesn't normally define these.
73using ssize_t = int64_t;
74#define O_DIRECT 0x80000000U
75
76struct VRS_API AsyncWindowsHandle {
77 AsyncWindowsHandle() : h_(INVALID_HANDLE_VALUE) {}
78 AsyncWindowsHandle(HANDLE h) : h_(h) {}
79 AsyncWindowsHandle(AsyncWindowsHandle&& rhs) : h_(rhs.h_) {
80 rhs.h_ = INVALID_HANDLE_VALUE;
81 }
82 AsyncWindowsHandle(AsyncWindowsHandle& rhs) : h_(rhs.h_) {}
83 AsyncWindowsHandle& operator=(AsyncWindowsHandle&& rhs) {
84 h_ = rhs.h_;
85 rhs.h_ = INVALID_HANDLE_VALUE;
86 return *this;
87 }
88
89 bool isOpened() const;
90 int open(const std::string& path, const char* modes, int flags);
91 int close();
92 int pwrite(const void* buf, size_t count, int64_t offset, size_t& outWriteSize);
93 int read(void* buf, size_t count, int64_t offset, size_t& outReadSize);
94 int truncate(int64_t newSize);
95 int seek(int64_t pos, int origin, int64_t& outFilepos);
96
97 private:
98 int _readwrite(bool readNotWrite, void* buf, size_t count, int64_t offset, size_t& outSize);
99
100 public:
101 HANDLE h_ = INVALID_HANDLE_VALUE;
102 std::mutex mtx_;
103};
104using AsyncHandle = AsyncWindowsHandle;
105#else
106struct VRS_API AsyncFileDescriptor {
107 static constexpr int INVALID_FILE_DESCRIPTOR = -1;
108
109 AsyncFileDescriptor() = default;
110 explicit AsyncFileDescriptor(int fd) : fd_(fd) {}
111 AsyncFileDescriptor(AsyncFileDescriptor&& rhs) noexcept : fd_(rhs.fd_) {
112 rhs.fd_ = INVALID_FILE_DESCRIPTOR;
113 }
114 AsyncFileDescriptor(const AsyncFileDescriptor& rhs) noexcept = delete;
115 AsyncFileDescriptor& operator=(AsyncFileDescriptor&& rhs) noexcept {
116 fd_ = rhs.fd_;
117 rhs.fd_ = INVALID_FILE_DESCRIPTOR;
118 return *this;
119 }
120 AsyncFileDescriptor& operator=(const AsyncFileDescriptor& rhs) = delete;
121
122 bool operator==(int fd) const {
123 return fd_ == fd;
124 }
125
126 int open(const std::string& path, const char* modes, int flags);
127 [[nodiscard]] bool isOpened() const;
128 int read(void* ptr, size_t bufferSize, int64_t offset, size_t& outReadSize);
129 int truncate(int64_t newSize);
130 int seek(int64_t pos, int origin, int64_t& outFilepos);
131 int pwrite(const void* buf, size_t count, int64_t offset, size_t& written);
132 int close();
133
134 int fd_ = INVALID_FILE_DESCRIPTOR;
135};
136using AsyncHandle = AsyncFileDescriptor;
137#endif
138
139class VRS_API AlignedBuffer {
140 private:
141 void* aligned_buffer_ = nullptr;
142 size_t capacity_ = 0;
143 size_t size_ = 0;
144
145 protected:
147 AlignedBuffer(size_t size, size_t memalign, size_t lenalign);
148
149 [[nodiscard]] inline bool isValid() const {
150 return aligned_buffer_ != nullptr;
151 }
152
153 public:
156 static std::unique_ptr<AlignedBuffer> make(size_t size, size_t memalign, size_t lenalign);
157
158 virtual ~AlignedBuffer();
159
160 [[nodiscard]] inline size_t size() const {
161 return size_;
162 }
163 [[nodiscard]] inline size_t capacity() const {
164 return capacity_;
165 }
166 [[nodiscard]] inline bool empty() const {
167 return !size();
168 }
169 [[nodiscard]] inline bool full() const {
170 return size() == capacity();
171 }
172
173 void free();
174 void clear();
175 [[nodiscard]] inline void* data() const {
176 return aligned_buffer_;
177 }
178 [[nodiscard]] inline char* bdata() const {
179 return reinterpret_cast<char*>(aligned_buffer_);
180 }
185 [[nodiscard]] bool add(const void* buffer, size_t size, size_t& outCopiedSize);
186};
187
188class AsyncBuffer;
189#if IS_WINDOWS_PLATFORM()
190struct VRS_API AsyncOVERLAPPED {
191 OVERLAPPED ov;
192 // Allows the completion routine to recover a pointer to the containing AsyncBuffer
193 AsyncBuffer* self;
194};
195#endif
196
197class VRS_API AsyncBuffer : public AlignedBuffer {
198 public:
199 using complete_write_callback = std::function<void(ssize_t io_return, int io_errno)>;
200
203 static std::unique_ptr<AsyncBuffer> make(size_t size, size_t memalign, size_t lenalign);
204
205 ~AsyncBuffer() override = default;
206
207 void complete_write(ssize_t io_return, int io_errno);
212 [[nodiscard]] int
213 start_write(const AsyncHandle& file, int64_t offset, complete_write_callback on_complete);
214
215 protected:
216 AsyncBuffer(size_t size, size_t memalign, size_t lenalign)
217 : AlignedBuffer(size, memalign, lenalign) {}
218
219 private:
220#if IS_WINDOWS_PLATFORM()
221 AsyncOVERLAPPED ov_;
222 static void CompletedWriteRoutine(DWORD dwErr, DWORD cbBytesWritten, LPOVERLAPPED lpOverlapped);
223#elif POSIX_AIO_SUPPORTED()
224 AioControlBlock aiocb_{};
225 using AioSubmitter = int (*)(decltype(aiocb_)*);
226 int startWrite(
227 const AsyncHandle& file,
228 int64_t offset,
229 complete_write_callback on_complete,
230 AioSubmitter submit);
231 static void SigEvNotifyFunction(union sigval val);
232 friend class AsyncDiskFileChunkTestPeer;
233#endif
234 complete_write_callback on_complete_ = nullptr;
235};
236
237class VRS_API AsyncDiskFileChunk {
238 public:
239 AsyncDiskFileChunk() = default;
240 AsyncDiskFileChunk(std::string path, int64_t offset, int64_t size)
241 : path_{std::move(path)}, offset_{offset}, size_{size} {}
242 AsyncDiskFileChunk(AsyncDiskFileChunk&& other) noexcept;
243
244 // Prevent copying
245 AsyncDiskFileChunk(const AsyncDiskFileChunk& other) noexcept = delete;
246 AsyncDiskFileChunk& operator=(const AsyncDiskFileChunk& other) noexcept = delete;
247 AsyncDiskFileChunk& operator=(AsyncDiskFileChunk&& rhs) noexcept = delete;
248
249 ~AsyncDiskFileChunk();
250
251 int create(const std::string& newpath, const FileSpec::Extras& options);
252 int open(bool readOnly, const FileSpec::Extras& options);
253 int close();
254 int rewind();
255 [[nodiscard]] bool eof() const;
256 bool isOpened();
257 int write(const void* buffer, size_t count, size_t& outWrittenSize);
258 void setSize(int64_t newSize);
259 int flush();
260 int truncate(int64_t newSize);
261 int read(void* buffer, size_t count, size_t& outReadSize);
262 [[nodiscard]] int64_t getSize() const;
263 [[nodiscard]] bool contains(int64_t fileOffset) const;
264 int tell(int64_t& outFilepos) const;
265 int seek(int64_t pos, int origin);
266 [[nodiscard]] const std::string& getPath() const;
267 void setOffset(int64_t newOffset);
268 [[nodiscard]] int64_t getOffset() const;
269
270 enum class IoEngine {
271 Sync,
272 AIO,
273 PSync,
274 };
275
276 private:
277 struct QueuedWrite {
278 AsyncBuffer* buffer_;
279 // N.B. QueuedWrite's are guaranteed to be flushed before the associated file descriptor is
280 // close, so storing this via reference is safe.
281 const AsyncHandle& file_;
282 int64_t offset_;
283 AsyncBuffer::complete_write_callback callback_;
284 QueuedWrite(
285 AsyncBuffer* buffer,
286 AsyncHandle& file,
287 int64_t offset,
288 AsyncBuffer::complete_write_callback callback)
289 : buffer_(buffer), file_(file), offset_(offset), callback_(std::move(callback)) {}
290 };
291
292 int flushWriteBuffer();
293 int ensureOpenNonDirect();
294 int ensureOpenDirect();
295 int ensureOpen_(int requested_flags);
296 void complete_write(AsyncBuffer* buffer, ssize_t io_return, int io_errno);
297 AsyncBuffer* get_free_buffer_locked(std::unique_lock<std::mutex>& lock);
298 AsyncBuffer* get_free_buffer();
299 void free_buffer(AsyncBuffer*& buffer);
300 void free_buffer_locked(std::unique_lock<std::mutex>& lock, AsyncBuffer*& buffer);
301 void pump_buffers();
302 using WriteSubmitter = std::function<int(QueuedWrite&)>;
303 void pump_buffers_locked(
304 std::unique_lock<std::mutex>& lock,
305 const WriteSubmitter& submit = nullptr);
306 void recordAsyncError(int error);
307 friend class AsyncDiskFileChunkTestPeer;
308 int alloc_write_buffers();
309 int free_write_buffers();
310 int init_parameters(const FileSpec::Extras& options);
311
312 AsyncHandle file_{};
313 std::string path_; // path of this chunk
314 int64_t offset_{}; // offset of this chunk in the file
315 int64_t size_{}; // size of the chunk
316
317 // Keeps track of the current read/write position in the file of the current buffer.
318 int64_t file_position_ = 0;
319
320 const char* file_mode_ = nullptr;
321 // Keeps track of the flags currently in force for the opened fd_. Typically a subset of the
322 // supported_flags_
323 int current_flags_ = 0;
324 // The flags supported by the underlying path_ file
325 int supported_flags_ = 0;
326
327 // Protects the following members from the writing thread as well as the asyncio callback
328 // thread(s). Note that this lock is not really required on Windows, as the callbacks are
329 // delivered on the dispatching thread when it's in an alertable state.
330 std::mutex buffers_mutex_;
331 // Used to notify a waiting writing thread that a buffer was freed.
332 std::condition_variable buffer_freed_cv_;
333 // The list of free buffers
334 std::vector<AsyncBuffer*> buffers_free_;
335 // The list of buffers to be written. Drained by pump_buffers()
336 std::deque<QueuedWrite> buffers_queued_;
337 // A count of the number of buffers waiting on async completions
338 //
339 // This could be a std::atomic<size_t>, but the current implementation has to take the lock
340 // anyway to manage the list of buffers_free_, so don't bother.
341 size_t buffers_writing_ = 0;
342 // A list of all the buffers to keep them alive when they are being written (no longer in any
343 // other queue)
344 std::vector<std::unique_ptr<AsyncBuffer>> buffers_;
345 // The current buffer (if any) being filled by calls to `write()`. It will either be queued
346 // for async write by `write()`, or written out by `flushWriteBuffer()`
347 AsyncBuffer* current_buffer_ = nullptr;
348 // If != SUCCESS, represents errors that were signaled by async writes completing. Typically
349 // returned to the caller as the result of another, later operation (e.g. another write after
350 // the failure, or a call to flushWriteBuffer(), etc)
351 std::atomic<int> async_error_ = SUCCESS;
352
353 // Operational parameters initialized from the FileSpec extra params/options at create/open
354 // time. These can be tuned by the user via uri parameters.
355 IoEngine ioengine_ = IoEngine::AIO;
356 bool use_directio_ = true;
357 // How many asyncio buffers to allocate and fill
358 size_t num_buffers_ = 0;
359 // The size of each individual buffer
360 size_t buffer_size_ = 0;
361 // The maximum number of simultaneous async_write operations allowed
362 size_t iodepth_ = 4;
363 // The requested alignment of buffer lengths and file offsets
364 size_t offset_align_ = 0;
365 // The requested length of memory alignment
366 size_t mem_align_ = 0;
367};
368
369} // namespace vrs
370
371#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:130