Line data Source code
1 : //! VirtualFile is like a normal File, but it's not bound directly to
2 : //! a file descriptor.
3 : //!
4 : //! Instead, the file is opened when it's read from,
5 : //! and if too many files are open globally in the system, least-recently
6 : //! used ones are closed.
7 : //!
8 : //! To track which files have been recently used, we use the clock algorithm
9 : //! with a 'recently_used' flag on each slot.
10 : //!
11 : //! This is similar to PostgreSQL's virtual file descriptor facility in
12 : //! src/backend/storage/file/fd.c
13 : //!
14 : use std::fs::File;
15 : use std::io::{Error, ErrorKind, Seek, SeekFrom};
16 : use std::os::fd::{AsRawFd, FromRawFd, IntoRawFd, OwnedFd, RawFd};
17 : #[cfg(target_os = "linux")]
18 : use std::os::unix::fs::OpenOptionsExt;
19 : use std::sync::atomic::{AtomicBool, AtomicU8, AtomicUsize, Ordering};
20 :
21 : use camino::{Utf8Path, Utf8PathBuf};
22 : use once_cell::sync::OnceCell;
23 : use owned_buffers_io::aligned_buffer::buffer::AlignedBuffer;
24 : use owned_buffers_io::aligned_buffer::{AlignedBufferMut, AlignedSlice, ConstAlign};
25 : use owned_buffers_io::io_buf_aligned::{IoBufAligned, IoBufAlignedMut};
26 : use owned_buffers_io::io_buf_ext::FullSlice;
27 : use pageserver_api::config::defaults::DEFAULT_IO_BUFFER_ALIGNMENT;
28 : pub use pageserver_api::models::virtual_file as api;
29 : use tokio::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard};
30 : use tokio::time::Instant;
31 : use tokio_epoll_uring::{BoundedBuf, IoBuf, IoBufMut, Slice};
32 :
33 : use crate::assert_u64_eq_usize::UsizeIsU64;
34 : use crate::context::RequestContext;
35 : use crate::metrics::{STORAGE_IO_TIME_METRIC, StorageIoOperation};
36 : use crate::page_cache::{PAGE_SZ, PageWriteGuard};
37 : pub(crate) mod io_engine;
38 : pub use io_engine::{
39 : FeatureTestResult as IoEngineFeatureTestResult, feature_test as io_engine_feature_test,
40 : io_engine_for_bench,
41 : };
42 : mod metadata;
43 : mod open_options;
44 : pub(crate) use api::IoMode;
45 : pub(crate) use io_engine::IoEngineKind;
46 : pub(crate) use metadata::Metadata;
47 : pub(crate) use open_options::*;
48 :
49 : use self::owned_buffers_io::write::OwnedAsyncWriter;
50 :
51 : pub(crate) mod owned_buffers_io {
52 : //! Abstractions for IO with owned buffers.
53 : //!
54 : //! Not actually tied to [`crate::virtual_file`] specifically, but, it's the primary
55 : //! reason we need this abstraction.
56 : //!
57 : //! Over time, this could move into the `tokio-epoll-uring` crate, maybe `uring-common`,
58 : //! but for the time being we're proving out the primitives in the neon.git repo
59 : //! for faster iteration.
60 :
61 : pub(crate) mod aligned_buffer;
62 : pub(crate) mod io_buf_aligned;
63 : pub(crate) mod io_buf_ext;
64 : pub(crate) mod slice;
65 : pub(crate) mod write;
66 : }
67 :
68 : #[derive(Debug)]
69 : pub struct VirtualFile {
70 : inner: VirtualFileInner,
71 : _mode: IoMode,
72 : }
73 :
74 : impl VirtualFile {
75 : /// Open a file in read-only mode. Like File::open.
76 2112 : pub async fn open<P: AsRef<Utf8Path>>(
77 2112 : path: P,
78 2112 : ctx: &RequestContext,
79 2112 : ) -> Result<Self, std::io::Error> {
80 2112 : let inner = VirtualFileInner::open(path, ctx).await?;
81 2112 : Ok(VirtualFile {
82 2112 : inner,
83 2112 : _mode: IoMode::Buffered,
84 2112 : })
85 2112 : }
86 :
87 : /// Open a file in read-only mode. Like File::open.
88 : ///
89 : /// `O_DIRECT` will be enabled base on `virtual_file_io_mode`.
90 2464 : pub async fn open_v2<P: AsRef<Utf8Path>>(
91 2464 : path: P,
92 2464 : ctx: &RequestContext,
93 2464 : ) -> Result<Self, std::io::Error> {
94 2464 : Self::open_with_options_v2(path.as_ref(), OpenOptions::new().read(true), ctx).await
95 2464 : }
96 :
97 3030 : pub async fn create<P: AsRef<Utf8Path>>(
98 3030 : path: P,
99 3030 : ctx: &RequestContext,
100 3030 : ) -> Result<Self, std::io::Error> {
101 3030 : let inner = VirtualFileInner::create(path, ctx).await?;
102 3030 : Ok(VirtualFile {
103 3030 : inner,
104 3030 : _mode: IoMode::Buffered,
105 3030 : })
106 3030 : }
107 :
108 0 : pub async fn create_v2<P: AsRef<Utf8Path>>(
109 0 : path: P,
110 0 : ctx: &RequestContext,
111 0 : ) -> Result<Self, std::io::Error> {
112 0 : VirtualFile::open_with_options_v2(
113 0 : path.as_ref(),
114 0 : OpenOptions::new().write(true).create(true).truncate(true),
115 0 : ctx,
116 0 : )
117 0 : .await
118 0 : }
119 :
120 1616 : pub async fn open_with_options<P: AsRef<Utf8Path>>(
121 1616 : path: P,
122 1616 : open_options: &OpenOptions,
123 1616 : ctx: &RequestContext,
124 1616 : ) -> Result<Self, std::io::Error> {
125 1616 : let inner = VirtualFileInner::open_with_options(path, open_options, ctx).await?;
126 1616 : Ok(VirtualFile {
127 1616 : inner,
128 1616 : _mode: IoMode::Buffered,
129 1616 : })
130 1616 : }
131 :
132 5096 : pub async fn open_with_options_v2<P: AsRef<Utf8Path>>(
133 5096 : path: P,
134 5096 : open_options: &OpenOptions,
135 5096 : ctx: &RequestContext,
136 5096 : ) -> Result<Self, std::io::Error> {
137 5096 : let file = match get_io_mode() {
138 : IoMode::Buffered => {
139 5096 : let inner = VirtualFileInner::open_with_options(path, open_options, ctx).await?;
140 5096 : VirtualFile {
141 5096 : inner,
142 5096 : _mode: IoMode::Buffered,
143 5096 : }
144 : }
145 : #[cfg(target_os = "linux")]
146 : IoMode::Direct => {
147 0 : let inner = VirtualFileInner::open_with_options(
148 0 : path,
149 0 : open_options.clone().custom_flags(nix::libc::O_DIRECT),
150 0 : ctx,
151 0 : )
152 0 : .await?;
153 0 : VirtualFile {
154 0 : inner,
155 0 : _mode: IoMode::Direct,
156 0 : }
157 : }
158 : };
159 5096 : Ok(file)
160 5096 : }
161 :
162 2388 : pub fn path(&self) -> &Utf8Path {
163 2388 : self.inner.path.as_path()
164 2388 : }
165 :
166 44 : pub async fn crashsafe_overwrite<B: BoundedBuf<Buf = Buf> + Send, Buf: IoBuf + Send>(
167 44 : final_path: Utf8PathBuf,
168 44 : tmp_path: Utf8PathBuf,
169 44 : content: B,
170 44 : ) -> std::io::Result<()> {
171 44 : VirtualFileInner::crashsafe_overwrite(final_path, tmp_path, content).await
172 44 : }
173 :
174 5650 : pub async fn sync_all(&self) -> Result<(), Error> {
175 5650 : if SYNC_MODE.load(std::sync::atomic::Ordering::Relaxed) == SyncMode::UnsafeNoSync as u8 {
176 0 : return Ok(());
177 5650 : }
178 5650 : self.inner.sync_all().await
179 5650 : }
180 :
181 0 : pub async fn sync_data(&self) -> Result<(), Error> {
182 0 : if SYNC_MODE.load(std::sync::atomic::Ordering::Relaxed) == SyncMode::UnsafeNoSync as u8 {
183 0 : return Ok(());
184 0 : }
185 0 : self.inner.sync_data().await
186 0 : }
187 :
188 3620 : pub async fn metadata(&self) -> Result<Metadata, Error> {
189 3620 : self.inner.metadata().await
190 3620 : }
191 :
192 524 : pub fn remove(self) {
193 524 : self.inner.remove();
194 524 : }
195 :
196 11408 : pub async fn seek(&mut self, pos: SeekFrom) -> Result<u64, Error> {
197 11408 : self.inner.seek(pos).await
198 11408 : }
199 :
200 461852 : pub async fn read_exact_at<Buf>(
201 461852 : &self,
202 461852 : slice: Slice<Buf>,
203 461852 : offset: u64,
204 461852 : ctx: &RequestContext,
205 461852 : ) -> Result<Slice<Buf>, Error>
206 461852 : where
207 461852 : Buf: IoBufAlignedMut + Send,
208 461852 : {
209 461852 : self.inner.read_exact_at(slice, offset, ctx).await
210 461852 : }
211 :
212 63468 : pub async fn read_exact_at_page(
213 63468 : &self,
214 63468 : page: PageWriteGuard<'static>,
215 63468 : offset: u64,
216 63468 : ctx: &RequestContext,
217 63468 : ) -> Result<PageWriteGuard<'static>, Error> {
218 63468 : self.inner.read_exact_at_page(page, offset, ctx).await
219 63468 : }
220 :
221 13222 : pub async fn write_all_at<Buf: IoBufAligned + Send>(
222 13222 : &self,
223 13222 : buf: FullSlice<Buf>,
224 13222 : offset: u64,
225 13222 : ctx: &RequestContext,
226 13222 : ) -> (FullSlice<Buf>, Result<(), Error>) {
227 13222 : self.inner.write_all_at(buf, offset, ctx).await
228 13222 : }
229 :
230 2261020 : pub async fn write_all<Buf: IoBuf + Send>(
231 2261020 : &mut self,
232 2261020 : buf: FullSlice<Buf>,
233 2261020 : ctx: &RequestContext,
234 2261020 : ) -> (FullSlice<Buf>, Result<usize, Error>) {
235 2261020 : self.inner.write_all(buf, ctx).await
236 2261020 : }
237 :
238 448 : async fn read_to_end(&mut self, buf: &mut Vec<u8>, ctx: &RequestContext) -> Result<(), Error> {
239 448 : self.inner.read_to_end(buf, ctx).await
240 448 : }
241 :
242 0 : pub(crate) async fn read_to_string(
243 0 : &mut self,
244 0 : ctx: &RequestContext,
245 0 : ) -> Result<String, anyhow::Error> {
246 0 : let mut buf = Vec::new();
247 0 : self.read_to_end(&mut buf, ctx).await?;
248 0 : Ok(String::from_utf8(buf)?)
249 0 : }
250 : }
251 :
252 : /// Indicates whether to enable fsync, fdatasync, or O_SYNC/O_DSYNC when writing
253 : /// files. Switching this off is unsafe and only used for testing on machines
254 : /// with slow drives.
255 : #[repr(u8)]
256 : pub enum SyncMode {
257 : Sync,
258 : UnsafeNoSync,
259 : }
260 :
261 : impl TryFrom<u8> for SyncMode {
262 : type Error = u8;
263 :
264 0 : fn try_from(value: u8) -> Result<Self, Self::Error> {
265 0 : Ok(match value {
266 0 : v if v == (SyncMode::Sync as u8) => SyncMode::Sync,
267 0 : v if v == (SyncMode::UnsafeNoSync as u8) => SyncMode::UnsafeNoSync,
268 0 : x => return Err(x),
269 : })
270 0 : }
271 : }
272 :
273 : ///
274 : /// A virtual file descriptor. You can use this just like std::fs::File, but internally
275 : /// the underlying file is closed if the system is low on file descriptors,
276 : /// and re-opened when it's accessed again.
277 : ///
278 : /// Like with std::fs::File, multiple threads can read/write the file concurrently,
279 : /// holding just a shared reference the same VirtualFile, using the read_at() / write_at()
280 : /// functions from the FileExt trait. But the functions from the Read/Write/Seek traits
281 : /// require a mutable reference, because they modify the "current position".
282 : ///
283 : /// Each VirtualFile has a physical file descriptor in the global OPEN_FILES array, at the
284 : /// slot that 'handle points to, if the underlying file is currently open. If it's not
285 : /// currently open, the 'handle' can still point to the slot where it was last kept. The
286 : /// 'tag' field is used to detect whether the handle still is valid or not.
287 : ///
288 : #[derive(Debug)]
289 : pub struct VirtualFileInner {
290 : /// Lazy handle to the global file descriptor cache. The slot that this points to
291 : /// might contain our File, or it may be empty, or it may contain a File that
292 : /// belongs to a different VirtualFile.
293 : handle: RwLock<SlotHandle>,
294 :
295 : /// Current file position
296 : pos: u64,
297 :
298 : /// File path and options to use to open it.
299 : ///
300 : /// Note: this only contains the options needed to re-open it. For example,
301 : /// if a new file is created, we only pass the create flag when it's initially
302 : /// opened, in the VirtualFile::create() function, and strip the flag before
303 : /// storing it here.
304 : pub path: Utf8PathBuf,
305 : open_options: OpenOptions,
306 : }
307 :
308 : #[derive(Debug, PartialEq, Clone, Copy)]
309 : struct SlotHandle {
310 : /// Index into OPEN_FILES.slots
311 : index: usize,
312 :
313 : /// Value of 'tag' in the slot. If slot's tag doesn't match, then the slot has
314 : /// been recycled and no longer contains the FD for this virtual file.
315 : tag: u64,
316 : }
317 :
318 : /// OPEN_FILES is the global array that holds the physical file descriptors that
319 : /// are currently open. Each slot in the array is protected by a separate lock,
320 : /// so that different files can be accessed independently. The lock must be held
321 : /// in write mode to replace the slot with a different file, but a read mode
322 : /// is enough to operate on the file, whether you're reading or writing to it.
323 : ///
324 : /// OPEN_FILES starts in uninitialized state, and it's initialized by
325 : /// the virtual_file::init() function. It must be called exactly once at page
326 : /// server startup.
327 : static OPEN_FILES: OnceCell<OpenFiles> = OnceCell::new();
328 :
329 : struct OpenFiles {
330 : slots: &'static [Slot],
331 :
332 : /// clock arm for the clock algorithm
333 : next: AtomicUsize,
334 : }
335 :
336 : struct Slot {
337 : inner: RwLock<SlotInner>,
338 :
339 : /// has this file been used since last clock sweep?
340 : recently_used: AtomicBool,
341 : }
342 :
343 : struct SlotInner {
344 : /// Counter that's incremented every time a different file is stored here.
345 : /// To avoid the ABA problem.
346 : tag: u64,
347 :
348 : /// the underlying file
349 : file: Option<OwnedFd>,
350 : }
351 :
352 : /// Impl of [`tokio_epoll_uring::IoBuf`] and [`tokio_epoll_uring::IoBufMut`] for [`PageWriteGuard`].
353 : struct PageWriteGuardBuf {
354 : page: PageWriteGuard<'static>,
355 : }
356 : // Safety: the [`PageWriteGuard`] gives us exclusive ownership of the page cache slot,
357 : // and the location remains stable even if [`Self`] or the [`PageWriteGuard`] is moved.
358 : // Page cache pages are zero-initialized, so, wrt uninitialized memory we're good.
359 : // (Page cache tracks separately whether the contents are valid, see `PageWriteGuard::mark_valid`.)
360 : unsafe impl tokio_epoll_uring::IoBuf for PageWriteGuardBuf {
361 253894 : fn stable_ptr(&self) -> *const u8 {
362 253894 : self.page.as_ptr()
363 253894 : }
364 476043 : fn bytes_init(&self) -> usize {
365 476043 : self.page.len()
366 476043 : }
367 190404 : fn bytes_total(&self) -> usize {
368 190404 : self.page.len()
369 190404 : }
370 : }
371 : // Safety: see above, plus: the ownership of [`PageWriteGuard`] means exclusive access,
372 : // hence it's safe to hand out the `stable_mut_ptr()`.
373 : unsafe impl tokio_epoll_uring::IoBufMut for PageWriteGuardBuf {
374 95213 : fn stable_mut_ptr(&mut self) -> *mut u8 {
375 95213 : self.page.as_mut_ptr()
376 95213 : }
377 :
378 63468 : unsafe fn set_init(&mut self, pos: usize) {
379 63468 : // There shouldn't really be any reason to call this API since bytes_init() == bytes_total().
380 63468 : assert!(pos <= self.page.len());
381 63468 : }
382 : }
383 :
384 : impl OpenFiles {
385 : /// Find a slot to use, evicting an existing file descriptor if needed.
386 : ///
387 : /// On return, we hold a lock on the slot, and its 'tag' has been updated
388 : /// recently_used has been set. It's all ready for reuse.
389 388197 : async fn find_victim_slot(&self) -> (SlotHandle, RwLockWriteGuard<SlotInner>) {
390 388197 : //
391 388197 : // Run the clock algorithm to find a slot to replace.
392 388197 : //
393 388197 : let num_slots = self.slots.len();
394 388197 : let mut retries = 0;
395 : let mut slot;
396 : let mut slot_guard;
397 : let index;
398 : loop {
399 4824188 : let next = self.next.fetch_add(1, Ordering::AcqRel) % num_slots;
400 4824188 : slot = &self.slots[next];
401 4824188 :
402 4824188 : // If the recently_used flag on this slot is set, continue the clock
403 4824188 : // sweep. Otherwise try to use this slot. If we cannot acquire the
404 4824188 : // lock, also continue the clock sweep.
405 4824188 : //
406 4824188 : // We only continue in this manner for a while, though. If we loop
407 4824188 : // through the array twice without finding a victim, just pick the
408 4824188 : // next slot and wait until we can reuse it. This way, we avoid
409 4824188 : // spinning in the extreme case that all the slots are busy with an
410 4824188 : // I/O operation.
411 4824188 : if retries < num_slots * 2 {
412 4639207 : if !slot.recently_used.swap(false, Ordering::Release) {
413 4223781 : if let Ok(guard) = slot.inner.try_write() {
414 203216 : slot_guard = guard;
415 203216 : index = next;
416 203216 : break;
417 4020565 : }
418 415426 : }
419 4435991 : retries += 1;
420 : } else {
421 184981 : slot_guard = slot.inner.write().await;
422 184981 : index = next;
423 184981 : break;
424 : }
425 : }
426 :
427 : //
428 : // We now have the victim slot locked. If it was in use previously, close the
429 : // old file.
430 : //
431 388197 : if let Some(old_file) = slot_guard.file.take() {
432 378170 : // the normal path of dropping VirtualFile uses "close", use "close-by-replace" here to
433 378170 : // distinguish the two.
434 378170 : STORAGE_IO_TIME_METRIC
435 378170 : .get(StorageIoOperation::CloseByReplace)
436 378170 : .observe_closure_duration(|| drop(old_file));
437 378170 : }
438 :
439 : // Prepare the slot for reuse and return it
440 388197 : slot_guard.tag += 1;
441 388197 : slot.recently_used.store(true, Ordering::Relaxed);
442 388197 : (
443 388197 : SlotHandle {
444 388197 : index,
445 388197 : tag: slot_guard.tag,
446 388197 : },
447 388197 : slot_guard,
448 388197 : )
449 388197 : }
450 : }
451 :
452 : /// Identify error types that should alwways terminate the process. Other
453 : /// error types may be elegible for retry.
454 8 : pub(crate) fn is_fatal_io_error(e: &std::io::Error) -> bool {
455 : use nix::errno::Errno::*;
456 8 : match e.raw_os_error().map(nix::errno::from_i32) {
457 : Some(EIO) => {
458 : // Terminate on EIO because we no longer trust the device to store
459 : // data safely, or to uphold persistence guarantees on fsync.
460 0 : true
461 : }
462 : Some(EROFS) => {
463 : // Terminate on EROFS because a filesystem is usually remounted
464 : // readonly when it has experienced some critical issue, so the same
465 : // logic as EIO applies.
466 0 : true
467 : }
468 : Some(EACCES) => {
469 : // Terminate on EACCESS because we should always have permissions
470 : // for our own data dir: if we don't, then we can't do our job and
471 : // need administrative intervention to fix permissions. Terminating
472 : // is the best way to make sure we stop cleanly rather than going
473 : // into infinite retry loops, and will make it clear to the outside
474 : // world that we need help.
475 0 : true
476 : }
477 : _ => {
478 : // Treat all other local file I/O errors are retryable. This includes:
479 : // - ENOSPC: we stay up and wait for eviction to free some space
480 : // - EINVAL, EBADF, EBADFD: this is a code bug, not a filesystem/hardware issue
481 : // - WriteZero, Interrupted: these are used internally VirtualFile
482 8 : false
483 : }
484 : }
485 8 : }
486 :
487 : /// Call this when the local filesystem gives us an error with an external
488 : /// cause: this includes EIO, EROFS, and EACCESS: all these indicate either
489 : /// bad storage or bad configuration, and we can't fix that from inside
490 : /// a running process.
491 0 : pub(crate) fn on_fatal_io_error(e: &std::io::Error, context: &str) -> ! {
492 0 : let backtrace = std::backtrace::Backtrace::force_capture();
493 0 : tracing::error!("Fatal I/O error: {e}: {context})\n{backtrace}");
494 0 : std::process::abort();
495 : }
496 :
497 : pub(crate) trait MaybeFatalIo<T> {
498 : fn maybe_fatal_err(self, context: &str) -> std::io::Result<T>;
499 : fn fatal_err(self, context: &str) -> T;
500 : }
501 :
502 : impl<T> MaybeFatalIo<T> for std::io::Result<T> {
503 : /// Terminate the process if the result is an error of a fatal type, else pass it through
504 : ///
505 : /// This is appropriate for writes, where we typically want to die on EIO/ACCES etc, but
506 : /// not on ENOSPC.
507 4232100 : fn maybe_fatal_err(self, context: &str) -> std::io::Result<T> {
508 4232100 : if let Err(e) = &self {
509 8 : if is_fatal_io_error(e) {
510 0 : on_fatal_io_error(e, context);
511 8 : }
512 4232092 : }
513 4232100 : self
514 4232100 : }
515 :
516 : /// Terminate the process on any I/O error.
517 : ///
518 : /// This is appropriate for reads on files that we know exist: they should always work.
519 4116 : fn fatal_err(self, context: &str) -> T {
520 4116 : match self {
521 4116 : Ok(v) => v,
522 0 : Err(e) => {
523 0 : on_fatal_io_error(&e, context);
524 : }
525 : }
526 4116 : }
527 : }
528 :
529 : /// Observe duration for the given storage I/O operation
530 : ///
531 : /// Unlike `observe_closure_duration`, this supports async,
532 : /// where "support" means that we measure wall clock time.
533 : macro_rules! observe_duration {
534 : ($op:expr, $($body:tt)*) => {{
535 : let instant = Instant::now();
536 : let result = $($body)*;
537 : let elapsed = instant.elapsed().as_secs_f64();
538 : STORAGE_IO_TIME_METRIC
539 : .get($op)
540 : .observe(elapsed);
541 : result
542 : }}
543 : }
544 :
545 : macro_rules! with_file {
546 : ($this:expr, $op:expr, | $ident:ident | $($body:tt)*) => {{
547 : let $ident = $this.lock_file().await?;
548 : observe_duration!($op, $($body)*)
549 : }};
550 : ($this:expr, $op:expr, | mut $ident:ident | $($body:tt)*) => {{
551 : let mut $ident = $this.lock_file().await?;
552 : observe_duration!($op, $($body)*)
553 : }};
554 : }
555 :
556 : impl VirtualFileInner {
557 : /// Open a file in read-only mode. Like File::open.
558 2112 : pub async fn open<P: AsRef<Utf8Path>>(
559 2112 : path: P,
560 2112 : ctx: &RequestContext,
561 2112 : ) -> Result<VirtualFileInner, std::io::Error> {
562 2112 : Self::open_with_options(path.as_ref(), OpenOptions::new().read(true), ctx).await
563 2112 : }
564 :
565 : /// Create a new file for writing. If the file exists, it will be truncated.
566 : /// Like File::create.
567 3030 : pub async fn create<P: AsRef<Utf8Path>>(
568 3030 : path: P,
569 3030 : ctx: &RequestContext,
570 3030 : ) -> Result<VirtualFileInner, std::io::Error> {
571 3030 : Self::open_with_options(
572 3030 : path.as_ref(),
573 3030 : OpenOptions::new().write(true).create(true).truncate(true),
574 3030 : ctx,
575 3030 : )
576 3030 : .await
577 3030 : }
578 :
579 : /// Open a file with given options.
580 : ///
581 : /// Note: If any custom flags were set in 'open_options' through OpenOptionsExt,
582 : /// they will be applied also when the file is subsequently re-opened, not only
583 : /// on the first time. Make sure that's sane!
584 12254 : pub async fn open_with_options<P: AsRef<Utf8Path>>(
585 12254 : path: P,
586 12254 : open_options: &OpenOptions,
587 12254 : _ctx: &RequestContext,
588 12254 : ) -> Result<VirtualFileInner, std::io::Error> {
589 12254 : let path = path.as_ref();
590 12254 : let (handle, mut slot_guard) = get_open_files().find_victim_slot().await;
591 :
592 : // NB: there is also StorageIoOperation::OpenAfterReplace which is for the case
593 : // where our caller doesn't get to use the returned VirtualFile before its
594 : // slot gets re-used by someone else.
595 12254 : let file = observe_duration!(StorageIoOperation::Open, {
596 12254 : open_options.open(path.as_std_path()).await?
597 : });
598 :
599 : // Strip all options other than read and write.
600 : //
601 : // It would perhaps be nicer to check just for the read and write flags
602 : // explicitly, but OpenOptions doesn't contain any functions to read flags,
603 : // only to set them.
604 12254 : let mut reopen_options = open_options.clone();
605 12254 : reopen_options.create(false);
606 12254 : reopen_options.create_new(false);
607 12254 : reopen_options.truncate(false);
608 12254 :
609 12254 : let vfile = VirtualFileInner {
610 12254 : handle: RwLock::new(handle),
611 12254 : pos: 0,
612 12254 : path: path.to_owned(),
613 12254 : open_options: reopen_options,
614 12254 : };
615 12254 :
616 12254 : // TODO: Under pressure, it's likely the slot will get re-used and
617 12254 : // the underlying file closed before they get around to using it.
618 12254 : // => https://github.com/neondatabase/neon/issues/6065
619 12254 : slot_guard.file.replace(file);
620 12254 :
621 12254 : Ok(vfile)
622 12254 : }
623 :
624 : /// Async version of [`::utils::crashsafe::overwrite`].
625 : ///
626 : /// # NB:
627 : ///
628 : /// Doesn't actually use the [`VirtualFile`] file descriptor cache, but,
629 : /// it did at an earlier time.
630 : /// And it will use this module's [`io_engine`] in the near future, so, leaving it here.
631 56 : pub async fn crashsafe_overwrite<B: BoundedBuf<Buf = Buf> + Send, Buf: IoBuf + Send>(
632 56 : final_path: Utf8PathBuf,
633 56 : tmp_path: Utf8PathBuf,
634 56 : content: B,
635 56 : ) -> std::io::Result<()> {
636 56 : // TODO: use tokio_epoll_uring if configured as `io_engine`.
637 56 : // See https://github.com/neondatabase/neon/issues/6663
638 56 :
639 56 : tokio::task::spawn_blocking(move || {
640 56 : let slice_storage;
641 56 : let content_len = content.bytes_init();
642 56 : let content = if content.bytes_init() > 0 {
643 56 : slice_storage = Some(content.slice(0..content_len));
644 56 : slice_storage.as_deref().expect("just set it to Some()")
645 : } else {
646 0 : &[]
647 : };
648 56 : utils::crashsafe::overwrite(&final_path, &tmp_path, content)
649 56 : .maybe_fatal_err("crashsafe_overwrite")
650 56 : })
651 56 : .await
652 56 : .expect("blocking task is never aborted")
653 56 : }
654 :
655 : /// Call File::sync_all() on the underlying File.
656 5650 : pub async fn sync_all(&self) -> Result<(), Error> {
657 5650 : with_file!(self, StorageIoOperation::Fsync, |file_guard| {
658 5650 : let (_file_guard, res) = io_engine::get().sync_all(file_guard).await;
659 5650 : res.maybe_fatal_err("sync_all")
660 : })
661 5650 : }
662 :
663 : /// Call File::sync_data() on the underlying File.
664 0 : pub async fn sync_data(&self) -> Result<(), Error> {
665 0 : with_file!(self, StorageIoOperation::Fsync, |file_guard| {
666 0 : let (_file_guard, res) = io_engine::get().sync_data(file_guard).await;
667 0 : res.maybe_fatal_err("sync_data")
668 : })
669 0 : }
670 :
671 3620 : pub async fn metadata(&self) -> Result<Metadata, Error> {
672 3620 : with_file!(self, StorageIoOperation::Metadata, |file_guard| {
673 3620 : let (_file_guard, res) = io_engine::get().metadata(file_guard).await;
674 3620 : res
675 : })
676 3620 : }
677 :
678 : /// Helper function internal to `VirtualFile` that looks up the underlying File,
679 : /// opens it and evicts some other File if necessary. The passed parameter is
680 : /// assumed to be a function available for the physical `File`.
681 : ///
682 : /// We are doing it via a macro as Rust doesn't support async closures that
683 : /// take on parameters with lifetimes.
684 3251084 : async fn lock_file(&self) -> Result<FileGuard, Error> {
685 3251084 : let open_files = get_open_files();
686 :
687 375943 : let mut handle_guard = {
688 : // Read the cached slot handle, and see if the slot that it points to still
689 : // contains our File.
690 : //
691 : // We only need to hold the handle lock while we read the current handle. If
692 : // another thread closes the file and recycles the slot for a different file,
693 : // we will notice that the handle we read is no longer valid and retry.
694 3251084 : let mut handle = *self.handle.read().await;
695 : loop {
696 : // Check if the slot contains our File
697 : {
698 3449319 : let slot = &open_files.slots[handle.index];
699 3449319 : let slot_guard = slot.inner.read().await;
700 3449319 : if slot_guard.tag == handle.tag && slot_guard.file.is_some() {
701 : // Found a cached file descriptor.
702 2875141 : slot.recently_used.store(true, Ordering::Relaxed);
703 2875141 : return Ok(FileGuard { slot_guard });
704 574178 : }
705 : }
706 :
707 : // The slot didn't contain our File. We will have to open it ourselves,
708 : // but before that, grab a write lock on handle in the VirtualFile, so
709 : // that no other thread will try to concurrently open the same file.
710 574178 : let handle_guard = self.handle.write().await;
711 :
712 : // If another thread changed the handle while we were not holding the lock,
713 : // then the handle might now be valid again. Loop back to retry.
714 574178 : if *handle_guard != handle {
715 198235 : handle = *handle_guard;
716 198235 : continue;
717 375943 : }
718 375943 : break handle_guard;
719 : }
720 : };
721 :
722 : // We need to open the file ourselves. The handle in the VirtualFile is
723 : // now locked in write-mode. Find a free slot to put it in.
724 375943 : let (handle, mut slot_guard) = open_files.find_victim_slot().await;
725 :
726 : // Re-open the physical file.
727 : // NB: we use StorageIoOperation::OpenAferReplace for this to distinguish this
728 : // case from StorageIoOperation::Open. This helps with identifying thrashing
729 : // of the virtual file descriptor cache.
730 375943 : let file = observe_duration!(StorageIoOperation::OpenAfterReplace, {
731 375943 : self.open_options.open(self.path.as_std_path()).await?
732 : });
733 :
734 : // Store the File in the slot and update the handle in the VirtualFile
735 : // to point to it.
736 375943 : slot_guard.file.replace(file);
737 375943 :
738 375943 : *handle_guard = handle;
739 375943 :
740 375943 : Ok(FileGuard {
741 375943 : slot_guard: slot_guard.downgrade(),
742 375943 : })
743 3251084 : }
744 :
745 524 : pub fn remove(self) {
746 524 : let path = self.path.clone();
747 524 : drop(self);
748 524 : std::fs::remove_file(path).expect("failed to remove the virtual file");
749 524 : }
750 :
751 11408 : pub async fn seek(&mut self, pos: SeekFrom) -> Result<u64, Error> {
752 11408 : match pos {
753 11388 : SeekFrom::Start(offset) => {
754 11388 : self.pos = offset;
755 11388 : }
756 8 : SeekFrom::End(offset) => {
757 8 : self.pos = with_file!(self, StorageIoOperation::Seek, |mut file_guard| file_guard
758 8 : .with_std_file_mut(|std_file| std_file.seek(SeekFrom::End(offset))))?
759 : }
760 12 : SeekFrom::Current(offset) => {
761 12 : let pos = self.pos as i128 + offset as i128;
762 12 : if pos < 0 {
763 4 : return Err(Error::new(
764 4 : ErrorKind::InvalidInput,
765 4 : "offset would be negative",
766 4 : ));
767 8 : }
768 8 : if pos > u64::MAX as i128 {
769 0 : return Err(Error::new(ErrorKind::InvalidInput, "offset overflow"));
770 8 : }
771 8 : self.pos = pos as u64;
772 : }
773 : }
774 11400 : Ok(self.pos)
775 11408 : }
776 :
777 : /// Read the file contents in range `offset..(offset + slice.bytes_total())` into `slice[0..slice.bytes_total()]`.
778 : ///
779 : /// The returned `Slice<Buf>` is equivalent to the input `slice`, i.e., it's the same view into the same buffer.
780 966752 : pub async fn read_exact_at<Buf>(
781 966752 : &self,
782 966752 : slice: Slice<Buf>,
783 966752 : offset: u64,
784 966752 : ctx: &RequestContext,
785 966752 : ) -> Result<Slice<Buf>, Error>
786 966752 : where
787 966752 : Buf: IoBufAlignedMut + Send,
788 966752 : {
789 966752 : let assert_we_return_original_bounds = if cfg!(debug_assertions) {
790 966752 : Some((slice.stable_ptr() as usize, slice.bytes_total()))
791 : } else {
792 0 : None
793 : };
794 :
795 966752 : let original_bounds = slice.bounds();
796 966752 : let (buf, res) =
797 966752 : read_exact_at_impl(slice, offset, |buf, offset| self.read_at(buf, offset, ctx)).await;
798 966752 : let res = res.map(|_| buf.slice(original_bounds));
799 :
800 966752 : if let Some(original_bounds) = assert_we_return_original_bounds {
801 966752 : if let Ok(slice) = &res {
802 966752 : let returned_bounds = (slice.stable_ptr() as usize, slice.bytes_total());
803 966752 : assert_eq!(original_bounds, returned_bounds);
804 0 : }
805 0 : }
806 :
807 966752 : res
808 966752 : }
809 :
810 : /// Like [`Self::read_exact_at`] but for [`PageWriteGuard`].
811 63468 : pub async fn read_exact_at_page(
812 63468 : &self,
813 63468 : page: PageWriteGuard<'static>,
814 63468 : offset: u64,
815 63468 : ctx: &RequestContext,
816 63468 : ) -> Result<PageWriteGuard<'static>, Error> {
817 63468 : let buf = PageWriteGuardBuf { page }.slice_full();
818 63468 : debug_assert_eq!(buf.bytes_total(), PAGE_SZ);
819 63468 : self.read_exact_at(buf, offset, ctx)
820 63468 : .await
821 63468 : .map(|slice| slice.into_inner().page)
822 63468 : }
823 :
824 : // Copied from https://doc.rust-lang.org/1.72.0/src/std/os/unix/fs.rs.html#219-235
825 13222 : pub async fn write_all_at<Buf: IoBuf + Send>(
826 13222 : &self,
827 13222 : buf: FullSlice<Buf>,
828 13222 : mut offset: u64,
829 13222 : ctx: &RequestContext,
830 13222 : ) -> (FullSlice<Buf>, Result<(), Error>) {
831 13222 : let buf = buf.into_raw_slice();
832 13222 : let bounds = buf.bounds();
833 13222 : let restore =
834 13222 : |buf: Slice<_>| FullSlice::must_new(Slice::from_buf_bounds(buf.into_inner(), bounds));
835 13222 : let mut buf = buf;
836 26444 : while !buf.is_empty() {
837 13222 : let (tmp, res) = self.write_at(FullSlice::must_new(buf), offset, ctx).await;
838 13222 : buf = tmp.into_raw_slice();
839 0 : match res {
840 : Ok(0) => {
841 0 : return (
842 0 : restore(buf),
843 0 : Err(Error::new(
844 0 : std::io::ErrorKind::WriteZero,
845 0 : "failed to write whole buffer",
846 0 : )),
847 0 : );
848 : }
849 13222 : Ok(n) => {
850 13222 : buf = buf.slice(n..);
851 13222 : offset += n as u64;
852 13222 : }
853 0 : Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
854 0 : Err(e) => return (restore(buf), Err(e)),
855 : }
856 : }
857 13222 : (restore(buf), Ok(()))
858 13222 : }
859 :
860 : /// Writes `buf` to the file at the current offset.
861 : ///
862 : /// Panics if there is an uninitialized range in `buf`, as that is most likely a bug in the caller.
863 2261020 : pub async fn write_all<Buf: IoBuf + Send>(
864 2261020 : &mut self,
865 2261020 : buf: FullSlice<Buf>,
866 2261020 : ctx: &RequestContext,
867 2261020 : ) -> (FullSlice<Buf>, Result<usize, Error>) {
868 2261020 : let buf = buf.into_raw_slice();
869 2261020 : let bounds = buf.bounds();
870 2261020 : let restore =
871 2261020 : |buf: Slice<_>| FullSlice::must_new(Slice::from_buf_bounds(buf.into_inner(), bounds));
872 2261020 : let nbytes = buf.len();
873 2261020 : let mut buf = buf;
874 4521960 : while !buf.is_empty() {
875 2260944 : let (tmp, res) = self.write(FullSlice::must_new(buf), ctx).await;
876 2260944 : buf = tmp.into_raw_slice();
877 4 : match res {
878 : Ok(0) => {
879 0 : return (
880 0 : restore(buf),
881 0 : Err(Error::new(
882 0 : std::io::ErrorKind::WriteZero,
883 0 : "failed to write whole buffer",
884 0 : )),
885 0 : );
886 : }
887 2260940 : Ok(n) => {
888 2260940 : buf = buf.slice(n..);
889 2260940 : }
890 4 : Err(ref e) if e.kind() == std::io::ErrorKind::Interrupted => {}
891 4 : Err(e) => return (restore(buf), Err(e)),
892 : }
893 : }
894 2261016 : (restore(buf), Ok(nbytes))
895 2261020 : }
896 :
897 2260944 : async fn write<B: IoBuf + Send>(
898 2260944 : &mut self,
899 2260944 : buf: FullSlice<B>,
900 2260944 : ctx: &RequestContext,
901 2260944 : ) -> (FullSlice<B>, Result<usize, std::io::Error>) {
902 2260944 : let pos = self.pos;
903 2260944 : let (buf, res) = self.write_at(buf, pos, ctx).await;
904 2260944 : let n = match res {
905 2260940 : Ok(n) => n,
906 4 : Err(e) => return (buf, Err(e)),
907 : };
908 2260940 : self.pos += n as u64;
909 2260940 : (buf, Ok(n))
910 2260944 : }
911 :
912 967640 : pub(crate) async fn read_at<Buf>(
913 967640 : &self,
914 967640 : buf: tokio_epoll_uring::Slice<Buf>,
915 967640 : offset: u64,
916 967640 : ctx: &RequestContext,
917 967640 : ) -> (tokio_epoll_uring::Slice<Buf>, Result<usize, Error>)
918 967640 : where
919 967640 : Buf: tokio_epoll_uring::IoBufMut + Send,
920 967640 : {
921 967640 : let file_guard = match self
922 967640 : .lock_file()
923 967640 : .await
924 967640 : .maybe_fatal_err("lock_file inside VirtualFileInner::read_at")
925 : {
926 967640 : Ok(file_guard) => file_guard,
927 0 : Err(e) => return (buf, Err(e)),
928 : };
929 :
930 967640 : observe_duration!(StorageIoOperation::Read, {
931 967640 : let ((_file_guard, buf), res) = io_engine::get().read_at(file_guard, offset, buf).await;
932 967640 : let res = res.maybe_fatal_err("io_engine read_at inside VirtualFileInner::read_at");
933 967640 : if let Ok(size) = res {
934 967636 : ctx.io_size_metrics().read.add(size.into_u64());
935 967636 : }
936 967640 : (buf, res)
937 : })
938 967640 : }
939 :
940 : /// The function aborts the process if the error is fatal.
941 2274166 : async fn write_at<B: IoBuf + Send>(
942 2274166 : &self,
943 2274166 : buf: FullSlice<B>,
944 2274166 : offset: u64,
945 2274166 : ctx: &RequestContext,
946 2274166 : ) -> (FullSlice<B>, Result<usize, Error>) {
947 2274166 : let (slice, result) = self.write_at_inner(buf, offset, ctx).await;
948 2274166 : let result = result.maybe_fatal_err("write_at");
949 2274166 : (slice, result)
950 2274166 : }
951 :
952 2274166 : async fn write_at_inner<B: IoBuf + Send>(
953 2274166 : &self,
954 2274166 : buf: FullSlice<B>,
955 2274166 : offset: u64,
956 2274166 : ctx: &RequestContext,
957 2274166 : ) -> (FullSlice<B>, Result<usize, Error>) {
958 2274166 : let file_guard = match self.lock_file().await {
959 2274166 : Ok(file_guard) => file_guard,
960 0 : Err(e) => return (buf, Err(e)),
961 : };
962 2274166 : observe_duration!(StorageIoOperation::Write, {
963 2274166 : let ((_file_guard, buf), result) =
964 2274166 : io_engine::get().write_at(file_guard, offset, buf).await;
965 2274166 : if let Ok(size) = result {
966 2274162 : ctx.io_size_metrics().write.add(size.into_u64());
967 2274162 : }
968 2274166 : (buf, result)
969 : })
970 2274166 : }
971 :
972 448 : async fn read_to_end(&mut self, buf: &mut Vec<u8>, ctx: &RequestContext) -> Result<(), Error> {
973 448 : let mut tmp = vec![0; 128];
974 : loop {
975 888 : let slice = tmp.slice(..128);
976 888 : let (slice, res) = self.read_at(slice, self.pos, ctx).await;
977 4 : match res {
978 444 : Ok(0) => return Ok(()),
979 440 : Ok(n) => {
980 440 : self.pos += n as u64;
981 440 : buf.extend_from_slice(&slice[..n]);
982 440 : }
983 4 : Err(ref e) if e.kind() == std::io::ErrorKind::Interrupted => {}
984 4 : Err(e) => return Err(e),
985 : }
986 440 : tmp = slice.into_inner();
987 : }
988 448 : }
989 : }
990 :
991 : // Adapted from https://doc.rust-lang.org/1.72.0/src/std/os/unix/fs.rs.html#117-135
992 966768 : pub async fn read_exact_at_impl<Buf, F, Fut>(
993 966768 : mut buf: tokio_epoll_uring::Slice<Buf>,
994 966768 : mut offset: u64,
995 966768 : mut read_at: F,
996 966768 : ) -> (Buf, std::io::Result<()>)
997 966768 : where
998 966768 : Buf: IoBufMut + Send,
999 966768 : F: FnMut(tokio_epoll_uring::Slice<Buf>, u64) -> Fut,
1000 966768 : Fut: std::future::Future<Output = (tokio_epoll_uring::Slice<Buf>, std::io::Result<usize>)>,
1001 966768 : {
1002 1933540 : while buf.bytes_total() != 0 {
1003 : let res;
1004 966776 : (buf, res) = read_at(buf, offset).await;
1005 0 : match res {
1006 4 : Ok(0) => break,
1007 966772 : Ok(n) => {
1008 966772 : buf = buf.slice(n..);
1009 966772 : offset += n as u64;
1010 966772 : }
1011 0 : Err(ref e) if e.kind() == std::io::ErrorKind::Interrupted => {}
1012 0 : Err(e) => return (buf.into_inner(), Err(e)),
1013 : }
1014 : }
1015 : // NB: don't use `buf.is_empty()` here; it is from the
1016 : // `impl Deref for Slice { Target = [u8] }`; the &[u8]
1017 : // returned by it only covers the initialized portion of `buf`.
1018 : // Whereas we're interested in ensuring that we filled the entire
1019 : // buffer that the user passed in.
1020 966768 : if buf.bytes_total() != 0 {
1021 4 : (
1022 4 : buf.into_inner(),
1023 4 : Err(std::io::Error::new(
1024 4 : std::io::ErrorKind::UnexpectedEof,
1025 4 : "failed to fill whole buffer",
1026 4 : )),
1027 4 : )
1028 : } else {
1029 966764 : assert_eq!(buf.len(), buf.bytes_total());
1030 966764 : (buf.into_inner(), Ok(()))
1031 : }
1032 966768 : }
1033 :
1034 : #[cfg(test)]
1035 : mod test_read_exact_at_impl {
1036 :
1037 : use std::collections::VecDeque;
1038 : use std::sync::Arc;
1039 :
1040 : use tokio_epoll_uring::{BoundedBuf, BoundedBufMut};
1041 :
1042 : use super::read_exact_at_impl;
1043 :
1044 : struct Expectation {
1045 : offset: u64,
1046 : bytes_total: usize,
1047 : result: std::io::Result<Vec<u8>>,
1048 : }
1049 : struct MockReadAt {
1050 : expectations: VecDeque<Expectation>,
1051 : }
1052 :
1053 : impl MockReadAt {
1054 24 : async fn read_at(
1055 24 : &mut self,
1056 24 : mut buf: tokio_epoll_uring::Slice<Vec<u8>>,
1057 24 : offset: u64,
1058 24 : ) -> (tokio_epoll_uring::Slice<Vec<u8>>, std::io::Result<usize>) {
1059 24 : let exp = self
1060 24 : .expectations
1061 24 : .pop_front()
1062 24 : .expect("read_at called but we have no expectations left");
1063 24 : assert_eq!(exp.offset, offset);
1064 24 : assert_eq!(exp.bytes_total, buf.bytes_total());
1065 24 : match exp.result {
1066 24 : Ok(bytes) => {
1067 24 : assert!(bytes.len() <= buf.bytes_total());
1068 24 : buf.put_slice(&bytes);
1069 24 : (buf, Ok(bytes.len()))
1070 : }
1071 0 : Err(e) => (buf, Err(e)),
1072 : }
1073 24 : }
1074 : }
1075 :
1076 : impl Drop for MockReadAt {
1077 16 : fn drop(&mut self) {
1078 16 : assert_eq!(self.expectations.len(), 0);
1079 16 : }
1080 : }
1081 :
1082 : #[tokio::test]
1083 4 : async fn test_basic() {
1084 4 : let buf = Vec::with_capacity(5).slice_full();
1085 4 : let mock_read_at = Arc::new(tokio::sync::Mutex::new(MockReadAt {
1086 4 : expectations: VecDeque::from(vec![Expectation {
1087 4 : offset: 0,
1088 4 : bytes_total: 5,
1089 4 : result: Ok(vec![b'a', b'b', b'c', b'd', b'e']),
1090 4 : }]),
1091 4 : }));
1092 4 : let (buf, res) = read_exact_at_impl(buf, 0, |buf, offset| {
1093 4 : let mock_read_at = Arc::clone(&mock_read_at);
1094 4 : async move { mock_read_at.lock().await.read_at(buf, offset).await }
1095 4 : })
1096 4 : .await;
1097 4 : assert!(res.is_ok());
1098 4 : assert_eq!(buf, vec![b'a', b'b', b'c', b'd', b'e']);
1099 4 : }
1100 :
1101 : #[tokio::test]
1102 4 : async fn test_empty_buf_issues_no_syscall() {
1103 4 : let buf = Vec::new().slice_full();
1104 4 : let mock_read_at = Arc::new(tokio::sync::Mutex::new(MockReadAt {
1105 4 : expectations: VecDeque::new(),
1106 4 : }));
1107 4 : let (_buf, res) = read_exact_at_impl(buf, 0, |buf, offset| {
1108 0 : let mock_read_at = Arc::clone(&mock_read_at);
1109 4 : async move { mock_read_at.lock().await.read_at(buf, offset).await }
1110 4 : })
1111 4 : .await;
1112 4 : assert!(res.is_ok());
1113 4 : }
1114 :
1115 : #[tokio::test]
1116 4 : async fn test_two_read_at_calls_needed_until_buf_filled() {
1117 4 : let buf = Vec::with_capacity(4).slice_full();
1118 4 : let mock_read_at = Arc::new(tokio::sync::Mutex::new(MockReadAt {
1119 4 : expectations: VecDeque::from(vec![
1120 4 : Expectation {
1121 4 : offset: 0,
1122 4 : bytes_total: 4,
1123 4 : result: Ok(vec![b'a', b'b']),
1124 4 : },
1125 4 : Expectation {
1126 4 : offset: 2,
1127 4 : bytes_total: 2,
1128 4 : result: Ok(vec![b'c', b'd']),
1129 4 : },
1130 4 : ]),
1131 4 : }));
1132 8 : let (buf, res) = read_exact_at_impl(buf, 0, |buf, offset| {
1133 8 : let mock_read_at = Arc::clone(&mock_read_at);
1134 8 : async move { mock_read_at.lock().await.read_at(buf, offset).await }
1135 8 : })
1136 4 : .await;
1137 4 : assert!(res.is_ok());
1138 4 : assert_eq!(buf, vec![b'a', b'b', b'c', b'd']);
1139 4 : }
1140 :
1141 : #[tokio::test]
1142 4 : async fn test_eof_before_buffer_full() {
1143 4 : let buf = Vec::with_capacity(3).slice_full();
1144 4 : let mock_read_at = Arc::new(tokio::sync::Mutex::new(MockReadAt {
1145 4 : expectations: VecDeque::from(vec![
1146 4 : Expectation {
1147 4 : offset: 0,
1148 4 : bytes_total: 3,
1149 4 : result: Ok(vec![b'a']),
1150 4 : },
1151 4 : Expectation {
1152 4 : offset: 1,
1153 4 : bytes_total: 2,
1154 4 : result: Ok(vec![b'b']),
1155 4 : },
1156 4 : Expectation {
1157 4 : offset: 2,
1158 4 : bytes_total: 1,
1159 4 : result: Ok(vec![]),
1160 4 : },
1161 4 : ]),
1162 4 : }));
1163 12 : let (_buf, res) = read_exact_at_impl(buf, 0, |buf, offset| {
1164 12 : let mock_read_at = Arc::clone(&mock_read_at);
1165 12 : async move { mock_read_at.lock().await.read_at(buf, offset).await }
1166 12 : })
1167 4 : .await;
1168 4 : let Err(err) = res else {
1169 4 : panic!("should return an error");
1170 4 : };
1171 4 : assert_eq!(err.kind(), std::io::ErrorKind::UnexpectedEof);
1172 4 : assert_eq!(format!("{err}"), "failed to fill whole buffer");
1173 4 : // buffer contents on error are unspecified
1174 4 : }
1175 : }
1176 :
1177 : struct FileGuard {
1178 : slot_guard: RwLockReadGuard<'static, SlotInner>,
1179 : }
1180 :
1181 : impl AsRef<OwnedFd> for FileGuard {
1182 3251084 : fn as_ref(&self) -> &OwnedFd {
1183 3251084 : // This unwrap is safe because we only create `FileGuard`s
1184 3251084 : // if we know that the file is Some.
1185 3251084 : self.slot_guard.file.as_ref().unwrap()
1186 3251084 : }
1187 : }
1188 :
1189 : impl FileGuard {
1190 : /// Soft deprecation: we'll move VirtualFile to async APIs and remove this function eventually.
1191 1625510 : fn with_std_file<F, R>(&self, with: F) -> R
1192 1625510 : where
1193 1625510 : F: FnOnce(&File) -> R,
1194 1625510 : {
1195 1625510 : // SAFETY:
1196 1625510 : // - lifetime of the fd: `file` doesn't outlive the OwnedFd stored in `self`.
1197 1625510 : // - `&` usage below: `self` is `&`, hence Rust typesystem guarantees there are is no `&mut`
1198 1625510 : let file = unsafe { File::from_raw_fd(self.as_ref().as_raw_fd()) };
1199 1625510 : let res = with(&file);
1200 1625510 : let _ = file.into_raw_fd();
1201 1625510 : res
1202 1625510 : }
1203 : /// Soft deprecation: we'll move VirtualFile to async APIs and remove this function eventually.
1204 8 : fn with_std_file_mut<F, R>(&mut self, with: F) -> R
1205 8 : where
1206 8 : F: FnOnce(&mut File) -> R,
1207 8 : {
1208 8 : // SAFETY:
1209 8 : // - lifetime of the fd: `file` doesn't outlive the OwnedFd stored in `self`.
1210 8 : // - &mut usage below: `self` is `&mut`, hence this call is the only task/thread that has control over the underlying fd
1211 8 : let mut file = unsafe { File::from_raw_fd(self.as_ref().as_raw_fd()) };
1212 8 : let res = with(&mut file);
1213 8 : let _ = file.into_raw_fd();
1214 8 : res
1215 8 : }
1216 : }
1217 :
1218 : impl tokio_epoll_uring::IoFd for FileGuard {
1219 1625566 : unsafe fn as_fd(&self) -> RawFd {
1220 1625566 : let owned_fd: &OwnedFd = self.as_ref();
1221 1625566 : owned_fd.as_raw_fd()
1222 1625566 : }
1223 : }
1224 :
1225 : #[cfg(test)]
1226 : impl VirtualFile {
1227 41832 : pub(crate) async fn read_blk(
1228 41832 : &self,
1229 41832 : blknum: u32,
1230 41832 : ctx: &RequestContext,
1231 41832 : ) -> Result<crate::tenant::block_io::BlockLease<'_>, std::io::Error> {
1232 41832 : self.inner.read_blk(blknum, ctx).await
1233 41832 : }
1234 : }
1235 :
1236 : #[cfg(test)]
1237 : impl VirtualFileInner {
1238 41832 : pub(crate) async fn read_blk(
1239 41832 : &self,
1240 41832 : blknum: u32,
1241 41832 : ctx: &RequestContext,
1242 41832 : ) -> Result<crate::tenant::block_io::BlockLease<'_>, std::io::Error> {
1243 : use crate::page_cache::PAGE_SZ;
1244 41832 : let slice = IoBufferMut::with_capacity(PAGE_SZ).slice_full();
1245 41832 : assert_eq!(slice.bytes_total(), PAGE_SZ);
1246 41832 : let slice = self
1247 41832 : .read_exact_at(slice, blknum as u64 * (PAGE_SZ as u64), ctx)
1248 41832 : .await?;
1249 41832 : Ok(crate::tenant::block_io::BlockLease::IoBufferMut(
1250 41832 : slice.into_inner(),
1251 41832 : ))
1252 41832 : }
1253 : }
1254 :
1255 : impl Drop for VirtualFileInner {
1256 : /// If a VirtualFile is dropped, close the underlying file if it was open.
1257 10630 : fn drop(&mut self) {
1258 10630 : let handle = self.handle.get_mut();
1259 :
1260 10630 : fn clean_slot(slot: &Slot, mut slot_guard: RwLockWriteGuard<'_, SlotInner>, tag: u64) {
1261 10630 : if slot_guard.tag == tag {
1262 9472 : slot.recently_used.store(false, Ordering::Relaxed);
1263 : // there is also operation "close-by-replace" for closes done on eviction for
1264 : // comparison.
1265 9472 : if let Some(fd) = slot_guard.file.take() {
1266 9472 : STORAGE_IO_TIME_METRIC
1267 9472 : .get(StorageIoOperation::Close)
1268 9472 : .observe_closure_duration(|| drop(fd));
1269 9472 : }
1270 1158 : }
1271 10630 : }
1272 :
1273 : // We don't have async drop so we cannot directly await the lock here.
1274 : // Instead, first do a best-effort attempt at closing the underlying
1275 : // file descriptor by using `try_write`, and if that fails, spawn
1276 : // a tokio task to do it asynchronously: we just want it to be
1277 : // cleaned up eventually.
1278 : // Most of the time, the `try_lock` should succeed though,
1279 : // as we have `&mut self` access. In other words, if the slot
1280 : // is still occupied by our file, there should be no access from
1281 : // other I/O operations; the only other possible place to lock
1282 : // the slot is the lock algorithm looking for free slots.
1283 10630 : let slot = &get_open_files().slots[handle.index];
1284 10630 : if let Ok(slot_guard) = slot.inner.try_write() {
1285 10630 : clean_slot(slot, slot_guard, handle.tag);
1286 10630 : } else {
1287 0 : let tag = handle.tag;
1288 0 : tokio::spawn(async move {
1289 0 : let slot_guard = slot.inner.write().await;
1290 0 : clean_slot(slot, slot_guard, tag);
1291 0 : });
1292 0 : };
1293 10630 : }
1294 : }
1295 :
1296 : impl OwnedAsyncWriter for VirtualFile {
1297 13214 : async fn write_all_at<Buf: IoBufAligned + Send>(
1298 13214 : &self,
1299 13214 : buf: FullSlice<Buf>,
1300 13214 : offset: u64,
1301 13214 : ctx: &RequestContext,
1302 13214 : ) -> (FullSlice<Buf>, std::io::Result<()>) {
1303 13214 : VirtualFile::write_all_at(self, buf, offset, ctx).await
1304 13214 : }
1305 : }
1306 :
1307 : impl OpenFiles {
1308 472 : fn new(num_slots: usize) -> OpenFiles {
1309 472 : let mut slots = Box::new(Vec::with_capacity(num_slots));
1310 4720 : for _ in 0..num_slots {
1311 4720 : let slot = Slot {
1312 4720 : recently_used: AtomicBool::new(false),
1313 4720 : inner: RwLock::new(SlotInner { tag: 0, file: None }),
1314 4720 : };
1315 4720 : slots.push(slot);
1316 4720 : }
1317 :
1318 472 : OpenFiles {
1319 472 : next: AtomicUsize::new(0),
1320 472 : slots: Box::leak(slots),
1321 472 : }
1322 472 : }
1323 : }
1324 :
1325 : ///
1326 : /// Initialize the virtual file module. This must be called once at page
1327 : /// server startup.
1328 : ///
1329 : #[cfg(not(test))]
1330 0 : pub fn init(num_slots: usize, engine: IoEngineKind, mode: IoMode, sync_mode: SyncMode) {
1331 0 : if OPEN_FILES.set(OpenFiles::new(num_slots)).is_err() {
1332 0 : panic!("virtual_file::init called twice");
1333 0 : }
1334 0 : set_io_mode(mode);
1335 0 : io_engine::init(engine);
1336 0 : SYNC_MODE.store(sync_mode as u8, std::sync::atomic::Ordering::Relaxed);
1337 0 : crate::metrics::virtual_file_descriptor_cache::SIZE_MAX.set(num_slots as u64);
1338 0 : }
1339 :
1340 : const TEST_MAX_FILE_DESCRIPTORS: usize = 10;
1341 :
1342 : // Get a handle to the global slots array.
1343 3273968 : fn get_open_files() -> &'static OpenFiles {
1344 3273968 : //
1345 3273968 : // In unit tests, page server startup doesn't happen and no one calls
1346 3273968 : // virtual_file::init(). Initialize it here, with a small array.
1347 3273968 : //
1348 3273968 : // This applies to the virtual file tests below, but all other unit
1349 3273968 : // tests too, so the virtual file facility is always usable in
1350 3273968 : // unit tests.
1351 3273968 : //
1352 3273968 : if cfg!(test) {
1353 3273968 : OPEN_FILES.get_or_init(|| OpenFiles::new(TEST_MAX_FILE_DESCRIPTORS))
1354 : } else {
1355 0 : OPEN_FILES.get().expect("virtual_file::init not called yet")
1356 : }
1357 3273968 : }
1358 :
1359 : /// Gets the io buffer alignment.
1360 0 : pub(crate) const fn get_io_buffer_alignment() -> usize {
1361 0 : DEFAULT_IO_BUFFER_ALIGNMENT
1362 0 : }
1363 :
1364 : pub(crate) type IoBufferMut = AlignedBufferMut<ConstAlign<{ get_io_buffer_alignment() }>>;
1365 : pub(crate) type IoBuffer = AlignedBuffer<ConstAlign<{ get_io_buffer_alignment() }>>;
1366 : pub(crate) type IoPageSlice<'a> =
1367 : AlignedSlice<'a, PAGE_SZ, ConstAlign<{ get_io_buffer_alignment() }>>;
1368 :
1369 : static IO_MODE: AtomicU8 = AtomicU8::new(IoMode::preferred() as u8);
1370 :
1371 0 : pub(crate) fn set_io_mode(mode: IoMode) {
1372 0 : IO_MODE.store(mode as u8, std::sync::atomic::Ordering::Relaxed);
1373 0 : }
1374 :
1375 5096 : pub(crate) fn get_io_mode() -> IoMode {
1376 5096 : IoMode::try_from(IO_MODE.load(Ordering::Relaxed)).unwrap()
1377 5096 : }
1378 :
1379 : static SYNC_MODE: AtomicU8 = AtomicU8::new(SyncMode::Sync as u8);
1380 :
1381 : #[cfg(test)]
1382 : mod tests {
1383 : use std::io::Write;
1384 : use std::os::unix::fs::FileExt;
1385 : use std::sync::Arc;
1386 :
1387 : use owned_buffers_io::io_buf_ext::IoBufExt;
1388 : use owned_buffers_io::slice::SliceMutExt;
1389 : use rand::seq::SliceRandom;
1390 : use rand::{Rng, thread_rng};
1391 :
1392 : use super::*;
1393 : use crate::context::DownloadBehavior;
1394 : use crate::task_mgr::TaskKind;
1395 :
1396 : enum MaybeVirtualFile {
1397 : VirtualFile(VirtualFile),
1398 : File(File),
1399 : }
1400 :
1401 : impl From<VirtualFile> for MaybeVirtualFile {
1402 12 : fn from(vf: VirtualFile) -> Self {
1403 12 : MaybeVirtualFile::VirtualFile(vf)
1404 12 : }
1405 : }
1406 :
1407 : impl MaybeVirtualFile {
1408 808 : async fn read_exact_at(
1409 808 : &self,
1410 808 : mut slice: tokio_epoll_uring::Slice<IoBufferMut>,
1411 808 : offset: u64,
1412 808 : ctx: &RequestContext,
1413 808 : ) -> Result<tokio_epoll_uring::Slice<IoBufferMut>, Error> {
1414 808 : match self {
1415 404 : MaybeVirtualFile::VirtualFile(file) => file.read_exact_at(slice, offset, ctx).await,
1416 404 : MaybeVirtualFile::File(file) => {
1417 404 : let rust_slice: &mut [u8] = slice.as_mut_rust_slice_full_zeroed();
1418 404 : file.read_exact_at(rust_slice, offset).map(|()| slice)
1419 : }
1420 : }
1421 808 : }
1422 16 : async fn write_all_at<Buf: IoBufAligned + Send>(
1423 16 : &self,
1424 16 : buf: FullSlice<Buf>,
1425 16 : offset: u64,
1426 16 : ctx: &RequestContext,
1427 16 : ) -> Result<(), Error> {
1428 16 : match self {
1429 8 : MaybeVirtualFile::VirtualFile(file) => {
1430 8 : let (_buf, res) = file.write_all_at(buf, offset, ctx).await;
1431 8 : res
1432 : }
1433 8 : MaybeVirtualFile::File(file) => file.write_all_at(&buf[..], offset),
1434 : }
1435 16 : }
1436 72 : async fn seek(&mut self, pos: SeekFrom) -> Result<u64, Error> {
1437 72 : match self {
1438 36 : MaybeVirtualFile::VirtualFile(file) => file.seek(pos).await,
1439 36 : MaybeVirtualFile::File(file) => file.seek(pos),
1440 : }
1441 72 : }
1442 16 : async fn write_all<Buf: IoBuf + Send>(
1443 16 : &mut self,
1444 16 : buf: FullSlice<Buf>,
1445 16 : ctx: &RequestContext,
1446 16 : ) -> Result<(), Error> {
1447 16 : match self {
1448 8 : MaybeVirtualFile::VirtualFile(file) => {
1449 8 : let (_buf, res) = file.write_all(buf, ctx).await;
1450 8 : res.map(|_| ())
1451 : }
1452 8 : MaybeVirtualFile::File(file) => file.write_all(&buf[..]),
1453 : }
1454 16 : }
1455 :
1456 : // Helper function to slurp contents of a file, starting at the current position,
1457 : // into a string
1458 884 : async fn read_string(&mut self, ctx: &RequestContext) -> Result<String, Error> {
1459 : use std::io::Read;
1460 884 : let mut buf = String::new();
1461 884 : match self {
1462 448 : MaybeVirtualFile::VirtualFile(file) => {
1463 448 : let mut buf = Vec::new();
1464 448 : file.read_to_end(&mut buf, ctx).await?;
1465 444 : return Ok(String::from_utf8(buf).unwrap());
1466 : }
1467 436 : MaybeVirtualFile::File(file) => {
1468 436 : file.read_to_string(&mut buf)?;
1469 : }
1470 : }
1471 432 : Ok(buf)
1472 884 : }
1473 :
1474 : // Helper function to slurp a portion of a file into a string
1475 808 : async fn read_string_at(
1476 808 : &mut self,
1477 808 : pos: u64,
1478 808 : len: usize,
1479 808 : ctx: &RequestContext,
1480 808 : ) -> Result<String, Error> {
1481 808 : let slice = IoBufferMut::with_capacity(len).slice_full();
1482 808 : assert_eq!(slice.bytes_total(), len);
1483 808 : let slice = self.read_exact_at(slice, pos, ctx).await?;
1484 808 : let buf = slice.into_inner();
1485 808 : assert_eq!(buf.len(), len);
1486 :
1487 808 : Ok(String::from_utf8(buf.to_vec()).unwrap())
1488 808 : }
1489 : }
1490 :
1491 : #[tokio::test]
1492 4 : async fn test_virtual_files() -> anyhow::Result<()> {
1493 4 : // The real work is done in the test_files() helper function. This
1494 4 : // allows us to run the same set of tests against a native File, and
1495 4 : // VirtualFile. We trust the native Files and wouldn't need to test them,
1496 4 : // but this allows us to verify that the operations return the same
1497 4 : // results with VirtualFiles as with native Files. (Except that with
1498 4 : // native files, you will run out of file descriptors if the ulimit
1499 4 : // is low enough.)
1500 4 : struct A;
1501 4 :
1502 4 : impl Adapter for A {
1503 412 : async fn open(
1504 412 : path: Utf8PathBuf,
1505 412 : opts: OpenOptions,
1506 412 : ctx: &RequestContext,
1507 412 : ) -> Result<MaybeVirtualFile, anyhow::Error> {
1508 412 : let vf = VirtualFile::open_with_options(&path, &opts, ctx).await?;
1509 412 : Ok(MaybeVirtualFile::VirtualFile(vf))
1510 412 : }
1511 4 : }
1512 4 : test_files::<A>("virtual_files").await
1513 4 : }
1514 :
1515 : #[tokio::test]
1516 4 : async fn test_physical_files() -> anyhow::Result<()> {
1517 4 : struct B;
1518 4 :
1519 4 : impl Adapter for B {
1520 412 : async fn open(
1521 412 : path: Utf8PathBuf,
1522 412 : opts: OpenOptions,
1523 412 : _ctx: &RequestContext,
1524 412 : ) -> Result<MaybeVirtualFile, anyhow::Error> {
1525 4 : Ok(MaybeVirtualFile::File({
1526 412 : let owned_fd = opts.open(path.as_std_path()).await?;
1527 412 : File::from(owned_fd)
1528 4 : }))
1529 412 : }
1530 4 : }
1531 4 :
1532 4 : test_files::<B>("physical_files").await
1533 4 : }
1534 :
1535 : /// This is essentially a closure which returns a MaybeVirtualFile, but because rust edition
1536 : /// 2024 is not yet out with new lifetime capture or outlives rules, this is a async function
1537 : /// in trait which benefits from the new lifetime capture rules already.
1538 : trait Adapter {
1539 : async fn open(
1540 : path: Utf8PathBuf,
1541 : opts: OpenOptions,
1542 : ctx: &RequestContext,
1543 : ) -> Result<MaybeVirtualFile, anyhow::Error>;
1544 : }
1545 :
1546 8 : async fn test_files<A>(testname: &str) -> anyhow::Result<()>
1547 8 : where
1548 8 : A: Adapter,
1549 8 : {
1550 8 : let ctx =
1551 8 : RequestContext::new(TaskKind::UnitTest, DownloadBehavior::Error).with_scope_unit_test();
1552 8 : let testdir = crate::config::PageServerConf::test_repo_dir(testname);
1553 8 : std::fs::create_dir_all(&testdir)?;
1554 :
1555 8 : let path_a = testdir.join("file_a");
1556 8 : let mut file_a = A::open(
1557 8 : path_a.clone(),
1558 8 : OpenOptions::new()
1559 8 : .write(true)
1560 8 : .create(true)
1561 8 : .truncate(true)
1562 8 : .to_owned(),
1563 8 : &ctx,
1564 8 : )
1565 8 : .await?;
1566 :
1567 8 : file_a
1568 8 : .write_all(b"foobar".to_vec().slice_len(), &ctx)
1569 8 : .await?;
1570 :
1571 : // cannot read from a file opened in write-only mode
1572 8 : let _ = file_a.read_string(&ctx).await.unwrap_err();
1573 :
1574 : // Close the file and re-open for reading
1575 8 : let mut file_a = A::open(path_a, OpenOptions::new().read(true).to_owned(), &ctx).await?;
1576 :
1577 : // cannot write to a file opened in read-only mode
1578 8 : let _ = file_a
1579 8 : .write_all(b"bar".to_vec().slice_len(), &ctx)
1580 8 : .await
1581 8 : .unwrap_err();
1582 8 :
1583 8 : // Try simple read
1584 8 : assert_eq!("foobar", file_a.read_string(&ctx).await?);
1585 :
1586 : // It's positioned at the EOF now.
1587 8 : assert_eq!("", file_a.read_string(&ctx).await?);
1588 :
1589 : // Test seeks.
1590 8 : assert_eq!(file_a.seek(SeekFrom::Start(1)).await?, 1);
1591 8 : assert_eq!("oobar", file_a.read_string(&ctx).await?);
1592 :
1593 8 : assert_eq!(file_a.seek(SeekFrom::End(-2)).await?, 4);
1594 8 : assert_eq!("ar", file_a.read_string(&ctx).await?);
1595 :
1596 8 : assert_eq!(file_a.seek(SeekFrom::Start(1)).await?, 1);
1597 8 : assert_eq!(file_a.seek(SeekFrom::Current(2)).await?, 3);
1598 8 : assert_eq!("bar", file_a.read_string(&ctx).await?);
1599 :
1600 8 : assert_eq!(file_a.seek(SeekFrom::Current(-5)).await?, 1);
1601 8 : assert_eq!("oobar", file_a.read_string(&ctx).await?);
1602 :
1603 : // Test erroneous seeks to before byte 0
1604 8 : file_a.seek(SeekFrom::End(-7)).await.unwrap_err();
1605 8 : assert_eq!(file_a.seek(SeekFrom::Start(1)).await?, 1);
1606 8 : file_a.seek(SeekFrom::Current(-2)).await.unwrap_err();
1607 8 :
1608 8 : // the erroneous seek should have left the position unchanged
1609 8 : assert_eq!("oobar", file_a.read_string(&ctx).await?);
1610 :
1611 : // Create another test file, and try FileExt functions on it.
1612 8 : let path_b = testdir.join("file_b");
1613 8 : let mut file_b = A::open(
1614 8 : path_b.clone(),
1615 8 : OpenOptions::new()
1616 8 : .read(true)
1617 8 : .write(true)
1618 8 : .create(true)
1619 8 : .truncate(true)
1620 8 : .to_owned(),
1621 8 : &ctx,
1622 8 : )
1623 8 : .await?;
1624 8 : file_b
1625 8 : .write_all_at(IoBuffer::from(b"BAR").slice_len(), 3, &ctx)
1626 8 : .await?;
1627 8 : file_b
1628 8 : .write_all_at(IoBuffer::from(b"FOO").slice_len(), 0, &ctx)
1629 8 : .await?;
1630 :
1631 8 : assert_eq!(file_b.read_string_at(2, 3, &ctx).await?, "OBA");
1632 :
1633 : // Open a lot of files, enough to cause some evictions. (Or to be precise,
1634 : // open the same file many times. The effect is the same.)
1635 : //
1636 : // leave file_a positioned at offset 1 before we start
1637 8 : assert_eq!(file_a.seek(SeekFrom::Start(1)).await?, 1);
1638 :
1639 8 : let mut vfiles = Vec::new();
1640 808 : for _ in 0..100 {
1641 800 : let mut vfile = A::open(
1642 800 : path_b.clone(),
1643 800 : OpenOptions::new().read(true).to_owned(),
1644 800 : &ctx,
1645 800 : )
1646 800 : .await?;
1647 800 : assert_eq!("FOOBAR", vfile.read_string(&ctx).await?);
1648 800 : vfiles.push(vfile);
1649 : }
1650 :
1651 : // make sure we opened enough files to definitely cause evictions.
1652 8 : assert!(vfiles.len() > TEST_MAX_FILE_DESCRIPTORS * 2);
1653 :
1654 : // The underlying file descriptor for 'file_a' should be closed now. Try to read
1655 : // from it again. We left the file positioned at offset 1 above.
1656 8 : assert_eq!("oobar", file_a.read_string(&ctx).await?);
1657 :
1658 : // Check that all the other FDs still work too. Use them in random order for
1659 : // good measure.
1660 8 : vfiles.as_mut_slice().shuffle(&mut thread_rng());
1661 800 : for vfile in vfiles.iter_mut() {
1662 800 : assert_eq!("OOBAR", vfile.read_string_at(1, 5, &ctx).await?);
1663 : }
1664 :
1665 8 : Ok(())
1666 8 : }
1667 :
1668 : /// Test using VirtualFiles from many threads concurrently. This tests both using
1669 : /// a lot of VirtualFiles concurrently, causing evictions, and also using the same
1670 : /// VirtualFile from multiple threads concurrently.
1671 : #[tokio::test]
1672 4 : async fn test_vfile_concurrency() -> Result<(), Error> {
1673 4 : const SIZE: usize = 8 * 1024;
1674 4 : const VIRTUAL_FILES: usize = 100;
1675 4 : const THREADS: usize = 100;
1676 4 : const SAMPLE: [u8; SIZE] = [0xADu8; SIZE];
1677 4 :
1678 4 : let ctx =
1679 4 : RequestContext::new(TaskKind::UnitTest, DownloadBehavior::Error).with_scope_unit_test();
1680 4 : let testdir = crate::config::PageServerConf::test_repo_dir("vfile_concurrency");
1681 4 : std::fs::create_dir_all(&testdir)?;
1682 4 :
1683 4 : // Create a test file.
1684 4 : let test_file_path = testdir.join("concurrency_test_file");
1685 4 : {
1686 4 : let file = File::create(&test_file_path)?;
1687 4 : file.write_all_at(&SAMPLE, 0)?;
1688 4 : }
1689 4 :
1690 4 : // Open the file many times.
1691 4 : let mut files = Vec::new();
1692 404 : for _ in 0..VIRTUAL_FILES {
1693 400 : let f = VirtualFileInner::open_with_options(
1694 400 : &test_file_path,
1695 400 : OpenOptions::new().read(true),
1696 400 : &ctx,
1697 400 : )
1698 400 : .await?;
1699 400 : files.push(f);
1700 4 : }
1701 4 : let files = Arc::new(files);
1702 4 :
1703 4 : // Launch many threads, and use the virtual files concurrently in random order.
1704 4 : let rt = tokio::runtime::Builder::new_multi_thread()
1705 4 : .worker_threads(THREADS)
1706 4 : .thread_name("test_vfile_concurrency thread")
1707 4 : .build()
1708 4 : .unwrap();
1709 4 : let mut hdls = Vec::new();
1710 404 : for _threadno in 0..THREADS {
1711 400 : let files = files.clone();
1712 400 : let ctx = ctx.detached_child(TaskKind::UnitTest, DownloadBehavior::Error);
1713 400 : let hdl = rt.spawn(async move {
1714 400 : let mut buf = IoBufferMut::with_capacity_zeroed(SIZE);
1715 400 : let mut rng = rand::rngs::OsRng;
1716 400000 : for _ in 1..1000 {
1717 399600 : let f = &files[rng.gen_range(0..files.len())];
1718 399600 : buf = f
1719 399600 : .read_exact_at(buf.slice_full(), 0, &ctx)
1720 399600 : .await
1721 399600 : .unwrap()
1722 399600 : .into_inner();
1723 399600 : assert!(buf[..] == SAMPLE);
1724 4 : }
1725 400 : });
1726 400 : hdls.push(hdl);
1727 400 : }
1728 404 : for hdl in hdls {
1729 400 : hdl.await?;
1730 4 : }
1731 4 : std::mem::forget(rt);
1732 4 :
1733 4 : Ok(())
1734 4 : }
1735 :
1736 : #[tokio::test]
1737 4 : async fn test_atomic_overwrite_basic() {
1738 4 : let ctx =
1739 4 : RequestContext::new(TaskKind::UnitTest, DownloadBehavior::Error).with_scope_unit_test();
1740 4 : let testdir = crate::config::PageServerConf::test_repo_dir("test_atomic_overwrite_basic");
1741 4 : std::fs::create_dir_all(&testdir).unwrap();
1742 4 :
1743 4 : let path = testdir.join("myfile");
1744 4 : let tmp_path = testdir.join("myfile.tmp");
1745 4 :
1746 4 : VirtualFileInner::crashsafe_overwrite(path.clone(), tmp_path.clone(), b"foo".to_vec())
1747 4 : .await
1748 4 : .unwrap();
1749 4 : let mut file = MaybeVirtualFile::from(VirtualFile::open(&path, &ctx).await.unwrap());
1750 4 : let post = file.read_string(&ctx).await.unwrap();
1751 4 : assert_eq!(post, "foo");
1752 4 : assert!(!tmp_path.exists());
1753 4 : drop(file);
1754 4 :
1755 4 : VirtualFileInner::crashsafe_overwrite(path.clone(), tmp_path.clone(), b"bar".to_vec())
1756 4 : .await
1757 4 : .unwrap();
1758 4 : let mut file = MaybeVirtualFile::from(VirtualFile::open(&path, &ctx).await.unwrap());
1759 4 : let post = file.read_string(&ctx).await.unwrap();
1760 4 : assert_eq!(post, "bar");
1761 4 : assert!(!tmp_path.exists());
1762 4 : drop(file);
1763 4 : }
1764 :
1765 : #[tokio::test]
1766 4 : async fn test_atomic_overwrite_preexisting_tmp() {
1767 4 : let ctx =
1768 4 : RequestContext::new(TaskKind::UnitTest, DownloadBehavior::Error).with_scope_unit_test();
1769 4 : let testdir =
1770 4 : crate::config::PageServerConf::test_repo_dir("test_atomic_overwrite_preexisting_tmp");
1771 4 : std::fs::create_dir_all(&testdir).unwrap();
1772 4 :
1773 4 : let path = testdir.join("myfile");
1774 4 : let tmp_path = testdir.join("myfile.tmp");
1775 4 :
1776 4 : std::fs::write(&tmp_path, "some preexisting junk that should be removed").unwrap();
1777 4 : assert!(tmp_path.exists());
1778 4 :
1779 4 : VirtualFileInner::crashsafe_overwrite(path.clone(), tmp_path.clone(), b"foo".to_vec())
1780 4 : .await
1781 4 : .unwrap();
1782 4 :
1783 4 : let mut file = MaybeVirtualFile::from(VirtualFile::open(&path, &ctx).await.unwrap());
1784 4 : let post = file.read_string(&ctx).await.unwrap();
1785 4 : assert_eq!(post, "foo");
1786 4 : assert!(!tmp_path.exists());
1787 4 : drop(file);
1788 4 : }
1789 : }
|