LCOV - code coverage report
Current view: top level - pageserver/src/tenant - block_io.rs (source / functions) Coverage Total Hit
Test: b837401fb09d2d9818b70e630fdb67e9799b7b0d.info Lines: 87.5 % 96 84
Test Date: 2024-04-18 15:32:49 Functions: 85.7 % 21 18

            Line data    Source code
       1              : //!
       2              : //! Low-level Block-oriented I/O functions
       3              : //!
       4              : 
       5              : use super::ephemeral_file::EphemeralFile;
       6              : use super::storage_layer::delta_layer::{Adapter, DeltaLayerInner};
       7              : use crate::context::RequestContext;
       8              : use crate::page_cache::{self, FileId, PageReadGuard, PageWriteGuard, ReadBufResult, PAGE_SZ};
       9              : use crate::virtual_file::VirtualFile;
      10              : use bytes::Bytes;
      11              : use std::ops::Deref;
      12              : 
      13              : /// This is implemented by anything that can read 8 kB (PAGE_SZ)
      14              : /// blocks, using the page cache
      15              : ///
      16              : /// There are currently two implementations: EphemeralFile, and FileBlockReader
      17              : /// below.
      18              : pub trait BlockReader {
      19              :     ///
      20              :     /// Create a new "cursor" for reading from this reader.
      21              :     ///
      22              :     /// A cursor caches the last accessed page, allowing for faster
      23              :     /// access if the same block is accessed repeatedly.
      24              :     fn block_cursor(&self) -> BlockCursor<'_>;
      25              : }
      26              : 
      27              : impl<B> BlockReader for &B
      28              : where
      29              :     B: BlockReader,
      30              : {
      31       123788 :     fn block_cursor(&self) -> BlockCursor<'_> {
      32       123788 :         (*self).block_cursor()
      33       123788 :     }
      34              : }
      35              : 
      36              : /// Reference to an in-memory copy of an immutable on-disk block.
      37              : pub enum BlockLease<'a> {
      38              :     PageReadGuard(PageReadGuard<'static>),
      39              :     EphemeralFileMutableTail(&'a [u8; PAGE_SZ]),
      40              :     #[cfg(test)]
      41              :     Arc(std::sync::Arc<[u8; PAGE_SZ]>),
      42              :     #[cfg(test)]
      43              :     Vec(Vec<u8>),
      44              : }
      45              : 
      46              : impl From<PageReadGuard<'static>> for BlockLease<'static> {
      47      3478960 :     fn from(value: PageReadGuard<'static>) -> BlockLease<'static> {
      48      3478960 :         BlockLease::PageReadGuard(value)
      49      3478960 :     }
      50              : }
      51              : 
      52              : #[cfg(test)]
      53              : impl<'a> From<std::sync::Arc<[u8; PAGE_SZ]>> for BlockLease<'a> {
      54      1016254 :     fn from(value: std::sync::Arc<[u8; PAGE_SZ]>) -> Self {
      55      1016254 :         BlockLease::Arc(value)
      56      1016254 :     }
      57              : }
      58              : 
      59              : impl<'a> Deref for BlockLease<'a> {
      60              :     type Target = [u8; PAGE_SZ];
      61              : 
      62     15132117 :     fn deref(&self) -> &Self::Target {
      63     15132117 :         match self {
      64     13429005 :             BlockLease::PageReadGuard(v) => v.deref(),
      65       652350 :             BlockLease::EphemeralFileMutableTail(v) => v,
      66              :             #[cfg(test)]
      67      1016254 :             BlockLease::Arc(v) => v.deref(),
      68              :             #[cfg(test)]
      69        34508 :             BlockLease::Vec(v) => {
      70        34508 :                 TryFrom::try_from(&v[..]).expect("caller must ensure that v has PAGE_SZ")
      71              :             }
      72              :         }
      73     15132117 :     }
      74              : }
      75              : 
      76              : /// Provides the ability to read blocks from different sources,
      77              : /// similar to using traits for this purpose.
      78              : ///
      79              : /// Unlike traits, we also support the read function to be async though.
      80              : pub(crate) enum BlockReaderRef<'a> {
      81              :     FileBlockReader(&'a FileBlockReader<'a>),
      82              :     EphemeralFile(&'a EphemeralFile),
      83              :     Adapter(Adapter<&'a DeltaLayerInner>),
      84              :     #[cfg(test)]
      85              :     TestDisk(&'a super::disk_btree::tests::TestDisk),
      86              :     #[cfg(test)]
      87              :     VirtualFile(&'a VirtualFile),
      88              : }
      89              : 
      90              : impl<'a> BlockReaderRef<'a> {
      91              :     #[inline(always)]
      92      8234634 :     async fn read_blk(
      93      8234634 :         &self,
      94      8234634 :         blknum: u32,
      95      8234634 :         ctx: &RequestContext,
      96      8234634 :     ) -> Result<BlockLease, std::io::Error> {
      97      8234634 :         use BlockReaderRef::*;
      98      8234634 :         match self {
      99       327646 :             FileBlockReader(r) => r.read_blk(blknum, ctx).await,
     100      3719850 :             EphemeralFile(r) => r.read_blk(blknum, ctx).await,
     101      3150684 :             Adapter(r) => r.read_blk(blknum, ctx).await,
     102              :             #[cfg(test)]
     103      1016254 :             TestDisk(r) => r.read_blk(blknum),
     104              :             #[cfg(test)]
     105        20200 :             VirtualFile(r) => r.read_blk(blknum).await,
     106              :         }
     107      8234634 :     }
     108              : }
     109              : 
     110              : ///
     111              : /// A "cursor" for efficiently reading multiple pages from a BlockReader
     112              : ///
     113              : /// You can access the last page with `*cursor`. 'read_blk' returns 'self', so
     114              : /// that in many cases you can use a BlockCursor as a drop-in replacement for
     115              : /// the underlying BlockReader. For example:
     116              : ///
     117              : /// ```no_run
     118              : /// # use pageserver::tenant::block_io::{BlockReader, FileBlockReader};
     119              : /// # use pageserver::context::RequestContext;
     120              : /// # let reader: FileBlockReader = unimplemented!("stub");
     121              : /// # let ctx: RequestContext = unimplemented!("stub");
     122              : /// let cursor = reader.block_cursor();
     123              : /// let buf = cursor.read_blk(1, &ctx);
     124              : /// // do stuff with 'buf'
     125              : /// let buf = cursor.read_blk(2, &ctx);
     126              : /// // do stuff with 'buf'
     127              : /// ```
     128              : ///
     129              : pub struct BlockCursor<'a> {
     130              :     reader: BlockReaderRef<'a>,
     131              : }
     132              : 
     133              : impl<'a> BlockCursor<'a> {
     134      4285749 :     pub(crate) fn new(reader: BlockReaderRef<'a>) -> Self {
     135      4285749 :         BlockCursor { reader }
     136      4285749 :     }
     137              :     // Needed by cli
     138            0 :     pub fn new_fileblockreader(reader: &'a FileBlockReader) -> Self {
     139            0 :         BlockCursor {
     140            0 :             reader: BlockReaderRef::FileBlockReader(reader),
     141            0 :         }
     142            0 :     }
     143              : 
     144              :     /// Read a block.
     145              :     ///
     146              :     /// Returns a "lease" object that can be used to
     147              :     /// access to the contents of the page. (For the page cache, the
     148              :     /// lease object represents a lock on the buffer.)
     149              :     #[inline(always)]
     150      8234634 :     pub async fn read_blk(
     151      8234634 :         &self,
     152      8234634 :         blknum: u32,
     153      8234634 :         ctx: &RequestContext,
     154      8234634 :     ) -> Result<BlockLease, std::io::Error> {
     155      8234634 :         self.reader.read_blk(blknum, ctx).await
     156      8234634 :     }
     157              : }
     158              : 
     159              : /// An adapter for reading a (virtual) file using the page cache.
     160              : ///
     161              : /// The file is assumed to be immutable. This doesn't provide any functions
     162              : /// for modifying the file, nor for invalidating the cache if it is modified.
     163              : pub struct FileBlockReader<'a> {
     164              :     pub file: &'a VirtualFile,
     165              : 
     166              :     /// Unique ID of this file, used as key in the page cache.
     167              :     file_id: page_cache::FileId,
     168              : }
     169              : 
     170              : impl<'a> FileBlockReader<'a> {
     171      3275780 :     pub fn new(file: &'a VirtualFile, file_id: FileId) -> Self {
     172      3275780 :         FileBlockReader { file_id, file }
     173      3275780 :     }
     174              : 
     175              :     /// Read a page from the underlying file into given buffer.
     176        64607 :     async fn fill_buffer(
     177        64607 :         &self,
     178        64607 :         buf: PageWriteGuard<'static>,
     179        64607 :         blkno: u32,
     180        64607 :     ) -> Result<PageWriteGuard<'static>, std::io::Error> {
     181        64607 :         assert!(buf.len() == PAGE_SZ);
     182        64607 :         self.file
     183        64607 :             .read_exact_at_page(buf, blkno as u64 * PAGE_SZ as u64)
     184        38397 :             .await
     185        64607 :     }
     186              :     /// Read a block.
     187              :     ///
     188              :     /// Returns a "lease" object that can be used to
     189              :     /// access to the contents of the page. (For the page cache, the
     190              :     /// lease object represents a lock on the buffer.)
     191      3478960 :     pub async fn read_blk<'b>(
     192      3478960 :         &self,
     193      3478960 :         blknum: u32,
     194      3478960 :         ctx: &RequestContext,
     195      3478960 :     ) -> Result<BlockLease<'b>, std::io::Error> {
     196      3478960 :         let cache = page_cache::get();
     197      3478960 :         match cache
     198      3478960 :             .read_immutable_buf(self.file_id, blknum, ctx)
     199        42780 :             .await
     200      3478960 :             .map_err(|e| {
     201            0 :                 std::io::Error::new(
     202            0 :                     std::io::ErrorKind::Other,
     203            0 :                     format!("Failed to read immutable buf: {e:#}"),
     204            0 :                 )
     205      3478960 :             })? {
     206      3414353 :             ReadBufResult::Found(guard) => Ok(guard.into()),
     207        64607 :             ReadBufResult::NotFound(write_guard) => {
     208              :                 // Read the page from disk into the buffer
     209        64607 :                 let write_guard = self.fill_buffer(write_guard, blknum).await?;
     210        64607 :                 Ok(write_guard.mark_valid().into())
     211              :             }
     212              :         }
     213      3478960 :     }
     214              : }
     215              : 
     216              : impl BlockReader for FileBlockReader<'_> {
     217       248494 :     fn block_cursor(&self) -> BlockCursor<'_> {
     218       248494 :         BlockCursor::new(BlockReaderRef::FileBlockReader(self))
     219       248494 :     }
     220              : }
     221              : 
     222              : ///
     223              : /// Trait for block-oriented output
     224              : ///
     225              : pub trait BlockWriter {
     226              :     ///
     227              :     /// Write a page to the underlying storage.
     228              :     ///
     229              :     /// 'buf' must be of size PAGE_SZ. Returns the block number the page was
     230              :     /// written to.
     231              :     ///
     232              :     fn write_blk(&mut self, buf: Bytes) -> Result<u32, std::io::Error>;
     233              : }
     234              : 
     235              : ///
     236              : /// A simple in-memory buffer of blocks.
     237              : ///
     238              : pub struct BlockBuf {
     239              :     pub blocks: Vec<Bytes>,
     240              : }
     241              : impl BlockWriter for BlockBuf {
     242        12862 :     fn write_blk(&mut self, buf: Bytes) -> Result<u32, std::io::Error> {
     243        12862 :         assert!(buf.len() == PAGE_SZ);
     244        12862 :         let blknum = self.blocks.len();
     245        12862 :         self.blocks.push(buf);
     246        12862 :         Ok(blknum as u32)
     247        12862 :     }
     248              : }
     249              : 
     250              : impl BlockBuf {
     251          960 :     pub fn new() -> Self {
     252          960 :         BlockBuf { blocks: Vec::new() }
     253          960 :     }
     254              : 
     255      3029956 :     pub fn size(&self) -> u64 {
     256      3029956 :         (self.blocks.len() * PAGE_SZ) as u64
     257      3029956 :     }
     258              : }
     259              : impl Default for BlockBuf {
     260            0 :     fn default() -> Self {
     261            0 :         Self::new()
     262            0 :     }
     263              : }
        

Generated by: LCOV version 2.1-beta