LCOV - code coverage report
Current view: top level - pageserver/src - lib.rs (source / functions) Coverage Total Hit
Test: 691a4c28fe7169edd60b367c52d448a0a6605f1f.info Lines: 86.4 % 66 57
Test Date: 2024-05-10 13:18:37 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              :     deletion_queue: Option<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              :     if let Some(mut deletion_queue) = deletion_queue {
      93              :         deletion_queue.shutdown(Duration::from_secs(5)).await;
      94              :     }
      95              : 
      96              :     // Shut down the HTTP endpoint last, so that you can still check the server's
      97              :     // status while it's shutting down.
      98              :     // FIXME: We should probably stop accepting commands like attach/detach earlier.
      99              :     timed(
     100              :         task_mgr::shutdown_tasks(Some(TaskKind::HttpEndpointListener), None, None),
     101              :         "shutdown http",
     102              :         Duration::from_secs(1),
     103              :     )
     104              :     .await;
     105              : 
     106              :     // There should be nothing left, but let's be sure
     107              :     timed(
     108              :         task_mgr::shutdown_tasks(None, None, None),
     109              :         "shutdown leftovers",
     110              :         Duration::from_secs(1),
     111              :     )
     112              :     .await;
     113              :     info!("Shut down successfully completed");
     114              :     std::process::exit(exit_code);
     115              : }
     116              : 
     117              : /// The name of the metadata file pageserver creates per timeline.
     118              : /// Full path: `tenants/<tenant_id>/timelines/<timeline_id>/metadata`.
     119              : pub const METADATA_FILE_NAME: &str = "metadata";
     120              : 
     121              : /// Per-tenant configuration file.
     122              : /// Full path: `tenants/<tenant_id>/config`.
     123              : pub(crate) const TENANT_CONFIG_NAME: &str = "config";
     124              : 
     125              : /// Per-tenant configuration file.
     126              : /// Full path: `tenants/<tenant_id>/config`.
     127              : pub(crate) const TENANT_LOCATION_CONFIG_NAME: &str = "config-v1";
     128              : 
     129              : /// Per-tenant copy of their remote heatmap, downloaded into the local
     130              : /// tenant path while in secondary mode.
     131              : pub(crate) const TENANT_HEATMAP_BASENAME: &str = "heatmap-v1.json";
     132              : 
     133              : /// A suffix used for various temporary files. Any temporary files found in the
     134              : /// data directory at pageserver startup can be automatically removed.
     135              : pub(crate) const TEMP_FILE_SUFFIX: &str = "___temp";
     136              : 
     137              : /// A marker file to mark that a timeline directory was not fully initialized.
     138              : /// If a timeline directory with this marker is encountered at pageserver startup,
     139              : /// the timeline directory and the marker file are both removed.
     140              : /// Full path: `tenants/<tenant_id>/timelines/<timeline_id>___uninit`.
     141              : pub(crate) const TIMELINE_UNINIT_MARK_SUFFIX: &str = "___uninit";
     142              : 
     143              : pub(crate) const TIMELINE_DELETE_MARK_SUFFIX: &str = "___delete";
     144              : 
     145              : /// A marker file to prevent pageserver from loading a certain tenant on restart.
     146              : /// Different from [`TIMELINE_UNINIT_MARK_SUFFIX`] due to semantics of the corresponding
     147              : /// `ignore` management API command, that expects the ignored tenant to be properly loaded
     148              : /// into pageserver's memory before being ignored.
     149              : /// Full path: `tenants/<tenant_id>/___ignored_tenant`.
     150              : pub const IGNORED_TENANT_FILE_NAME: &str = "___ignored_tenant";
     151              : 
     152            8 : pub fn is_temporary(path: &Utf8Path) -> bool {
     153            8 :     match path.file_name() {
     154            8 :         Some(name) => name.ends_with(TEMP_FILE_SUFFIX),
     155            0 :         None => false,
     156              :     }
     157            8 : }
     158              : 
     159           16 : fn ends_with_suffix(path: &Utf8Path, suffix: &str) -> bool {
     160           16 :     match path.file_name() {
     161           16 :         Some(name) => name.ends_with(suffix),
     162            0 :         None => false,
     163              :     }
     164           16 : }
     165              : 
     166              : // FIXME: DO NOT ADD new query methods like this, which will have a next step of parsing timelineid
     167              : // from the directory name. Instead create type "UninitMark(TimelineId)" and only parse it once
     168              : // from the name.
     169              : 
     170            8 : pub(crate) fn is_uninit_mark(path: &Utf8Path) -> bool {
     171            8 :     ends_with_suffix(path, TIMELINE_UNINIT_MARK_SUFFIX)
     172            8 : }
     173              : 
     174            8 : pub(crate) fn is_delete_mark(path: &Utf8Path) -> bool {
     175            8 :     ends_with_suffix(path, TIMELINE_DELETE_MARK_SUFFIX)
     176            8 : }
     177              : 
     178              : /// During pageserver startup, we need to order operations not to exhaust tokio worker threads by
     179              : /// blocking.
     180              : ///
     181              : /// The instances of this value exist only during startup, otherwise `None` is provided, meaning no
     182              : /// delaying is needed.
     183              : #[derive(Clone)]
     184              : pub struct InitializationOrder {
     185              :     /// Each initial tenant load task carries this until it is done loading timelines from remote storage
     186              :     pub initial_tenant_load_remote: Option<utils::completion::Completion>,
     187              : 
     188              :     /// Each initial tenant load task carries this until completion.
     189              :     pub initial_tenant_load: Option<utils::completion::Completion>,
     190              : 
     191              :     /// Barrier for when we can start any background jobs.
     192              :     ///
     193              :     /// This can be broken up later on, but right now there is just one class of a background job.
     194              :     pub background_jobs_can_start: utils::completion::Barrier,
     195              : }
     196              : 
     197              : /// Time the future with a warning when it exceeds a threshold.
     198            4 : async fn timed<Fut: std::future::Future>(
     199            4 :     fut: Fut,
     200            4 :     name: &str,
     201            4 :     warn_at: std::time::Duration,
     202            4 : ) -> <Fut as std::future::Future>::Output {
     203            4 :     let started = std::time::Instant::now();
     204            4 : 
     205            4 :     let mut fut = std::pin::pin!(fut);
     206            4 : 
     207            4 :     match tokio::time::timeout(warn_at, &mut fut).await {
     208            2 :         Ok(ret) => {
     209            2 :             tracing::info!(
     210              :                 stage = name,
     211            0 :                 elapsed_ms = started.elapsed().as_millis(),
     212            0 :                 "completed"
     213              :             );
     214            2 :             ret
     215              :         }
     216              :         Err(_) => {
     217            2 :             tracing::info!(
     218              :                 stage = name,
     219            0 :                 elapsed_ms = started.elapsed().as_millis(),
     220            0 :                 "still waiting, taking longer than expected..."
     221              :             );
     222              : 
     223            2 :             let ret = fut.await;
     224              : 
     225              :             // this has a global allowed_errors
     226            2 :             tracing::warn!(
     227              :                 stage = name,
     228            0 :                 elapsed_ms = started.elapsed().as_millis(),
     229            0 :                 "completed, took longer than expected"
     230              :             );
     231              : 
     232            2 :             ret
     233              :         }
     234              :     }
     235            4 : }
     236              : 
     237              : #[cfg(test)]
     238              : mod timed_tests {
     239              :     use super::timed;
     240              :     use std::time::Duration;
     241              : 
     242              :     #[tokio::test]
     243            2 :     async fn timed_completes_when_inner_future_completes() {
     244            2 :         // A future that completes on time should have its result returned
     245            2 :         let r1 = timed(
     246            2 :             async move {
     247            2 :                 tokio::time::sleep(Duration::from_millis(10)).await;
     248            2 :                 123
     249            2 :             },
     250            2 :             "test 1",
     251            2 :             Duration::from_millis(50),
     252            2 :         )
     253            2 :         .await;
     254            2 :         assert_eq!(r1, 123);
     255            2 : 
     256            2 :         // A future that completes too slowly should also have its result returned
     257            2 :         let r1 = timed(
     258            2 :             async move {
     259            6 :                 tokio::time::sleep(Duration::from_millis(50)).await;
     260            2 :                 456
     261            2 :             },
     262            2 :             "test 1",
     263            2 :             Duration::from_millis(10),
     264            2 :         )
     265            4 :         .await;
     266            2 :         assert_eq!(r1, 456);
     267            2 :     }
     268              : }
        

Generated by: LCOV version 2.1-beta