Line data Source code
1 : //!
2 : //! VirtualFile is like a normal File, but it's not bound directly to
3 : //! a file descriptor. Instead, the file is opened when it's read from,
4 : //! and if too many files are open globally in the system, least-recently
5 : //! used ones are closed.
6 : //!
7 : //! To track which files have been recently used, we use the clock algorithm
8 : //! with a 'recently_used' flag on each slot.
9 : //!
10 : //! This is similar to PostgreSQL's virtual file descriptor facility in
11 : //! src/backend/storage/file/fd.c
12 : //!
13 : use crate::metrics::{StorageIoOperation, STORAGE_IO_SIZE, STORAGE_IO_TIME_METRIC};
14 :
15 : use crate::page_cache::PageWriteGuard;
16 : use crate::tenant::TENANTS_SEGMENT_NAME;
17 : use camino::{Utf8Path, Utf8PathBuf};
18 : use once_cell::sync::OnceCell;
19 : use pageserver_api::shard::TenantShardId;
20 : use std::fs::{self, File};
21 : use std::io::{Error, ErrorKind, Seek, SeekFrom};
22 : use tokio_epoll_uring::IoBufMut;
23 :
24 : use std::os::fd::{AsRawFd, FromRawFd, IntoRawFd, OwnedFd, RawFd};
25 : use std::os::unix::fs::FileExt;
26 : use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
27 : use tokio::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard};
28 : use tokio::time::Instant;
29 : use utils::fs_ext;
30 :
31 : pub use pageserver_api::models::virtual_file as api;
32 : pub(crate) mod io_engine;
33 : mod open_options;
34 : pub(crate) use io_engine::IoEngineKind;
35 : pub(crate) use open_options::*;
36 :
37 : ///
38 : /// A virtual file descriptor. You can use this just like std::fs::File, but internally
39 : /// the underlying file is closed if the system is low on file descriptors,
40 : /// and re-opened when it's accessed again.
41 : ///
42 : /// Like with std::fs::File, multiple threads can read/write the file concurrently,
43 : /// holding just a shared reference the same VirtualFile, using the read_at() / write_at()
44 : /// functions from the FileExt trait. But the functions from the Read/Write/Seek traits
45 : /// require a mutable reference, because they modify the "current position".
46 : ///
47 : /// Each VirtualFile has a physical file descriptor in the global OPEN_FILES array, at the
48 : /// slot that 'handle points to, if the underlying file is currently open. If it's not
49 : /// currently open, the 'handle' can still point to the slot where it was last kept. The
50 : /// 'tag' field is used to detect whether the handle still is valid or not.
51 : ///
52 0 : #[derive(Debug)]
53 : pub struct VirtualFile {
54 : /// Lazy handle to the global file descriptor cache. The slot that this points to
55 : /// might contain our File, or it may be empty, or it may contain a File that
56 : /// belongs to a different VirtualFile.
57 : handle: RwLock<SlotHandle>,
58 :
59 : /// Current file position
60 : pos: u64,
61 :
62 : /// File path and options to use to open it.
63 : ///
64 : /// Note: this only contains the options needed to re-open it. For example,
65 : /// if a new file is created, we only pass the create flag when it's initially
66 : /// opened, in the VirtualFile::create() function, and strip the flag before
67 : /// storing it here.
68 : pub path: Utf8PathBuf,
69 : open_options: OpenOptions,
70 :
71 : // These are strings becase we only use them for metrics, and those expect strings.
72 : // It makes no sense for us to constantly turn the `TimelineId` and `TenantId` into
73 : // strings.
74 : tenant_id: String,
75 : shard_id: String,
76 : timeline_id: String,
77 : }
78 :
79 290425 : #[derive(Debug, PartialEq, Clone, Copy)]
80 : struct SlotHandle {
81 : /// Index into OPEN_FILES.slots
82 : index: usize,
83 :
84 : /// Value of 'tag' in the slot. If slot's tag doesn't match, then the slot has
85 : /// been recycled and no longer contains the FD for this virtual file.
86 : tag: u64,
87 : }
88 :
89 : /// OPEN_FILES is the global array that holds the physical file descriptors that
90 : /// are currently open. Each slot in the array is protected by a separate lock,
91 : /// so that different files can be accessed independently. The lock must be held
92 : /// in write mode to replace the slot with a different file, but a read mode
93 : /// is enough to operate on the file, whether you're reading or writing to it.
94 : ///
95 : /// OPEN_FILES starts in uninitialized state, and it's initialized by
96 : /// the virtual_file::init() function. It must be called exactly once at page
97 : /// server startup.
98 : static OPEN_FILES: OnceCell<OpenFiles> = OnceCell::new();
99 :
100 : struct OpenFiles {
101 : slots: &'static [Slot],
102 :
103 : /// clock arm for the clock algorithm
104 : next: AtomicUsize,
105 : }
106 :
107 : struct Slot {
108 : inner: RwLock<SlotInner>,
109 :
110 : /// has this file been used since last clock sweep?
111 : recently_used: AtomicBool,
112 : }
113 :
114 : struct SlotInner {
115 : /// Counter that's incremented every time a different file is stored here.
116 : /// To avoid the ABA problem.
117 : tag: u64,
118 :
119 : /// the underlying file
120 : file: Option<OwnedFd>,
121 : }
122 :
123 : /// Impl of [`tokio_epoll_uring::IoBuf`] and [`tokio_epoll_uring::IoBufMut`] for [`PageWriteGuard`].
124 : struct PageWriteGuardBuf {
125 : page: PageWriteGuard<'static>,
126 : init_up_to: usize,
127 : }
128 : // Safety: the [`PageWriteGuard`] gives us exclusive ownership of the page cache slot,
129 : // and the location remains stable even if [`Self`] or the [`PageWriteGuard`] is moved.
130 : unsafe impl tokio_epoll_uring::IoBuf for PageWriteGuardBuf {
131 5115143 : fn stable_ptr(&self) -> *const u8 {
132 5115143 : self.page.as_ptr()
133 5115143 : }
134 15345429 : fn bytes_init(&self) -> usize {
135 15345429 : self.init_up_to
136 15345429 : }
137 5115143 : fn bytes_total(&self) -> usize {
138 5115143 : self.page.len()
139 5115143 : }
140 : }
141 : // Safety: see above, plus: the ownership of [`PageWriteGuard`] means exclusive access,
142 : // hence it's safe to hand out the `stable_mut_ptr()`.
143 : unsafe impl tokio_epoll_uring::IoBufMut for PageWriteGuardBuf {
144 5115143 : fn stable_mut_ptr(&mut self) -> *mut u8 {
145 5115143 : self.page.as_mut_ptr()
146 5115143 : }
147 :
148 5115143 : unsafe fn set_init(&mut self, pos: usize) {
149 5115143 : assert!(pos <= self.page.len());
150 5115143 : self.init_up_to = pos;
151 5115143 : }
152 : }
153 :
154 : impl OpenFiles {
155 : /// Find a slot to use, evicting an existing file descriptor if needed.
156 : ///
157 : /// On return, we hold a lock on the slot, and its 'tag' has been updated
158 : /// recently_used has been set. It's all ready for reuse.
159 273531 : async fn find_victim_slot(&self) -> (SlotHandle, RwLockWriteGuard<SlotInner>) {
160 273531 : //
161 273531 : // Run the clock algorithm to find a slot to replace.
162 273531 : //
163 273531 : let num_slots = self.slots.len();
164 273531 : let mut retries = 0;
165 : let mut slot;
166 : let mut slot_guard;
167 : let index;
168 2416105 : loop {
169 2416105 : let next = self.next.fetch_add(1, Ordering::AcqRel) % num_slots;
170 2416105 : slot = &self.slots[next];
171 2416105 :
172 2416105 : // If the recently_used flag on this slot is set, continue the clock
173 2416105 : // sweep. Otherwise try to use this slot. If we cannot acquire the
174 2416105 : // lock, also continue the clock sweep.
175 2416105 : //
176 2416105 : // We only continue in this manner for a while, though. If we loop
177 2416105 : // through the array twice without finding a victim, just pick the
178 2416105 : // next slot and wait until we can reuse it. This way, we avoid
179 2416105 : // spinning in the extreme case that all the slots are busy with an
180 2416105 : // I/O operation.
181 2416105 : if retries < num_slots * 2 {
182 2330734 : if !slot.recently_used.swap(false, Ordering::Release) {
183 2085028 : if let Ok(guard) = slot.inner.try_write() {
184 188160 : slot_guard = guard;
185 188160 : index = next;
186 188160 : break;
187 1896868 : }
188 245706 : }
189 2142574 : retries += 1;
190 : } else {
191 85371 : slot_guard = slot.inner.write().await;
192 85371 : index = next;
193 85371 : break;
194 : }
195 : }
196 :
197 : //
198 : // We now have the victim slot locked. If it was in use previously, close the
199 : // old file.
200 : //
201 273531 : if let Some(old_file) = slot_guard.file.take() {
202 212703 : // the normal path of dropping VirtualFile uses "close", use "close-by-replace" here to
203 212703 : // distinguish the two.
204 212703 : STORAGE_IO_TIME_METRIC
205 212703 : .get(StorageIoOperation::CloseByReplace)
206 212703 : .observe_closure_duration(|| drop(old_file));
207 212703 : }
208 :
209 : // Prepare the slot for reuse and return it
210 273531 : slot_guard.tag += 1;
211 273531 : slot.recently_used.store(true, Ordering::Relaxed);
212 273531 : (
213 273531 : SlotHandle {
214 273531 : index,
215 273531 : tag: slot_guard.tag,
216 273531 : },
217 273531 : slot_guard,
218 273531 : )
219 273531 : }
220 : }
221 :
222 : /// Identify error types that should alwways terminate the process. Other
223 : /// error types may be elegible for retry.
224 0 : pub(crate) fn is_fatal_io_error(e: &std::io::Error) -> bool {
225 0 : use nix::errno::Errno::*;
226 0 : match e.raw_os_error().map(nix::errno::from_i32) {
227 : Some(EIO) => {
228 : // Terminate on EIO because we no longer trust the device to store
229 : // data safely, or to uphold persistence guarantees on fsync.
230 0 : true
231 : }
232 : Some(EROFS) => {
233 : // Terminate on EROFS because a filesystem is usually remounted
234 : // readonly when it has experienced some critical issue, so the same
235 : // logic as EIO applies.
236 0 : true
237 : }
238 : Some(EACCES) => {
239 : // Terminate on EACCESS because we should always have permissions
240 : // for our own data dir: if we don't, then we can't do our job and
241 : // need administrative intervention to fix permissions. Terminating
242 : // is the best way to make sure we stop cleanly rather than going
243 : // into infinite retry loops, and will make it clear to the outside
244 : // world that we need help.
245 0 : true
246 : }
247 : _ => {
248 : // Treat all other local file I/O errors are retryable. This includes:
249 : // - ENOSPC: we stay up and wait for eviction to free some space
250 : // - EINVAL, EBADF, EBADFD: this is a code bug, not a filesystem/hardware issue
251 : // - WriteZero, Interrupted: these are used internally VirtualFile
252 0 : false
253 : }
254 : }
255 0 : }
256 :
257 : /// Call this when the local filesystem gives us an error with an external
258 : /// cause: this includes EIO, EROFS, and EACCESS: all these indicate either
259 : /// bad storage or bad configuration, and we can't fix that from inside
260 : /// a running process.
261 0 : pub(crate) fn on_fatal_io_error(e: &std::io::Error, context: &str) -> ! {
262 0 : tracing::error!("Fatal I/O error: {e}: {context})");
263 0 : std::process::abort();
264 : }
265 :
266 : pub(crate) trait MaybeFatalIo<T> {
267 : fn maybe_fatal_err(self, context: &str) -> std::io::Result<T>;
268 : fn fatal_err(self, context: &str) -> T;
269 : }
270 :
271 : impl<T> MaybeFatalIo<T> for std::io::Result<T> {
272 : /// Terminate the process if the result is an error of a fatal type, else pass it through
273 : ///
274 : /// This is appropriate for writes, where we typically want to die on EIO/ACCES etc, but
275 : /// not on ENOSPC.
276 119 : fn maybe_fatal_err(self, context: &str) -> std::io::Result<T> {
277 119 : if let Err(e) = &self {
278 0 : if is_fatal_io_error(e) {
279 0 : on_fatal_io_error(e, context);
280 0 : }
281 119 : }
282 119 : self
283 119 : }
284 :
285 : /// Terminate the process on any I/O error.
286 : ///
287 : /// This is appropriate for reads on files that we know exist: they should always work.
288 1485 : fn fatal_err(self, context: &str) -> T {
289 1485 : match self {
290 1485 : Ok(v) => v,
291 0 : Err(e) => {
292 0 : on_fatal_io_error(&e, context);
293 : }
294 : }
295 1485 : }
296 : }
297 :
298 : /// Observe duration for the given storage I/O operation
299 : ///
300 : /// Unlike `observe_closure_duration`, this supports async,
301 : /// where "support" means that we measure wall clock time.
302 : macro_rules! observe_duration {
303 : ($op:expr, $($body:tt)*) => {{
304 : let instant = Instant::now();
305 : let result = $($body)*;
306 : let elapsed = instant.elapsed().as_secs_f64();
307 : STORAGE_IO_TIME_METRIC
308 : .get($op)
309 : .observe(elapsed);
310 : result
311 : }}
312 : }
313 :
314 : macro_rules! with_file {
315 : ($this:expr, $op:expr, | $ident:ident | $($body:tt)*) => {{
316 : let $ident = $this.lock_file().await?;
317 : observe_duration!($op, $($body)*)
318 : }};
319 : ($this:expr, $op:expr, | mut $ident:ident | $($body:tt)*) => {{
320 : let mut $ident = $this.lock_file().await?;
321 : observe_duration!($op, $($body)*)
322 : }};
323 : }
324 :
325 : impl VirtualFile {
326 : /// Open a file in read-only mode. Like File::open.
327 33421 : pub async fn open(path: &Utf8Path) -> Result<VirtualFile, std::io::Error> {
328 33421 : Self::open_with_options(path, OpenOptions::new().read(true)).await
329 33421 : }
330 :
331 : /// Create a new file for writing. If the file exists, it will be truncated.
332 : /// Like File::create.
333 15919 : pub async fn create(path: &Utf8Path) -> Result<VirtualFile, std::io::Error> {
334 15919 : Self::open_with_options(
335 15919 : path,
336 15919 : OpenOptions::new().write(true).create(true).truncate(true),
337 15919 : )
338 235 : .await
339 15919 : }
340 :
341 : /// Open a file with given options.
342 : ///
343 : /// Note: If any custom flags were set in 'open_options' through OpenOptionsExt,
344 : /// they will be applied also when the file is subsequently re-opened, not only
345 : /// on the first time. Make sure that's sane!
346 79748 : pub async fn open_with_options(
347 79748 : path: &Utf8Path,
348 79748 : open_options: &OpenOptions,
349 79748 : ) -> Result<VirtualFile, std::io::Error> {
350 79748 : let path_str = path.to_string();
351 79748 : let parts = path_str.split('/').collect::<Vec<&str>>();
352 79748 : let (tenant_id, shard_id, timeline_id) =
353 79748 : if parts.len() > 5 && parts[parts.len() - 5] == TENANTS_SEGMENT_NAME {
354 68283 : let tenant_shard_part = parts[parts.len() - 4];
355 68283 : let (tenant_id, shard_id) = match tenant_shard_part.parse::<TenantShardId>() {
356 68283 : Ok(tenant_shard_id) => (
357 68283 : tenant_shard_id.tenant_id.to_string(),
358 68283 : format!("{}", tenant_shard_id.shard_slug()),
359 68283 : ),
360 : Err(_) => {
361 : // Malformed path: this ID is just for observability, so tolerate it
362 : // and pass through
363 0 : (tenant_shard_part.to_string(), "*".to_string())
364 : }
365 : };
366 68283 : (tenant_id, shard_id, parts[parts.len() - 2].to_string())
367 : } else {
368 11465 : ("*".to_string(), "*".to_string(), "*".to_string())
369 : };
370 79748 : let (handle, mut slot_guard) = get_open_files().find_victim_slot().await;
371 :
372 : // NB: there is also StorageIoOperation::OpenAfterReplace which is for the case
373 : // where our caller doesn't get to use the returned VirtualFile before its
374 : // slot gets re-used by someone else.
375 79748 : let file = observe_duration!(StorageIoOperation::Open, {
376 79748 : open_options.open(path.as_std_path()).await?
377 : });
378 :
379 : // Strip all options other than read and write.
380 : //
381 : // It would perhaps be nicer to check just for the read and write flags
382 : // explicitly, but OpenOptions doesn't contain any functions to read flags,
383 : // only to set them.
384 79748 : let mut reopen_options = open_options.clone();
385 79748 : reopen_options.create(false);
386 79748 : reopen_options.create_new(false);
387 79748 : reopen_options.truncate(false);
388 79748 :
389 79748 : let vfile = VirtualFile {
390 79748 : handle: RwLock::new(handle),
391 79748 : pos: 0,
392 79748 : path: path.to_path_buf(),
393 79748 : open_options: reopen_options,
394 79748 : tenant_id,
395 79748 : shard_id,
396 79748 : timeline_id,
397 79748 : };
398 79748 :
399 79748 : // TODO: Under pressure, it's likely the slot will get re-used and
400 79748 : // the underlying file closed before they get around to using it.
401 79748 : // => https://github.com/neondatabase/neon/issues/6065
402 79748 : slot_guard.file.replace(file);
403 79748 :
404 79748 : Ok(vfile)
405 79748 : }
406 :
407 : /// Writes a file to the specified `final_path` in a crash safe fasion
408 : ///
409 : /// The file is first written to the specified tmp_path, and in a second
410 : /// step, the tmp path is renamed to the final path. As renames are
411 : /// atomic, a crash during the write operation will never leave behind a
412 : /// partially written file.
413 8916 : pub async fn crashsafe_overwrite(
414 8916 : final_path: &Utf8Path,
415 8916 : tmp_path: &Utf8Path,
416 8916 : content: &[u8],
417 8916 : ) -> std::io::Result<()> {
418 8916 : let Some(final_path_parent) = final_path.parent() else {
419 0 : return Err(std::io::Error::from_raw_os_error(
420 0 : nix::errno::Errno::EINVAL as i32,
421 0 : ));
422 : };
423 8916 : std::fs::remove_file(tmp_path).or_else(fs_ext::ignore_not_found)?;
424 8916 : let mut file = Self::open_with_options(
425 8916 : tmp_path,
426 8916 : OpenOptions::new()
427 8916 : .write(true)
428 8916 : // Use `create_new` so that, if we race with ourselves or something else,
429 8916 : // we bail out instead of causing damage.
430 8916 : .create_new(true),
431 8916 : )
432 451 : .await?;
433 8916 : file.write_all(content).await?;
434 8916 : file.sync_all().await?;
435 8916 : drop(file); // before the rename, that's important!
436 8916 : // renames are atomic
437 8916 : std::fs::rename(tmp_path, final_path)?;
438 : // Only open final path parent dirfd now, so that this operation only
439 : // ever holds one VirtualFile fd at a time. That's important because
440 : // the current `find_victim_slot` impl might pick the same slot for both
441 : // VirtualFile., and it eventually does a blocking write lock instead of
442 : // try_lock.
443 8916 : let final_parent_dirfd =
444 8916 : Self::open_with_options(final_path_parent, OpenOptions::new().read(true)).await?;
445 8916 : final_parent_dirfd.sync_all().await?;
446 8916 : Ok(())
447 8916 : }
448 :
449 : /// Call File::sync_all() on the underlying File.
450 40197 : pub async fn sync_all(&self) -> Result<(), Error> {
451 40197 : with_file!(self, StorageIoOperation::Fsync, |file_guard| file_guard
452 40197 : .with_std_file(|std_file| std_file.sync_all()))
453 40197 : }
454 :
455 22365 : pub async fn metadata(&self) -> Result<fs::Metadata, Error> {
456 22365 : with_file!(self, StorageIoOperation::Metadata, |file_guard| file_guard
457 22365 : .with_std_file(|std_file| std_file.metadata()))
458 22365 : }
459 :
460 : /// Helper function internal to `VirtualFile` that looks up the underlying File,
461 : /// opens it and evicts some other File if necessary. The passed parameter is
462 : /// assumed to be a function available for the physical `File`.
463 : ///
464 : /// We are doing it via a macro as Rust doesn't support async closures that
465 : /// take on parameters with lifetimes.
466 14199314 : async fn lock_file(&self) -> Result<FileGuard, Error> {
467 14199311 : let open_files = get_open_files();
468 :
469 193783 : let mut handle_guard = {
470 : // Read the cached slot handle, and see if the slot that it points to still
471 : // contains our File.
472 : //
473 : // We only need to hold the handle lock while we read the current handle. If
474 : // another thread closes the file and recycles the slot for a different file,
475 : // we will notice that the handle we read is no longer valid and retry.
476 14199311 : let mut handle = *self.handle.read().await;
477 14295953 : loop {
478 14295953 : // Check if the slot contains our File
479 14295953 : {
480 14295953 : let slot = &open_files.slots[handle.index];
481 14295953 : let slot_guard = slot.inner.read().await;
482 14295953 : if slot_guard.tag == handle.tag && slot_guard.file.is_some() {
483 : // Found a cached file descriptor.
484 14005528 : slot.recently_used.store(true, Ordering::Relaxed);
485 14005528 : return Ok(FileGuard { slot_guard });
486 290425 : }
487 : }
488 :
489 : // The slot didn't contain our File. We will have to open it ourselves,
490 : // but before that, grab a write lock on handle in the VirtualFile, so
491 : // that no other thread will try to concurrently open the same file.
492 290425 : let handle_guard = self.handle.write().await;
493 :
494 : // If another thread changed the handle while we were not holding the lock,
495 : // then the handle might now be valid again. Loop back to retry.
496 290425 : if *handle_guard != handle {
497 96642 : handle = *handle_guard;
498 96642 : continue;
499 193783 : }
500 193783 : break handle_guard;
501 : }
502 : };
503 :
504 : // We need to open the file ourselves. The handle in the VirtualFile is
505 : // now locked in write-mode. Find a free slot to put it in.
506 193783 : let (handle, mut slot_guard) = open_files.find_victim_slot().await;
507 :
508 : // Re-open the physical file.
509 : // NB: we use StorageIoOperation::OpenAferReplace for this to distinguish this
510 : // case from StorageIoOperation::Open. This helps with identifying thrashing
511 : // of the virtual file descriptor cache.
512 193783 : let file = observe_duration!(StorageIoOperation::OpenAfterReplace, {
513 193783 : self.open_options.open(self.path.as_std_path()).await?
514 : });
515 :
516 : // Store the File in the slot and update the handle in the VirtualFile
517 : // to point to it.
518 193783 : slot_guard.file.replace(file);
519 193783 :
520 193783 : *handle_guard = handle;
521 193783 :
522 193783 : return Ok(FileGuard {
523 193783 : slot_guard: slot_guard.downgrade(),
524 193783 : });
525 14199311 : }
526 :
527 0 : pub fn remove(self) {
528 0 : let path = self.path.clone();
529 0 : drop(self);
530 0 : std::fs::remove_file(path).expect("failed to remove the virtual file");
531 0 : }
532 :
533 67115 : pub async fn seek(&mut self, pos: SeekFrom) -> Result<u64, Error> {
534 67115 : match pos {
535 67105 : SeekFrom::Start(offset) => {
536 67105 : self.pos = offset;
537 67105 : }
538 4 : SeekFrom::End(offset) => {
539 4 : self.pos = with_file!(self, StorageIoOperation::Seek, |mut file_guard| file_guard
540 4 : .with_std_file_mut(|std_file| std_file.seek(SeekFrom::End(offset))))?
541 : }
542 6 : SeekFrom::Current(offset) => {
543 6 : let pos = self.pos as i128 + offset as i128;
544 6 : if pos < 0 {
545 2 : return Err(Error::new(
546 2 : ErrorKind::InvalidInput,
547 2 : "offset would be negative",
548 2 : ));
549 4 : }
550 4 : if pos > u64::MAX as i128 {
551 0 : return Err(Error::new(ErrorKind::InvalidInput, "offset overflow"));
552 4 : }
553 4 : self.pos = pos as u64;
554 : }
555 : }
556 67111 : Ok(self.pos)
557 67115 : }
558 :
559 5335342 : pub async fn read_exact_at<B>(&self, buf: B, offset: u64) -> Result<B, Error>
560 5335342 : where
561 5335342 : B: IoBufMut + Send,
562 5335342 : {
563 5335342 : let (buf, res) =
564 5335342 : read_exact_at_impl(buf, offset, |buf, offset| self.read_at(buf, offset)).await;
565 5335342 : res.map(|()| buf)
566 5335342 : }
567 :
568 : /// Like [`Self::read_exact_at`] but for [`PageWriteGuard`].
569 5115143 : pub async fn read_exact_at_page(
570 5115143 : &self,
571 5115143 : page: PageWriteGuard<'static>,
572 5115143 : offset: u64,
573 5115143 : ) -> Result<PageWriteGuard<'static>, Error> {
574 5115140 : let buf = PageWriteGuardBuf {
575 5115140 : page,
576 5115140 : init_up_to: 0,
577 5115140 : };
578 5115140 : let res = self.read_exact_at(buf, offset).await;
579 5115140 : res.map(|PageWriteGuardBuf { page, .. }| page)
580 5115140 : .map_err(|e| Error::new(ErrorKind::Other, e))
581 5115140 : }
582 :
583 : // Copied from https://doc.rust-lang.org/1.72.0/src/std/os/unix/fs.rs.html#219-235
584 3688654 : pub async fn write_all_at(&self, mut buf: &[u8], mut offset: u64) -> Result<(), Error> {
585 7377308 : while !buf.is_empty() {
586 3688654 : match self.write_at(buf, offset).await {
587 : Ok(0) => {
588 0 : return Err(Error::new(
589 0 : std::io::ErrorKind::WriteZero,
590 0 : "failed to write whole buffer",
591 0 : ));
592 : }
593 3688654 : Ok(n) => {
594 3688654 : buf = &buf[n..];
595 3688654 : offset += n as u64;
596 3688654 : }
597 0 : Err(ref e) if e.kind() == std::io::ErrorKind::Interrupted => {}
598 0 : Err(e) => return Err(e),
599 : }
600 : }
601 3688654 : Ok(())
602 3688654 : }
603 :
604 5112336 : pub async fn write_all(&mut self, mut buf: &[u8]) -> Result<(), Error> {
605 10224639 : while !buf.is_empty() {
606 5112305 : match self.write(buf).await {
607 : Ok(0) => {
608 0 : return Err(Error::new(
609 0 : std::io::ErrorKind::WriteZero,
610 0 : "failed to write whole buffer",
611 0 : ));
612 : }
613 5112303 : Ok(n) => {
614 5112303 : buf = &buf[n..];
615 5112303 : }
616 2 : Err(ref e) if e.kind() == std::io::ErrorKind::Interrupted => {}
617 2 : Err(e) => return Err(e),
618 : }
619 : }
620 5112334 : Ok(())
621 5112336 : }
622 :
623 5112305 : async fn write(&mut self, buf: &[u8]) -> Result<usize, std::io::Error> {
624 5112305 : let pos = self.pos;
625 5112305 : let n = self.write_at(buf, pos).await?;
626 5112303 : self.pos += n as u64;
627 5112303 : Ok(n)
628 5112305 : }
629 :
630 5335786 : pub(crate) async fn read_at<B>(&self, buf: B, offset: u64) -> (B, Result<usize, Error>)
631 5335786 : where
632 5335786 : B: tokio_epoll_uring::BoundedBufMut + Send,
633 5335786 : {
634 5335786 : let file_guard = match self.lock_file().await {
635 5335786 : Ok(file_guard) => file_guard,
636 0 : Err(e) => return (buf, Err(e)),
637 : };
638 :
639 5335786 : observe_duration!(StorageIoOperation::Read, {
640 5335786 : let ((_file_guard, buf), res) = io_engine::get().read_at(file_guard, offset, buf).await;
641 5335786 : if let Ok(size) = res {
642 5335784 : STORAGE_IO_SIZE
643 5335784 : .with_label_values(&[
644 5335784 : "read",
645 5335784 : &self.tenant_id,
646 5335784 : &self.shard_id,
647 5335784 : &self.timeline_id,
648 5335784 : ])
649 5335784 : .add(size as i64);
650 5335784 : }
651 5335786 : (buf, res)
652 : })
653 5335786 : }
654 :
655 8800959 : async fn write_at(&self, buf: &[u8], offset: u64) -> Result<usize, Error> {
656 8800959 : let result = with_file!(self, StorageIoOperation::Write, |file_guard| {
657 8800959 : file_guard.with_std_file(|std_file| std_file.write_at(buf, offset))
658 : });
659 8800959 : if let Ok(size) = result {
660 8800957 : STORAGE_IO_SIZE
661 8800957 : .with_label_values(&["write", &self.tenant_id, &self.shard_id, &self.timeline_id])
662 8800957 : .add(size as i64);
663 8800957 : }
664 8800959 : result
665 8800959 : }
666 : }
667 :
668 : // Adapted from https://doc.rust-lang.org/1.72.0/src/std/os/unix/fs.rs.html#117-135
669 5335350 : pub async fn read_exact_at_impl<B, F, Fut>(
670 5335350 : buf: B,
671 5335350 : mut offset: u64,
672 5335350 : mut read_at: F,
673 5335350 : ) -> (B, std::io::Result<()>)
674 5335350 : where
675 5335350 : B: IoBufMut + Send,
676 5335350 : F: FnMut(tokio_epoll_uring::Slice<B>, u64) -> Fut,
677 5335350 : Fut: std::future::Future<Output = (tokio_epoll_uring::Slice<B>, std::io::Result<usize>)>,
678 5335350 : {
679 5335350 : use tokio_epoll_uring::BoundedBuf;
680 5335350 : let mut buf: tokio_epoll_uring::Slice<B> = buf.slice_full(); // includes all the uninitialized memory
681 10670702 : while buf.bytes_total() != 0 {
682 : let res;
683 5335354 : (buf, res) = read_at(buf, offset).await;
684 0 : match res {
685 2 : Ok(0) => break,
686 5335352 : Ok(n) => {
687 5335352 : buf = buf.slice(n..);
688 5335352 : offset += n as u64;
689 5335352 : }
690 0 : Err(ref e) if e.kind() == std::io::ErrorKind::Interrupted => {}
691 0 : Err(e) => return (buf.into_inner(), Err(e)),
692 : }
693 : }
694 : // NB: don't use `buf.is_empty()` here; it is from the
695 : // `impl Deref for Slice { Target = [u8] }`; the the &[u8]
696 : // returned by it only covers the initialized portion of `buf`.
697 : // Whereas we're interested in ensuring that we filled the entire
698 : // buffer that the user passed in.
699 5335350 : if buf.bytes_total() != 0 {
700 2 : (
701 2 : buf.into_inner(),
702 2 : Err(std::io::Error::new(
703 2 : std::io::ErrorKind::UnexpectedEof,
704 2 : "failed to fill whole buffer",
705 2 : )),
706 2 : )
707 : } else {
708 5335348 : assert_eq!(buf.len(), buf.bytes_total());
709 5335348 : (buf.into_inner(), Ok(()))
710 : }
711 5335350 : }
712 :
713 : #[cfg(test)]
714 : mod test_read_exact_at_impl {
715 :
716 : use std::{collections::VecDeque, sync::Arc};
717 :
718 : use tokio_epoll_uring::{BoundedBuf, BoundedBufMut};
719 :
720 : use super::read_exact_at_impl;
721 :
722 : struct Expectation {
723 : offset: u64,
724 : bytes_total: usize,
725 : result: std::io::Result<Vec<u8>>,
726 : }
727 : struct MockReadAt {
728 : expectations: VecDeque<Expectation>,
729 : }
730 :
731 : impl MockReadAt {
732 12 : async fn read_at(
733 12 : &mut self,
734 12 : mut buf: tokio_epoll_uring::Slice<Vec<u8>>,
735 12 : offset: u64,
736 12 : ) -> (tokio_epoll_uring::Slice<Vec<u8>>, std::io::Result<usize>) {
737 12 : let exp = self
738 12 : .expectations
739 12 : .pop_front()
740 12 : .expect("read_at called but we have no expectations left");
741 12 : assert_eq!(exp.offset, offset);
742 12 : assert_eq!(exp.bytes_total, buf.bytes_total());
743 12 : match exp.result {
744 12 : Ok(bytes) => {
745 12 : assert!(bytes.len() <= buf.bytes_total());
746 12 : buf.put_slice(&bytes);
747 12 : (buf, Ok(bytes.len()))
748 : }
749 0 : Err(e) => (buf, Err(e)),
750 : }
751 12 : }
752 : }
753 :
754 : impl Drop for MockReadAt {
755 8 : fn drop(&mut self) {
756 8 : assert_eq!(self.expectations.len(), 0);
757 8 : }
758 : }
759 :
760 2 : #[tokio::test]
761 2 : async fn test_basic() {
762 2 : let buf = Vec::with_capacity(5);
763 2 : let mock_read_at = Arc::new(tokio::sync::Mutex::new(MockReadAt {
764 2 : expectations: VecDeque::from(vec![Expectation {
765 2 : offset: 0,
766 2 : bytes_total: 5,
767 2 : result: Ok(vec![b'a', b'b', b'c', b'd', b'e']),
768 2 : }]),
769 2 : }));
770 2 : let (buf, res) = read_exact_at_impl(buf, 0, |buf, offset| {
771 2 : let mock_read_at = Arc::clone(&mock_read_at);
772 2 : async move { mock_read_at.lock().await.read_at(buf, offset).await }
773 2 : })
774 2 : .await;
775 2 : assert!(res.is_ok());
776 2 : assert_eq!(buf, vec![b'a', b'b', b'c', b'd', b'e']);
777 2 : }
778 :
779 2 : #[tokio::test]
780 2 : async fn test_empty_buf_issues_no_syscall() {
781 2 : let buf = Vec::new();
782 2 : let mock_read_at = Arc::new(tokio::sync::Mutex::new(MockReadAt {
783 2 : expectations: VecDeque::new(),
784 2 : }));
785 2 : let (_buf, res) = read_exact_at_impl(buf, 0, |buf, offset| {
786 0 : let mock_read_at = Arc::clone(&mock_read_at);
787 2 : async move { mock_read_at.lock().await.read_at(buf, offset).await }
788 2 : })
789 2 : .await;
790 2 : assert!(res.is_ok());
791 2 : }
792 :
793 2 : #[tokio::test]
794 2 : async fn test_two_read_at_calls_needed_until_buf_filled() {
795 2 : let buf = Vec::with_capacity(4);
796 2 : let mock_read_at = Arc::new(tokio::sync::Mutex::new(MockReadAt {
797 2 : expectations: VecDeque::from(vec![
798 2 : Expectation {
799 2 : offset: 0,
800 2 : bytes_total: 4,
801 2 : result: Ok(vec![b'a', b'b']),
802 2 : },
803 2 : Expectation {
804 2 : offset: 2,
805 2 : bytes_total: 2,
806 2 : result: Ok(vec![b'c', b'd']),
807 2 : },
808 2 : ]),
809 2 : }));
810 4 : let (buf, res) = read_exact_at_impl(buf, 0, |buf, offset| {
811 4 : let mock_read_at = Arc::clone(&mock_read_at);
812 4 : async move { mock_read_at.lock().await.read_at(buf, offset).await }
813 4 : })
814 2 : .await;
815 2 : assert!(res.is_ok());
816 2 : assert_eq!(buf, vec![b'a', b'b', b'c', b'd']);
817 2 : }
818 :
819 2 : #[tokio::test]
820 2 : async fn test_eof_before_buffer_full() {
821 2 : let buf = Vec::with_capacity(3);
822 2 : let mock_read_at = Arc::new(tokio::sync::Mutex::new(MockReadAt {
823 2 : expectations: VecDeque::from(vec![
824 2 : Expectation {
825 2 : offset: 0,
826 2 : bytes_total: 3,
827 2 : result: Ok(vec![b'a']),
828 2 : },
829 2 : Expectation {
830 2 : offset: 1,
831 2 : bytes_total: 2,
832 2 : result: Ok(vec![b'b']),
833 2 : },
834 2 : Expectation {
835 2 : offset: 2,
836 2 : bytes_total: 1,
837 2 : result: Ok(vec![]),
838 2 : },
839 2 : ]),
840 2 : }));
841 6 : let (_buf, res) = read_exact_at_impl(buf, 0, |buf, offset| {
842 6 : let mock_read_at = Arc::clone(&mock_read_at);
843 6 : async move { mock_read_at.lock().await.read_at(buf, offset).await }
844 6 : })
845 2 : .await;
846 2 : let Err(err) = res else {
847 2 : panic!("should return an error");
848 2 : };
849 2 : assert_eq!(err.kind(), std::io::ErrorKind::UnexpectedEof);
850 2 : assert_eq!(format!("{err}"), "failed to fill whole buffer");
851 2 : // buffer contents on error are unspecified
852 2 : }
853 : }
854 :
855 : struct FileGuard {
856 : slot_guard: RwLockReadGuard<'static, SlotInner>,
857 : }
858 :
859 : impl AsRef<OwnedFd> for FileGuard {
860 14199314 : fn as_ref(&self) -> &OwnedFd {
861 14199314 : // This unwrap is safe because we only create `FileGuard`s
862 14199314 : // if we know that the file is Some.
863 14199314 : self.slot_guard.file.as_ref().unwrap()
864 14199314 : }
865 : }
866 :
867 : impl FileGuard {
868 : /// Soft deprecation: we'll move VirtualFile to async APIs and remove this function eventually.
869 14054336 : fn with_std_file<F, R>(&self, with: F) -> R
870 14054336 : where
871 14054336 : F: FnOnce(&File) -> R,
872 14054336 : {
873 14054336 : // SAFETY:
874 14054336 : // - lifetime of the fd: `file` doesn't outlive the OwnedFd stored in `self`.
875 14054336 : // - `&` usage below: `self` is `&`, hence Rust typesystem guarantees there are is no `&mut`
876 14054336 : let file = unsafe { File::from_raw_fd(self.as_ref().as_raw_fd()) };
877 14054336 : let res = with(&file);
878 14054336 : let _ = file.into_raw_fd();
879 14054336 : res
880 14054336 : }
881 : /// Soft deprecation: we'll move VirtualFile to async APIs and remove this function eventually.
882 4 : fn with_std_file_mut<F, R>(&mut self, with: F) -> R
883 4 : where
884 4 : F: FnOnce(&mut File) -> R,
885 4 : {
886 4 : // SAFETY:
887 4 : // - lifetime of the fd: `file` doesn't outlive the OwnedFd stored in `self`.
888 4 : // - &mut usage below: `self` is `&mut`, hence this call is the only task/thread that has control over the underlying fd
889 4 : let mut file = unsafe { File::from_raw_fd(self.as_ref().as_raw_fd()) };
890 4 : let res = with(&mut file);
891 4 : let _ = file.into_raw_fd();
892 4 : res
893 4 : }
894 : }
895 :
896 : impl tokio_epoll_uring::IoFd for FileGuard {
897 144971 : unsafe fn as_fd(&self) -> RawFd {
898 144971 : let owned_fd: &OwnedFd = self.as_ref();
899 144971 : owned_fd.as_raw_fd()
900 144971 : }
901 : }
902 :
903 : #[cfg(test)]
904 : impl VirtualFile {
905 20200 : pub(crate) async fn read_blk(
906 20200 : &self,
907 20200 : blknum: u32,
908 20200 : ) -> Result<crate::tenant::block_io::BlockLease<'_>, std::io::Error> {
909 20200 : use crate::page_cache::PAGE_SZ;
910 20200 : let buf = vec![0; PAGE_SZ];
911 20200 : let buf = self
912 20200 : .read_exact_at(buf, blknum as u64 * (PAGE_SZ as u64))
913 10256 : .await?;
914 20200 : Ok(crate::tenant::block_io::BlockLease::Vec(buf))
915 20200 : }
916 :
917 224 : async fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<(), Error> {
918 224 : let mut tmp = vec![0; 128];
919 : loop {
920 : let res;
921 444 : (tmp, res) = self.read_at(tmp, self.pos).await;
922 2 : match res {
923 222 : Ok(0) => return Ok(()),
924 220 : Ok(n) => {
925 220 : self.pos += n as u64;
926 220 : buf.extend_from_slice(&tmp[..n]);
927 220 : }
928 2 : Err(ref e) if e.kind() == std::io::ErrorKind::Interrupted => {}
929 2 : Err(e) => return Err(e),
930 : }
931 : }
932 224 : }
933 : }
934 :
935 : impl Drop for VirtualFile {
936 : /// If a VirtualFile is dropped, close the underlying file if it was open.
937 65578 : fn drop(&mut self) {
938 65578 : let handle = self.handle.get_mut();
939 65578 :
940 65578 : fn clean_slot(slot: &Slot, mut slot_guard: RwLockWriteGuard<'_, SlotInner>, tag: u64) {
941 65578 : if slot_guard.tag == tag {
942 65578 : slot.recently_used.store(false, Ordering::Relaxed);
943 65578 : // there is also operation "close-by-replace" for closes done on eviction for
944 65578 : // comparison.
945 65578 : if let Some(fd) = slot_guard.file.take() {
946 55496 : STORAGE_IO_TIME_METRIC
947 55496 : .get(StorageIoOperation::Close)
948 55496 : .observe_closure_duration(|| drop(fd));
949 55496 : }
950 65578 : }
951 65578 : }
952 65578 :
953 65578 : // We don't have async drop so we cannot directly await the lock here.
954 65578 : // Instead, first do a best-effort attempt at closing the underlying
955 65578 : // file descriptor by using `try_write`, and if that fails, spawn
956 65578 : // a tokio task to do it asynchronously: we just want it to be
957 65578 : // cleaned up eventually.
958 65578 : // Most of the time, the `try_lock` should succeed though,
959 65578 : // as we have `&mut self` access. In other words, if the slot
960 65578 : // is still occupied by our file, there should be no access from
961 65578 : // other I/O operations; the only other possible place to lock
962 65578 : // the slot is the lock algorithm looking for free slots.
963 65578 : let slot = &get_open_files().slots[handle.index];
964 65578 : if let Ok(slot_guard) = slot.inner.try_write() {
965 65575 : clean_slot(slot, slot_guard, handle.tag);
966 65575 : } else {
967 3 : let tag = handle.tag;
968 3 : tokio::spawn(async move {
969 3 : let slot_guard = slot.inner.write().await;
970 3 : clean_slot(slot, slot_guard, tag);
971 3 : });
972 3 : };
973 65578 : }
974 : }
975 :
976 : impl OpenFiles {
977 726 : fn new(num_slots: usize) -> OpenFiles {
978 726 : let mut slots = Box::new(Vec::with_capacity(num_slots));
979 63420 : for _ in 0..num_slots {
980 63420 : let slot = Slot {
981 63420 : recently_used: AtomicBool::new(false),
982 63420 : inner: RwLock::new(SlotInner { tag: 0, file: None }),
983 63420 : };
984 63420 : slots.push(slot);
985 63420 : }
986 :
987 726 : OpenFiles {
988 726 : next: AtomicUsize::new(0),
989 726 : slots: Box::leak(slots),
990 726 : }
991 726 : }
992 : }
993 :
994 : ///
995 : /// Initialize the virtual file module. This must be called once at page
996 : /// server startup.
997 : ///
998 : #[cfg(not(test))]
999 624 : pub fn init(num_slots: usize, engine: IoEngineKind) {
1000 624 : if OPEN_FILES.set(OpenFiles::new(num_slots)).is_err() {
1001 0 : panic!("virtual_file::init called twice");
1002 624 : }
1003 624 : io_engine::init(engine);
1004 624 : crate::metrics::virtual_file_descriptor_cache::SIZE_MAX.set(num_slots as u64);
1005 624 : }
1006 :
1007 : const TEST_MAX_FILE_DESCRIPTORS: usize = 10;
1008 :
1009 : // Get a handle to the global slots array.
1010 14344640 : fn get_open_files() -> &'static OpenFiles {
1011 14344640 : //
1012 14344640 : // In unit tests, page server startup doesn't happen and no one calls
1013 14344640 : // virtual_file::init(). Initialize it here, with a small array.
1014 14344640 : //
1015 14344640 : // This applies to the virtual file tests below, but all other unit
1016 14344640 : // tests too, so the virtual file facility is always usable in
1017 14344640 : // unit tests.
1018 14344640 : //
1019 14344640 : if cfg!(test) {
1020 370581 : OPEN_FILES.get_or_init(|| OpenFiles::new(TEST_MAX_FILE_DESCRIPTORS))
1021 : } else {
1022 13974059 : OPEN_FILES.get().expect("virtual_file::init not called yet")
1023 : }
1024 14344640 : }
1025 :
1026 : #[cfg(test)]
1027 : mod tests {
1028 : use super::*;
1029 : use rand::seq::SliceRandom;
1030 : use rand::thread_rng;
1031 : use rand::Rng;
1032 : use std::future::Future;
1033 : use std::io::Write;
1034 : use std::sync::Arc;
1035 :
1036 : enum MaybeVirtualFile {
1037 : VirtualFile(VirtualFile),
1038 : File(File),
1039 : }
1040 :
1041 : impl From<VirtualFile> for MaybeVirtualFile {
1042 6 : fn from(vf: VirtualFile) -> Self {
1043 6 : MaybeVirtualFile::VirtualFile(vf)
1044 6 : }
1045 : }
1046 :
1047 : impl MaybeVirtualFile {
1048 404 : async fn read_exact_at(&self, mut buf: Vec<u8>, offset: u64) -> Result<Vec<u8>, Error> {
1049 404 : match self {
1050 202 : MaybeVirtualFile::VirtualFile(file) => file.read_exact_at(buf, offset).await,
1051 202 : MaybeVirtualFile::File(file) => file.read_exact_at(&mut buf, offset).map(|()| buf),
1052 : }
1053 404 : }
1054 8 : async fn write_all_at(&self, buf: &[u8], offset: u64) -> Result<(), Error> {
1055 8 : match self {
1056 4 : MaybeVirtualFile::VirtualFile(file) => file.write_all_at(buf, offset).await,
1057 4 : MaybeVirtualFile::File(file) => file.write_all_at(buf, offset),
1058 : }
1059 8 : }
1060 36 : async fn seek(&mut self, pos: SeekFrom) -> Result<u64, Error> {
1061 36 : match self {
1062 18 : MaybeVirtualFile::VirtualFile(file) => file.seek(pos).await,
1063 18 : MaybeVirtualFile::File(file) => file.seek(pos),
1064 : }
1065 36 : }
1066 8 : async fn write_all(&mut self, buf: &[u8]) -> Result<(), Error> {
1067 8 : match self {
1068 4 : MaybeVirtualFile::VirtualFile(file) => file.write_all(buf).await,
1069 4 : MaybeVirtualFile::File(file) => file.write_all(buf),
1070 : }
1071 8 : }
1072 :
1073 : // Helper function to slurp contents of a file, starting at the current position,
1074 : // into a string
1075 442 : async fn read_string(&mut self) -> Result<String, Error> {
1076 442 : use std::io::Read;
1077 442 : let mut buf = String::new();
1078 442 : match self {
1079 224 : MaybeVirtualFile::VirtualFile(file) => {
1080 224 : let mut buf = Vec::new();
1081 226 : file.read_to_end(&mut buf).await?;
1082 222 : return Ok(String::from_utf8(buf).unwrap());
1083 : }
1084 218 : MaybeVirtualFile::File(file) => {
1085 218 : file.read_to_string(&mut buf)?;
1086 : }
1087 : }
1088 216 : Ok(buf)
1089 442 : }
1090 :
1091 : // Helper function to slurp a portion of a file into a string
1092 404 : async fn read_string_at(&mut self, pos: u64, len: usize) -> Result<String, Error> {
1093 404 : let buf = vec![0; len];
1094 404 : let buf = self.read_exact_at(buf, pos).await?;
1095 404 : Ok(String::from_utf8(buf).unwrap())
1096 404 : }
1097 : }
1098 :
1099 2 : #[tokio::test]
1100 2 : async fn test_virtual_files() -> anyhow::Result<()> {
1101 2 : // The real work is done in the test_files() helper function. This
1102 2 : // allows us to run the same set of tests against a native File, and
1103 2 : // VirtualFile. We trust the native Files and wouldn't need to test them,
1104 2 : // but this allows us to verify that the operations return the same
1105 2 : // results with VirtualFiles as with native Files. (Except that with
1106 2 : // native files, you will run out of file descriptors if the ulimit
1107 2 : // is low enough.)
1108 206 : test_files("virtual_files", |path, open_options| async move {
1109 206 : let vf = VirtualFile::open_with_options(&path, &open_options).await?;
1110 206 : Ok(MaybeVirtualFile::VirtualFile(vf))
1111 412 : })
1112 526 : .await
1113 2 : }
1114 :
1115 2 : #[tokio::test]
1116 2 : async fn test_physical_files() -> anyhow::Result<()> {
1117 206 : test_files("physical_files", |path, open_options| async move {
1118 206 : Ok(MaybeVirtualFile::File({
1119 206 : let owned_fd = open_options.open(path.as_std_path()).await?;
1120 206 : File::from(owned_fd)
1121 2 : }))
1122 412 : })
1123 104 : .await
1124 2 : }
1125 :
1126 4 : async fn test_files<OF, FT>(testname: &str, openfunc: OF) -> anyhow::Result<()>
1127 4 : where
1128 4 : OF: Fn(Utf8PathBuf, OpenOptions) -> FT,
1129 4 : FT: Future<Output = Result<MaybeVirtualFile, std::io::Error>>,
1130 4 : {
1131 4 : let testdir = crate::config::PageServerConf::test_repo_dir(testname);
1132 4 : std::fs::create_dir_all(&testdir)?;
1133 :
1134 4 : let path_a = testdir.join("file_a");
1135 4 : let mut file_a = openfunc(
1136 4 : path_a.clone(),
1137 4 : OpenOptions::new()
1138 4 : .write(true)
1139 4 : .create(true)
1140 4 : .truncate(true)
1141 4 : .to_owned(),
1142 4 : )
1143 4 : .await?;
1144 4 : file_a.write_all(b"foobar").await?;
1145 :
1146 : // cannot read from a file opened in write-only mode
1147 4 : let _ = file_a.read_string().await.unwrap_err();
1148 :
1149 : // Close the file and re-open for reading
1150 4 : let mut file_a = openfunc(path_a, OpenOptions::new().read(true).to_owned()).await?;
1151 :
1152 : // cannot write to a file opened in read-only mode
1153 4 : let _ = file_a.write_all(b"bar").await.unwrap_err();
1154 4 :
1155 4 : // Try simple read
1156 4 : assert_eq!("foobar", file_a.read_string().await?);
1157 :
1158 : // It's positioned at the EOF now.
1159 4 : assert_eq!("", file_a.read_string().await?);
1160 :
1161 : // Test seeks.
1162 4 : assert_eq!(file_a.seek(SeekFrom::Start(1)).await?, 1);
1163 4 : assert_eq!("oobar", file_a.read_string().await?);
1164 :
1165 4 : assert_eq!(file_a.seek(SeekFrom::End(-2)).await?, 4);
1166 4 : assert_eq!("ar", file_a.read_string().await?);
1167 :
1168 4 : assert_eq!(file_a.seek(SeekFrom::Start(1)).await?, 1);
1169 4 : assert_eq!(file_a.seek(SeekFrom::Current(2)).await?, 3);
1170 4 : assert_eq!("bar", file_a.read_string().await?);
1171 :
1172 4 : assert_eq!(file_a.seek(SeekFrom::Current(-5)).await?, 1);
1173 4 : assert_eq!("oobar", file_a.read_string().await?);
1174 :
1175 : // Test erroneous seeks to before byte 0
1176 4 : file_a.seek(SeekFrom::End(-7)).await.unwrap_err();
1177 4 : assert_eq!(file_a.seek(SeekFrom::Start(1)).await?, 1);
1178 4 : file_a.seek(SeekFrom::Current(-2)).await.unwrap_err();
1179 4 :
1180 4 : // the erroneous seek should have left the position unchanged
1181 4 : assert_eq!("oobar", file_a.read_string().await?);
1182 :
1183 : // Create another test file, and try FileExt functions on it.
1184 4 : let path_b = testdir.join("file_b");
1185 4 : let mut file_b = openfunc(
1186 4 : path_b.clone(),
1187 4 : OpenOptions::new()
1188 4 : .read(true)
1189 4 : .write(true)
1190 4 : .create(true)
1191 4 : .truncate(true)
1192 4 : .to_owned(),
1193 4 : )
1194 2 : .await?;
1195 4 : file_b.write_all_at(b"BAR", 3).await?;
1196 4 : file_b.write_all_at(b"FOO", 0).await?;
1197 :
1198 4 : assert_eq!(file_b.read_string_at(2, 3).await?, "OBA");
1199 :
1200 : // Open a lot of files, enough to cause some evictions. (Or to be precise,
1201 : // open the same file many times. The effect is the same.)
1202 : //
1203 : // leave file_a positioned at offset 1 before we start
1204 4 : assert_eq!(file_a.seek(SeekFrom::Start(1)).await?, 1);
1205 :
1206 4 : let mut vfiles = Vec::new();
1207 404 : for _ in 0..100 {
1208 400 : let mut vfile =
1209 400 : openfunc(path_b.clone(), OpenOptions::new().read(true).to_owned()).await?;
1210 400 : assert_eq!("FOOBAR", vfile.read_string().await?);
1211 400 : vfiles.push(vfile);
1212 : }
1213 :
1214 : // make sure we opened enough files to definitely cause evictions.
1215 4 : assert!(vfiles.len() > TEST_MAX_FILE_DESCRIPTORS * 2);
1216 :
1217 : // The underlying file descriptor for 'file_a' should be closed now. Try to read
1218 : // from it again. We left the file positioned at offset 1 above.
1219 4 : assert_eq!("oobar", file_a.read_string().await?);
1220 :
1221 : // Check that all the other FDs still work too. Use them in random order for
1222 : // good measure.
1223 4 : vfiles.as_mut_slice().shuffle(&mut thread_rng());
1224 400 : for vfile in vfiles.iter_mut() {
1225 400 : assert_eq!("OOBAR", vfile.read_string_at(1, 5).await?);
1226 : }
1227 :
1228 4 : Ok(())
1229 4 : }
1230 :
1231 : /// Test using VirtualFiles from many threads concurrently. This tests both using
1232 : /// a lot of VirtualFiles concurrently, causing evictions, and also using the same
1233 : /// VirtualFile from multiple threads concurrently.
1234 2 : #[tokio::test]
1235 2 : async fn test_vfile_concurrency() -> Result<(), Error> {
1236 2 : const SIZE: usize = 8 * 1024;
1237 2 : const VIRTUAL_FILES: usize = 100;
1238 2 : const THREADS: usize = 100;
1239 2 : const SAMPLE: [u8; SIZE] = [0xADu8; SIZE];
1240 2 :
1241 2 : let testdir = crate::config::PageServerConf::test_repo_dir("vfile_concurrency");
1242 2 : std::fs::create_dir_all(&testdir)?;
1243 2 :
1244 2 : // Create a test file.
1245 2 : let test_file_path = testdir.join("concurrency_test_file");
1246 2 : {
1247 2 : let file = File::create(&test_file_path)?;
1248 2 : file.write_all_at(&SAMPLE, 0)?;
1249 2 : }
1250 2 :
1251 2 : // Open the file many times.
1252 2 : let mut files = Vec::new();
1253 202 : for _ in 0..VIRTUAL_FILES {
1254 200 : let f = VirtualFile::open_with_options(&test_file_path, OpenOptions::new().read(true))
1255 101 : .await?;
1256 200 : files.push(f);
1257 2 : }
1258 2 : let files = Arc::new(files);
1259 2 :
1260 2 : // Launch many threads, and use the virtual files concurrently in random order.
1261 2 : let rt = tokio::runtime::Builder::new_multi_thread()
1262 2 : .worker_threads(THREADS)
1263 2 : .thread_name("test_vfile_concurrency thread")
1264 2 : .build()
1265 2 : .unwrap();
1266 2 : let mut hdls = Vec::new();
1267 202 : for _threadno in 0..THREADS {
1268 200 : let files = files.clone();
1269 200 : let hdl = rt.spawn(async move {
1270 200 : let mut buf = vec![0u8; SIZE];
1271 200 : let mut rng = rand::rngs::OsRng;
1272 200000 : for _ in 1..1000 {
1273 199800 : let f = &files[rng.gen_range(0..files.len())];
1274 586558 : buf = f.read_exact_at(buf, 0).await.unwrap();
1275 199800 : assert!(buf == SAMPLE);
1276 2 : }
1277 200 : });
1278 200 : hdls.push(hdl);
1279 200 : }
1280 202 : for hdl in hdls {
1281 200 : hdl.await?;
1282 2 : }
1283 2 : std::mem::forget(rt);
1284 2 :
1285 2 : Ok(())
1286 2 : }
1287 :
1288 2 : #[tokio::test]
1289 2 : async fn test_atomic_overwrite_basic() {
1290 2 : let testdir = crate::config::PageServerConf::test_repo_dir("test_atomic_overwrite_basic");
1291 2 : std::fs::create_dir_all(&testdir).unwrap();
1292 2 :
1293 2 : let path = testdir.join("myfile");
1294 2 : let tmp_path = testdir.join("myfile.tmp");
1295 2 :
1296 2 : VirtualFile::crashsafe_overwrite(&path, &tmp_path, b"foo")
1297 3 : .await
1298 2 : .unwrap();
1299 2 : let mut file = MaybeVirtualFile::from(VirtualFile::open(&path).await.unwrap());
1300 2 : let post = file.read_string().await.unwrap();
1301 2 : assert_eq!(post, "foo");
1302 2 : assert!(!tmp_path.exists());
1303 2 : drop(file);
1304 2 :
1305 2 : VirtualFile::crashsafe_overwrite(&path, &tmp_path, b"bar")
1306 2 : .await
1307 2 : .unwrap();
1308 2 : let mut file = MaybeVirtualFile::from(VirtualFile::open(&path).await.unwrap());
1309 2 : let post = file.read_string().await.unwrap();
1310 2 : assert_eq!(post, "bar");
1311 2 : assert!(!tmp_path.exists());
1312 2 : drop(file);
1313 2 : }
1314 :
1315 2 : #[tokio::test]
1316 2 : async fn test_atomic_overwrite_preexisting_tmp() {
1317 2 : let testdir =
1318 2 : crate::config::PageServerConf::test_repo_dir("test_atomic_overwrite_preexisting_tmp");
1319 2 : std::fs::create_dir_all(&testdir).unwrap();
1320 2 :
1321 2 : let path = testdir.join("myfile");
1322 2 : let tmp_path = testdir.join("myfile.tmp");
1323 2 :
1324 2 : std::fs::write(&tmp_path, "some preexisting junk that should be removed").unwrap();
1325 2 : assert!(tmp_path.exists());
1326 2 :
1327 2 : VirtualFile::crashsafe_overwrite(&path, &tmp_path, b"foo")
1328 3 : .await
1329 2 : .unwrap();
1330 2 :
1331 2 : let mut file = MaybeVirtualFile::from(VirtualFile::open(&path).await.unwrap());
1332 2 : let post = file.read_string().await.unwrap();
1333 2 : assert_eq!(post, "foo");
1334 2 : assert!(!tmp_path.exists());
1335 2 : drop(file);
1336 2 : }
1337 : }
|