LCOV - code coverage report
Current view: top level - pageserver/src/tenant - secondary.rs (source / functions) Coverage Total Hit
Test: 52d9d4a58355424a48c56cb9ba9670a073f618b9.info Lines: 0.0 % 233 0
Test Date: 2024-11-21 08:31:22 Functions: 0.0 % 32 0

            Line data    Source code
       1              : mod downloader;
       2              : pub mod heatmap;
       3              : mod heatmap_uploader;
       4              : mod scheduler;
       5              : 
       6              : use std::{sync::Arc, time::SystemTime};
       7              : 
       8              : use crate::{
       9              :     context::RequestContext,
      10              :     disk_usage_eviction_task::DiskUsageEvictionInfo,
      11              :     metrics::SECONDARY_HEATMAP_TOTAL_SIZE,
      12              :     task_mgr::{self, TaskKind, BACKGROUND_RUNTIME},
      13              : };
      14              : 
      15              : use self::{
      16              :     downloader::{downloader_task, SecondaryDetail},
      17              :     heatmap_uploader::heatmap_uploader_task,
      18              : };
      19              : 
      20              : use super::{
      21              :     config::{SecondaryLocationConfig, TenantConfOpt},
      22              :     mgr::TenantManager,
      23              :     span::debug_assert_current_span_has_tenant_id,
      24              :     storage_layer::LayerName,
      25              : };
      26              : 
      27              : use crate::metrics::SECONDARY_RESIDENT_PHYSICAL_SIZE;
      28              : use metrics::UIntGauge;
      29              : use pageserver_api::{
      30              :     models,
      31              :     shard::{ShardIdentity, TenantShardId},
      32              : };
      33              : use remote_storage::GenericRemoteStorage;
      34              : 
      35              : use tokio::task::JoinHandle;
      36              : use tokio_util::sync::CancellationToken;
      37              : use tracing::instrument;
      38              : use utils::{completion::Barrier, id::TimelineId, sync::gate::Gate};
      39              : 
      40              : enum DownloadCommand {
      41              :     Download(TenantShardId),
      42              : }
      43              : enum UploadCommand {
      44              :     Upload(TenantShardId),
      45              : }
      46              : 
      47              : impl UploadCommand {
      48            0 :     fn get_tenant_shard_id(&self) -> &TenantShardId {
      49            0 :         match self {
      50            0 :             Self::Upload(id) => id,
      51            0 :         }
      52            0 :     }
      53              : }
      54              : 
      55              : impl DownloadCommand {
      56            0 :     fn get_tenant_shard_id(&self) -> &TenantShardId {
      57            0 :         match self {
      58            0 :             Self::Download(id) => id,
      59            0 :         }
      60            0 :     }
      61              : }
      62              : 
      63              : struct CommandRequest<T> {
      64              :     payload: T,
      65              :     response_tx: tokio::sync::oneshot::Sender<CommandResponse>,
      66              : }
      67              : 
      68              : struct CommandResponse {
      69              :     result: anyhow::Result<()>,
      70              : }
      71              : 
      72              : // Whereas [`Tenant`] represents an attached tenant, this type represents the work
      73              : // we do for secondary tenant locations: where we are not serving clients or
      74              : // ingesting WAL, but we are maintaining a warm cache of layer files.
      75              : //
      76              : // This type is all about the _download_ path for secondary mode.  The upload path
      77              : // runs separately (see [`heatmap_uploader`]) while a regular attached `Tenant` exists.
      78              : //
      79              : // This structure coordinates TenantManager and SecondaryDownloader,
      80              : // so that the downloader can indicate which tenants it is currently
      81              : // operating on, and the manager can indicate when a particular
      82              : // secondary tenant should cancel any work in flight.
      83              : #[derive(Debug)]
      84              : pub(crate) struct SecondaryTenant {
      85              :     /// Carrying a tenant shard ID simplifies callers such as the downloader
      86              :     /// which need to organize many of these objects by ID.
      87              :     tenant_shard_id: TenantShardId,
      88              : 
      89              :     /// Cancellation token indicates to SecondaryDownloader that it should stop doing
      90              :     /// any work for this tenant at the next opportunity.
      91              :     pub(crate) cancel: CancellationToken,
      92              : 
      93              :     pub(crate) gate: Gate,
      94              : 
      95              :     // Secondary mode does not need the full shard identity or the TenantConfOpt.  However,
      96              :     // storing these enables us to report our full LocationConf, enabling convenient reconciliation
      97              :     // by the control plane (see [`Self::get_location_conf`])
      98              :     shard_identity: ShardIdentity,
      99              :     tenant_conf: std::sync::Mutex<TenantConfOpt>,
     100              : 
     101              :     // Internal state used by the Downloader.
     102              :     detail: std::sync::Mutex<SecondaryDetail>,
     103              : 
     104              :     // Public state indicating overall progress of downloads relative to the last heatmap seen
     105              :     pub(crate) progress: std::sync::Mutex<models::SecondaryProgress>,
     106              : 
     107              :     // Sum of layer sizes on local disk
     108              :     pub(super) resident_size_metric: UIntGauge,
     109              : 
     110              :     // Sum of layer sizes in the most recently downloaded heatmap
     111              :     pub(super) heatmap_total_size_metric: UIntGauge,
     112              : }
     113              : 
     114              : impl SecondaryTenant {
     115            0 :     pub(crate) fn new(
     116            0 :         tenant_shard_id: TenantShardId,
     117            0 :         shard_identity: ShardIdentity,
     118            0 :         tenant_conf: TenantConfOpt,
     119            0 :         config: &SecondaryLocationConfig,
     120            0 :     ) -> Arc<Self> {
     121            0 :         let tenant_id = tenant_shard_id.tenant_id.to_string();
     122            0 :         let shard_id = format!("{}", tenant_shard_id.shard_slug());
     123            0 :         let resident_size_metric = SECONDARY_RESIDENT_PHYSICAL_SIZE
     124            0 :             .get_metric_with_label_values(&[&tenant_id, &shard_id])
     125            0 :             .unwrap();
     126            0 : 
     127            0 :         let heatmap_total_size_metric = SECONDARY_HEATMAP_TOTAL_SIZE
     128            0 :             .get_metric_with_label_values(&[&tenant_id, &shard_id])
     129            0 :             .unwrap();
     130            0 : 
     131            0 :         Arc::new(Self {
     132            0 :             tenant_shard_id,
     133            0 :             // todo: shall we make this a descendent of the
     134            0 :             // main cancellation token, or is it sufficient that
     135            0 :             // on shutdown we walk the tenants and fire their
     136            0 :             // individual cancellations?
     137            0 :             cancel: CancellationToken::new(),
     138            0 :             gate: Gate::default(),
     139            0 : 
     140            0 :             shard_identity,
     141            0 :             tenant_conf: std::sync::Mutex::new(tenant_conf),
     142            0 : 
     143            0 :             detail: std::sync::Mutex::new(SecondaryDetail::new(config.clone())),
     144            0 : 
     145            0 :             progress: std::sync::Mutex::default(),
     146            0 : 
     147            0 :             resident_size_metric,
     148            0 :             heatmap_total_size_metric,
     149            0 :         })
     150            0 :     }
     151              : 
     152            0 :     pub(crate) fn tenant_shard_id(&self) -> TenantShardId {
     153            0 :         self.tenant_shard_id
     154            0 :     }
     155              : 
     156            0 :     pub(crate) async fn shutdown(&self) {
     157            0 :         self.cancel.cancel();
     158            0 : 
     159            0 :         // Wait for any secondary downloader work to complete
     160            0 :         self.gate.close().await;
     161              : 
     162            0 :         self.validate_metrics();
     163            0 : 
     164            0 :         let tenant_id = self.tenant_shard_id.tenant_id.to_string();
     165            0 :         let shard_id = format!("{}", self.tenant_shard_id.shard_slug());
     166            0 :         let _ = SECONDARY_RESIDENT_PHYSICAL_SIZE.remove_label_values(&[&tenant_id, &shard_id]);
     167            0 :         let _ = SECONDARY_HEATMAP_TOTAL_SIZE.remove_label_values(&[&tenant_id, &shard_id]);
     168            0 :     }
     169              : 
     170            0 :     pub(crate) fn set_config(&self, config: &SecondaryLocationConfig) {
     171            0 :         self.detail.lock().unwrap().config = config.clone();
     172            0 :     }
     173              : 
     174            0 :     pub(crate) fn set_tenant_conf(&self, config: &TenantConfOpt) {
     175            0 :         *(self.tenant_conf.lock().unwrap()) = config.clone();
     176            0 :     }
     177              : 
     178              :     /// For API access: generate a LocationConfig equivalent to the one that would be used to
     179              :     /// create a Tenant in the same state.  Do not use this in hot paths: it's for relatively
     180              :     /// rare external API calls, like a reconciliation at startup.
     181            0 :     pub(crate) fn get_location_conf(&self) -> models::LocationConfig {
     182            0 :         let conf = self.detail.lock().unwrap().config.clone();
     183            0 : 
     184            0 :         let conf = models::LocationConfigSecondary { warm: conf.warm };
     185            0 : 
     186            0 :         let tenant_conf = self.tenant_conf.lock().unwrap().clone();
     187            0 :         models::LocationConfig {
     188            0 :             mode: models::LocationConfigMode::Secondary,
     189            0 :             generation: None,
     190            0 :             secondary_conf: Some(conf),
     191            0 :             shard_number: self.tenant_shard_id.shard_number.0,
     192            0 :             shard_count: self.tenant_shard_id.shard_count.literal(),
     193            0 :             shard_stripe_size: self.shard_identity.stripe_size.0,
     194            0 :             tenant_conf: tenant_conf.into(),
     195            0 :         }
     196            0 :     }
     197              : 
     198            0 :     pub(crate) fn get_tenant_shard_id(&self) -> &TenantShardId {
     199            0 :         &self.tenant_shard_id
     200            0 :     }
     201              : 
     202            0 :     pub(crate) fn get_layers_for_eviction(self: &Arc<Self>) -> (DiskUsageEvictionInfo, usize) {
     203            0 :         self.detail.lock().unwrap().get_layers_for_eviction(self)
     204            0 :     }
     205              : 
     206              :     /// Cancellation safe, but on cancellation the eviction will go through
     207            0 :     #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug(), timeline_id=%timeline_id, name=%name))]
     208              :     pub(crate) async fn evict_layer(self: &Arc<Self>, timeline_id: TimelineId, name: LayerName) {
     209              :         debug_assert_current_span_has_tenant_id();
     210              : 
     211              :         let guard = match self.gate.enter() {
     212              :             Ok(g) => g,
     213              :             Err(_) => {
     214              :                 tracing::debug!("Dropping layer evictions, secondary tenant shutting down",);
     215              :                 return;
     216              :             }
     217              :         };
     218              : 
     219              :         let now = SystemTime::now();
     220              :         tracing::info!("Evicting secondary layer");
     221              : 
     222              :         let this = self.clone();
     223              : 
     224              :         // spawn it to be cancellation safe
     225            0 :         tokio::task::spawn_blocking(move || {
     226            0 :             let _guard = guard;
     227            0 : 
     228            0 :             // Update the timeline's state.  This does not have to be synchronized with
     229            0 :             // the download process, because:
     230            0 :             // - If downloader is racing with us to remove a file (e.g. because it is
     231            0 :             //   removed from heatmap), then our mutual .remove() operations will both
     232            0 :             //   succeed.
     233            0 :             // - If downloader is racing with us to download the object (this would require
     234            0 :             //   multiple eviction iterations to race with multiple download iterations), then
     235            0 :             //   if we remove it from the state, the worst that happens is the downloader
     236            0 :             //   downloads it again before re-inserting, or we delete the file but it remains
     237            0 :             //   in the state map (in which case it will be downloaded if this secondary
     238            0 :             //   tenant transitions to attached and tries to access it)
     239            0 :             //
     240            0 :             // The important assumption here is that the secondary timeline state does not
     241            0 :             // have to 100% match what is on disk, because it's a best-effort warming
     242            0 :             // of the cache.
     243            0 :             let mut detail = this.detail.lock().unwrap();
     244            0 :             if let Some(removed) =
     245            0 :                 detail.evict_layer(name, &timeline_id, now, &this.resident_size_metric)
     246            0 :             {
     247            0 :                 // We might race with removal of the same layer during downloads, so finding the layer we
     248            0 :                 // were trying to remove is optional.  Only issue the disk I/O to remove it if we found it.
     249            0 :                 removed.remove_blocking();
     250            0 :             }
     251            0 :         })
     252              :         .await
     253              :         .expect("secondary eviction should not have panicked");
     254              :     }
     255              : 
     256              :     /// Exhaustive check that incrementally updated metrics match the actual state.
     257              :     #[cfg(feature = "testing")]
     258            0 :     fn validate_metrics(&self) {
     259            0 :         let detail = self.detail.lock().unwrap();
     260            0 :         let resident_size = detail.total_resident_size();
     261            0 : 
     262            0 :         assert_eq!(resident_size, self.resident_size_metric.get());
     263            0 :     }
     264              : 
     265              :     #[cfg(not(feature = "testing"))]
     266              :     fn validate_metrics(&self) {
     267              :         // No-op in non-testing builds
     268              :     }
     269              : }
     270              : 
     271              : /// The SecondaryController is a pseudo-rpc client for administrative control of secondary mode downloads,
     272              : /// and heatmap uploads.  This is not a hot data path: it's used for:
     273              : /// - Live migrations, where we want to ensure a migration destination has the freshest possible
     274              : ///   content before trying to cut over.
     275              : /// - Tests, where we want to immediately upload/download for a particular tenant.
     276              : ///
     277              : /// In normal operations, outside of migrations, uploads & downloads are autonomous and not driven by this interface.
     278              : pub struct SecondaryController {
     279              :     upload_req_tx: tokio::sync::mpsc::Sender<CommandRequest<UploadCommand>>,
     280              :     download_req_tx: tokio::sync::mpsc::Sender<CommandRequest<DownloadCommand>>,
     281              : }
     282              : 
     283              : impl SecondaryController {
     284            0 :     async fn dispatch<T>(
     285            0 :         &self,
     286            0 :         queue: &tokio::sync::mpsc::Sender<CommandRequest<T>>,
     287            0 :         payload: T,
     288            0 :     ) -> anyhow::Result<()> {
     289            0 :         let (response_tx, response_rx) = tokio::sync::oneshot::channel();
     290            0 : 
     291            0 :         queue
     292            0 :             .send(CommandRequest {
     293            0 :                 payload,
     294            0 :                 response_tx,
     295            0 :             })
     296            0 :             .await
     297            0 :             .map_err(|_| anyhow::anyhow!("Receiver shut down"))?;
     298              : 
     299            0 :         let response = response_rx
     300            0 :             .await
     301            0 :             .map_err(|_| anyhow::anyhow!("Request dropped"))?;
     302              : 
     303            0 :         response.result
     304            0 :     }
     305              : 
     306            0 :     pub async fn upload_tenant(&self, tenant_shard_id: TenantShardId) -> anyhow::Result<()> {
     307            0 :         self.dispatch(&self.upload_req_tx, UploadCommand::Upload(tenant_shard_id))
     308            0 :             .await
     309            0 :     }
     310            0 :     pub async fn download_tenant(&self, tenant_shard_id: TenantShardId) -> anyhow::Result<()> {
     311            0 :         self.dispatch(
     312            0 :             &self.download_req_tx,
     313            0 :             DownloadCommand::Download(tenant_shard_id),
     314            0 :         )
     315            0 :         .await
     316            0 :     }
     317              : }
     318              : 
     319              : pub struct GlobalTasks {
     320              :     cancel: CancellationToken,
     321              :     uploader: JoinHandle<()>,
     322              :     downloader: JoinHandle<()>,
     323              : }
     324              : 
     325              : impl GlobalTasks {
     326              :     /// Caller is responsible for requesting shutdown via the cancellation token that was
     327              :     /// passed to [`spawn_tasks`].
     328              :     ///
     329              :     /// # Panics
     330              :     ///
     331              :     /// This method panics if that token is not cancelled.
     332              :     /// This is low-risk because we're calling this during process shutdown, so, a panic
     333              :     /// will be informative but not cause undue downtime.
     334            0 :     pub async fn wait(self) {
     335            0 :         let Self {
     336            0 :             cancel,
     337            0 :             uploader,
     338            0 :             downloader,
     339            0 :         } = self;
     340            0 :         assert!(
     341            0 :             cancel.is_cancelled(),
     342            0 :             "must cancel cancellation token, otherwise the tasks will not shut down"
     343              :         );
     344              : 
     345            0 :         let (uploader, downloader) = futures::future::join(uploader, downloader).await;
     346            0 :         uploader.expect(
     347            0 :             "unreachable: exit_on_panic_or_error would catch the panic and exit the process",
     348            0 :         );
     349            0 :         downloader.expect(
     350            0 :             "unreachable: exit_on_panic_or_error would catch the panic and exit the process",
     351            0 :         );
     352            0 :     }
     353              : }
     354              : 
     355            0 : pub fn spawn_tasks(
     356            0 :     tenant_manager: Arc<TenantManager>,
     357            0 :     remote_storage: GenericRemoteStorage,
     358            0 :     background_jobs_can_start: Barrier,
     359            0 :     cancel: CancellationToken,
     360            0 : ) -> (SecondaryController, GlobalTasks) {
     361            0 :     let mgr_clone = tenant_manager.clone();
     362            0 :     let storage_clone = remote_storage.clone();
     363            0 :     let bg_jobs_clone = background_jobs_can_start.clone();
     364            0 : 
     365            0 :     let (download_req_tx, download_req_rx) =
     366            0 :         tokio::sync::mpsc::channel::<CommandRequest<DownloadCommand>>(16);
     367            0 :     let (upload_req_tx, upload_req_rx) =
     368            0 :         tokio::sync::mpsc::channel::<CommandRequest<UploadCommand>>(16);
     369            0 : 
     370            0 :     let cancel_clone = cancel.clone();
     371            0 :     let downloader = BACKGROUND_RUNTIME.spawn(task_mgr::exit_on_panic_or_error(
     372            0 :         "secondary tenant downloads",
     373            0 :         async move {
     374            0 :             downloader_task(
     375            0 :                 mgr_clone,
     376            0 :                 storage_clone,
     377            0 :                 download_req_rx,
     378            0 :                 bg_jobs_clone,
     379            0 :                 cancel_clone,
     380            0 :                 RequestContext::new(
     381            0 :                     TaskKind::SecondaryDownloads,
     382            0 :                     crate::context::DownloadBehavior::Download,
     383            0 :                 ),
     384            0 :             )
     385            0 :             .await;
     386            0 :             anyhow::Ok(())
     387            0 :         },
     388            0 :     ));
     389            0 : 
     390            0 :     let cancel_clone = cancel.clone();
     391            0 :     let uploader = BACKGROUND_RUNTIME.spawn(task_mgr::exit_on_panic_or_error(
     392            0 :         "heatmap uploads",
     393            0 :         async move {
     394            0 :             heatmap_uploader_task(
     395            0 :                 tenant_manager,
     396            0 :                 remote_storage,
     397            0 :                 upload_req_rx,
     398            0 :                 background_jobs_can_start,
     399            0 :                 cancel_clone,
     400            0 :             )
     401            0 :             .await;
     402            0 :             anyhow::Ok(())
     403            0 :         },
     404            0 :     ));
     405            0 : 
     406            0 :     (
     407            0 :         SecondaryController {
     408            0 :             upload_req_tx,
     409            0 :             download_req_tx,
     410            0 :         },
     411            0 :         GlobalTasks {
     412            0 :             cancel,
     413            0 :             uploader,
     414            0 :             downloader,
     415            0 :         },
     416            0 :     )
     417            0 : }
        

Generated by: LCOV version 2.1-beta