LCOV - code coverage report
Current view: top level - pageserver/src/tenant - block_io.rs (source / functions) Coverage Total Hit
Test: 465a86b0c1fda0069b3e0f6c1c126e6b635a1f72.info Lines: 87.6 % 97 85
Test Date: 2024-06-25 15:47:26 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       211122 :     fn block_cursor(&self) -> BlockCursor<'_> {
      32       211122 :         (*self).block_cursor()
      33       211122 :     }
      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      2739887 :     fn from(value: PageReadGuard<'static>) -> BlockLease<'static> {
      48      2739887 :         BlockLease::PageReadGuard(value)
      49      2739887 :     }
      50              : }
      51              : 
      52              : #[cfg(test)]
      53              : impl<'a> From<std::sync::Arc<[u8; PAGE_SZ]>> for BlockLease<'a> {
      54      1016718 :     fn from(value: std::sync::Arc<[u8; PAGE_SZ]>) -> Self {
      55      1016718 :         BlockLease::Arc(value)
      56      1016718 :     }
      57              : }
      58              : 
      59              : impl<'a> Deref for BlockLease<'a> {
      60              :     type Target = [u8; PAGE_SZ];
      61              : 
      62     15852814 :     fn deref(&self) -> &Self::Target {
      63     15852814 :         match self {
      64     13498710 :             BlockLease::PageReadGuard(v) => v.deref(),
      65      1302878 :             BlockLease::EphemeralFileMutableTail(v) => v,
      66              :             #[cfg(test)]
      67      1016718 :             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     15852814 :     }
      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      8731616 :     async fn read_blk(
      93      8731616 :         &self,
      94      8731616 :         blknum: u32,
      95      8731616 :         ctx: &RequestContext,
      96      8731616 :     ) -> Result<BlockLease, std::io::Error> {
      97      8731616 :         use BlockReaderRef::*;
      98      8731616 :         match self {
      99       655799 :             FileBlockReader(r) => r.read_blk(blknum, ctx).await,
     100      4955897 :             EphemeralFile(r) => r.read_blk(blknum, ctx).await,
     101      2083002 :             Adapter(r) => r.read_blk(blknum, ctx).await,
     102              :             #[cfg(test)]
     103      1016718 :             TestDisk(r) => r.read_blk(blknum),
     104              :             #[cfg(test)]
     105        20200 :             VirtualFile(r) => r.read_blk(blknum, ctx).await,
     106              :         }
     107      8731616 :     }
     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      3569561 :     pub(crate) fn new(reader: BlockReaderRef<'a>) -> Self {
     135      3569561 :         BlockCursor { reader }
     136      3569561 :     }
     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      8731616 :     pub async fn read_blk(
     151      8731616 :         &self,
     152      8731616 :         blknum: u32,
     153      8731616 :         ctx: &RequestContext,
     154      8731616 :     ) -> Result<BlockLease, std::io::Error> {
     155      8731616 :         self.reader.read_blk(blknum, ctx).await
     156      8731616 :     }
     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      2296090 :     pub fn new(file: &'a VirtualFile, file_id: FileId) -> Self {
     172      2296090 :         FileBlockReader { file_id, file }
     173      2296090 :     }
     174              : 
     175              :     /// Read a page from the underlying file into given buffer.
     176        60076 :     async fn fill_buffer(
     177        60076 :         &self,
     178        60076 :         buf: PageWriteGuard<'static>,
     179        60076 :         blkno: u32,
     180        60076 :         ctx: &RequestContext,
     181        60076 :     ) -> Result<PageWriteGuard<'static>, std::io::Error> {
     182        60076 :         assert!(buf.len() == PAGE_SZ);
     183        60076 :         self.file
     184        60076 :             .read_exact_at_page(buf, blkno as u64 * PAGE_SZ as u64, ctx)
     185        36563 :             .await
     186        60076 :     }
     187              :     /// Read a block.
     188              :     ///
     189              :     /// Returns a "lease" object that can be used to
     190              :     /// access to the contents of the page. (For the page cache, the
     191              :     /// lease object represents a lock on the buffer.)
     192      2739887 :     pub async fn read_blk<'b>(
     193      2739887 :         &self,
     194      2739887 :         blknum: u32,
     195      2739887 :         ctx: &RequestContext,
     196      2739887 :     ) -> Result<BlockLease<'b>, std::io::Error> {
     197      2739887 :         let cache = page_cache::get();
     198      2739887 :         match cache
     199      2739887 :             .read_immutable_buf(self.file_id, blknum, ctx)
     200        34001 :             .await
     201      2739887 :             .map_err(|e| {
     202            0 :                 std::io::Error::new(
     203            0 :                     std::io::ErrorKind::Other,
     204            0 :                     format!("Failed to read immutable buf: {e:#}"),
     205            0 :                 )
     206      2739887 :             })? {
     207      2679811 :             ReadBufResult::Found(guard) => Ok(guard.into()),
     208        60076 :             ReadBufResult::NotFound(write_guard) => {
     209              :                 // Read the page from disk into the buffer
     210        60076 :                 let write_guard = self.fill_buffer(write_guard, blknum, ctx).await?;
     211        60076 :                 Ok(write_guard.mark_valid().into())
     212              :             }
     213              :         }
     214      2739887 :     }
     215              : }
     216              : 
     217              : impl BlockReader for FileBlockReader<'_> {
     218       487050 :     fn block_cursor(&self) -> BlockCursor<'_> {
     219       487050 :         BlockCursor::new(BlockReaderRef::FileBlockReader(self))
     220       487050 :     }
     221              : }
     222              : 
     223              : ///
     224              : /// Trait for block-oriented output
     225              : ///
     226              : pub trait BlockWriter {
     227              :     ///
     228              :     /// Write a page to the underlying storage.
     229              :     ///
     230              :     /// 'buf' must be of size PAGE_SZ. Returns the block number the page was
     231              :     /// written to.
     232              :     ///
     233              :     fn write_blk(&mut self, buf: Bytes) -> Result<u32, std::io::Error>;
     234              : }
     235              : 
     236              : ///
     237              : /// A simple in-memory buffer of blocks.
     238              : ///
     239              : pub struct BlockBuf {
     240              :     pub blocks: Vec<Bytes>,
     241              : }
     242              : impl BlockWriter for BlockBuf {
     243        14223 :     fn write_blk(&mut self, buf: Bytes) -> Result<u32, std::io::Error> {
     244        14223 :         assert!(buf.len() == PAGE_SZ);
     245        14223 :         let blknum = self.blocks.len();
     246        14223 :         self.blocks.push(buf);
     247        14223 :         Ok(blknum as u32)
     248        14223 :     }
     249              : }
     250              : 
     251              : impl BlockBuf {
     252         1564 :     pub fn new() -> Self {
     253         1564 :         BlockBuf { blocks: Vec::new() }
     254         1564 :     }
     255              : 
     256      2023972 :     pub fn size(&self) -> u64 {
     257      2023972 :         (self.blocks.len() * PAGE_SZ) as u64
     258      2023972 :     }
     259              : }
     260              : impl Default for BlockBuf {
     261            0 :     fn default() -> Self {
     262            0 :         Self::new()
     263            0 :     }
     264              : }
        

Generated by: LCOV version 2.1-beta