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