LCOV - code coverage report
Current view: top level - pageserver/src - lib.rs (source / functions) Coverage Total Hit
Test: fabb29a6339542ee130cd1d32b534fafdc0be240.info Lines: 86.4 % 66 57
Test Date: 2024-06-25 13:20:00 Functions: 63.2 % 19 12

            Line data    Source code
       1              : #![recursion_limit = "300"]
       2              : #![deny(clippy::undocumented_unsafe_blocks)]
       3              : 
       4              : mod auth;
       5              : pub mod basebackup;
       6              : pub mod config;
       7              : pub mod consumption_metrics;
       8              : pub mod context;
       9              : pub mod control_plane_client;
      10              : pub mod deletion_queue;
      11              : pub mod disk_usage_eviction_task;
      12              : pub mod http;
      13              : pub mod import_datadir;
      14              : pub use pageserver_api::keyspace;
      15              : pub mod aux_file;
      16              : pub mod metrics;
      17              : pub mod page_cache;
      18              : pub mod page_service;
      19              : pub mod pgdatadir_mapping;
      20              : pub mod repository;
      21              : pub mod span;
      22              : pub(crate) mod statvfs;
      23              : pub mod task_mgr;
      24              : pub mod tenant;
      25              : pub mod trace;
      26              : pub mod utilization;
      27              : pub mod virtual_file;
      28              : pub mod walingest;
      29              : pub mod walrecord;
      30              : pub mod walredo;
      31              : 
      32              : use crate::task_mgr::TaskKind;
      33              : use camino::Utf8Path;
      34              : use deletion_queue::DeletionQueue;
      35              : use tenant::mgr::TenantManager;
      36              : use tracing::info;
      37              : 
      38              : /// Current storage format version
      39              : ///
      40              : /// This is embedded in the header of all the layer files.
      41              : /// If you make any backwards-incompatible changes to the storage
      42              : /// format, bump this!
      43              : /// Note that TimelineMetadata uses its own version number to track
      44              : /// backwards-compatible changes to the metadata format.
      45              : pub const STORAGE_FORMAT_VERSION: u16 = 3;
      46              : 
      47              : pub const DEFAULT_PG_VERSION: u32 = 15;
      48              : 
      49              : // Magic constants used to identify different kinds of files
      50              : pub const IMAGE_FILE_MAGIC: u16 = 0x5A60;
      51              : pub const DELTA_FILE_MAGIC: u16 = 0x5A61;
      52              : 
      53              : static ZERO_PAGE: bytes::Bytes = bytes::Bytes::from_static(&[0u8; 8192]);
      54              : 
      55              : pub use crate::metrics::preinitialize_metrics;
      56              : 
      57            0 : #[tracing::instrument(skip_all, fields(%exit_code))]
      58              : pub async fn shutdown_pageserver(
      59              :     tenant_manager: &TenantManager,
      60              :     mut deletion_queue: DeletionQueue,
      61              :     exit_code: i32,
      62              : ) {
      63              :     use std::time::Duration;
      64              :     // Shut down the libpq endpoint task. This prevents new connections from
      65              :     // being accepted.
      66              :     timed(
      67              :         task_mgr::shutdown_tasks(Some(TaskKind::LibpqEndpointListener), None, None),
      68              :         "shutdown LibpqEndpointListener",
      69              :         Duration::from_secs(1),
      70              :     )
      71              :     .await;
      72              : 
      73              :     // Shut down all the tenants. This flushes everything to disk and kills
      74              :     // the checkpoint and GC tasks.
      75              :     timed(
      76              :         tenant_manager.shutdown(),
      77              :         "shutdown all tenants",
      78              :         Duration::from_secs(5),
      79              :     )
      80              :     .await;
      81              : 
      82              :     // Shut down any page service tasks: any in-progress work for particular timelines or tenants
      83              :     // should already have been canclled via mgr::shutdown_all_tenants
      84              :     timed(
      85              :         task_mgr::shutdown_tasks(Some(TaskKind::PageRequestHandler), None, None),
      86              :         "shutdown PageRequestHandlers",
      87              :         Duration::from_secs(1),
      88              :     )
      89              :     .await;
      90              : 
      91              :     // Best effort to persist any outstanding deletions, to avoid leaking objects
      92              :     deletion_queue.shutdown(Duration::from_secs(5)).await;
      93              : 
      94              :     // Shut down the HTTP endpoint last, so that you can still check the server's
      95              :     // status while it's shutting down.
      96              :     // FIXME: We should probably stop accepting commands like attach/detach earlier.
      97              :     timed(
      98              :         task_mgr::shutdown_tasks(Some(TaskKind::HttpEndpointListener), None, None),
      99              :         "shutdown http",
     100              :         Duration::from_secs(1),
     101              :     )
     102              :     .await;
     103              : 
     104              :     // There should be nothing left, but let's be sure
     105              :     timed(
     106              :         task_mgr::shutdown_tasks(None, None, None),
     107              :         "shutdown leftovers",
     108              :         Duration::from_secs(1),
     109              :     )
     110              :     .await;
     111              :     info!("Shut down successfully completed");
     112              :     std::process::exit(exit_code);
     113              : }
     114              : 
     115              : /// Per-tenant configuration file.
     116              : /// Full path: `tenants/<tenant_id>/config`.
     117              : pub(crate) const TENANT_CONFIG_NAME: &str = "config";
     118              : 
     119              : /// Per-tenant configuration file.
     120              : /// Full path: `tenants/<tenant_id>/config`.
     121              : pub(crate) const TENANT_LOCATION_CONFIG_NAME: &str = "config-v1";
     122              : 
     123              : /// Per-tenant copy of their remote heatmap, downloaded into the local
     124              : /// tenant path while in secondary mode.
     125              : pub(crate) const TENANT_HEATMAP_BASENAME: &str = "heatmap-v1.json";
     126              : 
     127              : /// A suffix used for various temporary files. Any temporary files found in the
     128              : /// data directory at pageserver startup can be automatically removed.
     129              : pub(crate) const TEMP_FILE_SUFFIX: &str = "___temp";
     130              : 
     131              : /// A marker file to mark that a timeline directory was not fully initialized.
     132              : /// If a timeline directory with this marker is encountered at pageserver startup,
     133              : /// the timeline directory and the marker file are both removed.
     134              : /// Full path: `tenants/<tenant_id>/timelines/<timeline_id>___uninit`.
     135              : pub(crate) const TIMELINE_UNINIT_MARK_SUFFIX: &str = "___uninit";
     136              : 
     137              : pub(crate) const TIMELINE_DELETE_MARK_SUFFIX: &str = "___delete";
     138              : 
     139            8 : pub fn is_temporary(path: &Utf8Path) -> bool {
     140            8 :     match path.file_name() {
     141            8 :         Some(name) => name.ends_with(TEMP_FILE_SUFFIX),
     142            0 :         None => false,
     143              :     }
     144            8 : }
     145              : 
     146           16 : fn ends_with_suffix(path: &Utf8Path, suffix: &str) -> bool {
     147           16 :     match path.file_name() {
     148           16 :         Some(name) => name.ends_with(suffix),
     149            0 :         None => false,
     150              :     }
     151           16 : }
     152              : 
     153              : // FIXME: DO NOT ADD new query methods like this, which will have a next step of parsing timelineid
     154              : // from the directory name. Instead create type "UninitMark(TimelineId)" and only parse it once
     155              : // from the name.
     156              : 
     157            8 : pub(crate) fn is_uninit_mark(path: &Utf8Path) -> bool {
     158            8 :     ends_with_suffix(path, TIMELINE_UNINIT_MARK_SUFFIX)
     159            8 : }
     160              : 
     161            8 : pub(crate) fn is_delete_mark(path: &Utf8Path) -> bool {
     162            8 :     ends_with_suffix(path, TIMELINE_DELETE_MARK_SUFFIX)
     163            8 : }
     164              : 
     165              : /// During pageserver startup, we need to order operations not to exhaust tokio worker threads by
     166              : /// blocking.
     167              : ///
     168              : /// The instances of this value exist only during startup, otherwise `None` is provided, meaning no
     169              : /// delaying is needed.
     170              : #[derive(Clone)]
     171              : pub struct InitializationOrder {
     172              :     /// Each initial tenant load task carries this until it is done loading timelines from remote storage
     173              :     pub initial_tenant_load_remote: Option<utils::completion::Completion>,
     174              : 
     175              :     /// Each initial tenant load task carries this until completion.
     176              :     pub initial_tenant_load: Option<utils::completion::Completion>,
     177              : 
     178              :     /// Barrier for when we can start any background jobs.
     179              :     ///
     180              :     /// This can be broken up later on, but right now there is just one class of a background job.
     181              :     pub background_jobs_can_start: utils::completion::Barrier,
     182              : }
     183              : 
     184              : /// Time the future with a warning when it exceeds a threshold.
     185            4 : async fn timed<Fut: std::future::Future>(
     186            4 :     fut: Fut,
     187            4 :     name: &str,
     188            4 :     warn_at: std::time::Duration,
     189            4 : ) -> <Fut as std::future::Future>::Output {
     190            4 :     let started = std::time::Instant::now();
     191            4 : 
     192            4 :     let mut fut = std::pin::pin!(fut);
     193            4 : 
     194            4 :     match tokio::time::timeout(warn_at, &mut fut).await {
     195            2 :         Ok(ret) => {
     196            2 :             tracing::info!(
     197              :                 stage = name,
     198            0 :                 elapsed_ms = started.elapsed().as_millis(),
     199            0 :                 "completed"
     200              :             );
     201            2 :             ret
     202              :         }
     203              :         Err(_) => {
     204            2 :             tracing::info!(
     205              :                 stage = name,
     206            0 :                 elapsed_ms = started.elapsed().as_millis(),
     207            0 :                 "still waiting, taking longer than expected..."
     208              :             );
     209              : 
     210            2 :             let ret = fut.await;
     211              : 
     212              :             // this has a global allowed_errors
     213            2 :             tracing::warn!(
     214              :                 stage = name,
     215            0 :                 elapsed_ms = started.elapsed().as_millis(),
     216            0 :                 "completed, took longer than expected"
     217              :             );
     218              : 
     219            2 :             ret
     220              :         }
     221              :     }
     222            4 : }
     223              : 
     224              : #[cfg(test)]
     225              : mod timed_tests {
     226              :     use super::timed;
     227              :     use std::time::Duration;
     228              : 
     229              :     #[tokio::test]
     230            2 :     async fn timed_completes_when_inner_future_completes() {
     231            2 :         // A future that completes on time should have its result returned
     232            2 :         let r1 = timed(
     233            2 :             async move {
     234            2 :                 tokio::time::sleep(Duration::from_millis(10)).await;
     235            2 :                 123
     236            2 :             },
     237            2 :             "test 1",
     238            2 :             Duration::from_millis(50),
     239            2 :         )
     240            2 :         .await;
     241            2 :         assert_eq!(r1, 123);
     242            2 : 
     243            2 :         // A future that completes too slowly should also have its result returned
     244            2 :         let r1 = timed(
     245            2 :             async move {
     246            6 :                 tokio::time::sleep(Duration::from_millis(50)).await;
     247            2 :                 456
     248            2 :             },
     249            2 :             "test 1",
     250            2 :             Duration::from_millis(10),
     251            2 :         )
     252            4 :         .await;
     253            2 :         assert_eq!(r1, 456);
     254            2 :     }
     255              : }
        

Generated by: LCOV version 2.1-beta