LCOV - code coverage report
Current view: top level - pageserver/src/tenant - secondary.rs (source / functions) Coverage Total Hit
Test: 249f165943bd2c492f96a3f7d250276e4addca1a.info Lines: 0.0 % 227 0
Test Date: 2024-11-20 18:39:52 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 Drop for SecondaryTenant {
     115            0 :     fn drop(&mut self) {
     116            0 :         let tenant_id = self.tenant_shard_id.tenant_id.to_string();
     117            0 :         let shard_id = format!("{}", self.tenant_shard_id.shard_slug());
     118            0 :         let _ = SECONDARY_RESIDENT_PHYSICAL_SIZE.remove_label_values(&[&tenant_id, &shard_id]);
     119            0 :         let _ = SECONDARY_HEATMAP_TOTAL_SIZE.remove_label_values(&[&tenant_id, &shard_id]);
     120            0 :     }
     121              : }
     122              : 
     123              : impl SecondaryTenant {
     124            0 :     pub(crate) fn new(
     125            0 :         tenant_shard_id: TenantShardId,
     126            0 :         shard_identity: ShardIdentity,
     127            0 :         tenant_conf: TenantConfOpt,
     128            0 :         config: &SecondaryLocationConfig,
     129            0 :     ) -> Arc<Self> {
     130            0 :         let tenant_id = tenant_shard_id.tenant_id.to_string();
     131            0 :         let shard_id = format!("{}", tenant_shard_id.shard_slug());
     132            0 :         let resident_size_metric = SECONDARY_RESIDENT_PHYSICAL_SIZE
     133            0 :             .get_metric_with_label_values(&[&tenant_id, &shard_id])
     134            0 :             .unwrap();
     135            0 : 
     136            0 :         let heatmap_total_size_metric = SECONDARY_HEATMAP_TOTAL_SIZE
     137            0 :             .get_metric_with_label_values(&[&tenant_id, &shard_id])
     138            0 :             .unwrap();
     139            0 : 
     140            0 :         Arc::new(Self {
     141            0 :             tenant_shard_id,
     142            0 :             // todo: shall we make this a descendent of the
     143            0 :             // main cancellation token, or is it sufficient that
     144            0 :             // on shutdown we walk the tenants and fire their
     145            0 :             // individual cancellations?
     146            0 :             cancel: CancellationToken::new(),
     147            0 :             gate: Gate::default(),
     148            0 : 
     149            0 :             shard_identity,
     150            0 :             tenant_conf: std::sync::Mutex::new(tenant_conf),
     151            0 : 
     152            0 :             detail: std::sync::Mutex::new(SecondaryDetail::new(config.clone())),
     153            0 : 
     154            0 :             progress: std::sync::Mutex::default(),
     155            0 : 
     156            0 :             resident_size_metric,
     157            0 :             heatmap_total_size_metric,
     158            0 :         })
     159            0 :     }
     160              : 
     161            0 :     pub(crate) fn tenant_shard_id(&self) -> TenantShardId {
     162            0 :         self.tenant_shard_id
     163            0 :     }
     164              : 
     165            0 :     pub(crate) async fn shutdown(&self) {
     166            0 :         self.cancel.cancel();
     167            0 : 
     168            0 :         // Wait for any secondary downloader work to complete
     169            0 :         self.gate.close().await;
     170            0 :     }
     171              : 
     172            0 :     pub(crate) fn set_config(&self, config: &SecondaryLocationConfig) {
     173            0 :         self.detail.lock().unwrap().config = config.clone();
     174            0 :     }
     175              : 
     176            0 :     pub(crate) fn set_tenant_conf(&self, config: &TenantConfOpt) {
     177            0 :         *(self.tenant_conf.lock().unwrap()) = config.clone();
     178            0 :     }
     179              : 
     180              :     /// For API access: generate a LocationConfig equivalent to the one that would be used to
     181              :     /// create a Tenant in the same state.  Do not use this in hot paths: it's for relatively
     182              :     /// rare external API calls, like a reconciliation at startup.
     183            0 :     pub(crate) fn get_location_conf(&self) -> models::LocationConfig {
     184            0 :         let conf = self.detail.lock().unwrap().config.clone();
     185            0 : 
     186            0 :         let conf = models::LocationConfigSecondary { warm: conf.warm };
     187            0 : 
     188            0 :         let tenant_conf = self.tenant_conf.lock().unwrap().clone();
     189            0 :         models::LocationConfig {
     190            0 :             mode: models::LocationConfigMode::Secondary,
     191            0 :             generation: None,
     192            0 :             secondary_conf: Some(conf),
     193            0 :             shard_number: self.tenant_shard_id.shard_number.0,
     194            0 :             shard_count: self.tenant_shard_id.shard_count.literal(),
     195            0 :             shard_stripe_size: self.shard_identity.stripe_size.0,
     196            0 :             tenant_conf: tenant_conf.into(),
     197            0 :         }
     198            0 :     }
     199              : 
     200            0 :     pub(crate) fn get_tenant_shard_id(&self) -> &TenantShardId {
     201            0 :         &self.tenant_shard_id
     202            0 :     }
     203              : 
     204            0 :     pub(crate) fn get_layers_for_eviction(self: &Arc<Self>) -> (DiskUsageEvictionInfo, usize) {
     205            0 :         self.detail.lock().unwrap().get_layers_for_eviction(self)
     206            0 :     }
     207              : 
     208              :     /// Cancellation safe, but on cancellation the eviction will go through
     209            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))]
     210              :     pub(crate) async fn evict_layer(self: &Arc<Self>, timeline_id: TimelineId, name: LayerName) {
     211              :         debug_assert_current_span_has_tenant_id();
     212              : 
     213              :         let guard = match self.gate.enter() {
     214              :             Ok(g) => g,
     215              :             Err(_) => {
     216              :                 tracing::debug!("Dropping layer evictions, secondary tenant shutting down",);
     217              :                 return;
     218              :             }
     219              :         };
     220              : 
     221              :         let now = SystemTime::now();
     222              :         tracing::info!("Evicting secondary layer");
     223              : 
     224              :         let this = self.clone();
     225              : 
     226              :         // spawn it to be cancellation safe
     227            0 :         tokio::task::spawn_blocking(move || {
     228            0 :             let _guard = guard;
     229            0 : 
     230            0 :             // Update the timeline's state.  This does not have to be synchronized with
     231            0 :             // the download process, because:
     232            0 :             // - If downloader is racing with us to remove a file (e.g. because it is
     233            0 :             //   removed from heatmap), then our mutual .remove() operations will both
     234            0 :             //   succeed.
     235            0 :             // - If downloader is racing with us to download the object (this would require
     236            0 :             //   multiple eviction iterations to race with multiple download iterations), then
     237            0 :             //   if we remove it from the state, the worst that happens is the downloader
     238            0 :             //   downloads it again before re-inserting, or we delete the file but it remains
     239            0 :             //   in the state map (in which case it will be downloaded if this secondary
     240            0 :             //   tenant transitions to attached and tries to access it)
     241            0 :             //
     242            0 :             // The important assumption here is that the secondary timeline state does not
     243            0 :             // have to 100% match what is on disk, because it's a best-effort warming
     244            0 :             // of the cache.
     245            0 :             let mut detail = this.detail.lock().unwrap();
     246            0 :             if let Some(removed) =
     247            0 :                 detail.evict_layer(name, &timeline_id, now, &this.resident_size_metric)
     248            0 :             {
     249            0 :                 // We might race with removal of the same layer during downloads, so finding the layer we
     250            0 :                 // were trying to remove is optional.  Only issue the disk I/O to remove it if we found it.
     251            0 :                 removed.remove_blocking();
     252            0 :             }
     253            0 :         })
     254              :         .await
     255              :         .expect("secondary eviction should not have panicked");
     256              :     }
     257              : }
     258              : 
     259              : /// The SecondaryController is a pseudo-rpc client for administrative control of secondary mode downloads,
     260              : /// and heatmap uploads.  This is not a hot data path: it's used for:
     261              : /// - Live migrations, where we want to ensure a migration destination has the freshest possible
     262              : ///   content before trying to cut over.
     263              : /// - Tests, where we want to immediately upload/download for a particular tenant.
     264              : ///
     265              : /// In normal operations, outside of migrations, uploads & downloads are autonomous and not driven by this interface.
     266              : pub struct SecondaryController {
     267              :     upload_req_tx: tokio::sync::mpsc::Sender<CommandRequest<UploadCommand>>,
     268              :     download_req_tx: tokio::sync::mpsc::Sender<CommandRequest<DownloadCommand>>,
     269              : }
     270              : 
     271              : impl SecondaryController {
     272            0 :     async fn dispatch<T>(
     273            0 :         &self,
     274            0 :         queue: &tokio::sync::mpsc::Sender<CommandRequest<T>>,
     275            0 :         payload: T,
     276            0 :     ) -> anyhow::Result<()> {
     277            0 :         let (response_tx, response_rx) = tokio::sync::oneshot::channel();
     278            0 : 
     279            0 :         queue
     280            0 :             .send(CommandRequest {
     281            0 :                 payload,
     282            0 :                 response_tx,
     283            0 :             })
     284            0 :             .await
     285            0 :             .map_err(|_| anyhow::anyhow!("Receiver shut down"))?;
     286              : 
     287            0 :         let response = response_rx
     288            0 :             .await
     289            0 :             .map_err(|_| anyhow::anyhow!("Request dropped"))?;
     290              : 
     291            0 :         response.result
     292            0 :     }
     293              : 
     294            0 :     pub async fn upload_tenant(&self, tenant_shard_id: TenantShardId) -> anyhow::Result<()> {
     295            0 :         self.dispatch(&self.upload_req_tx, UploadCommand::Upload(tenant_shard_id))
     296            0 :             .await
     297            0 :     }
     298            0 :     pub async fn download_tenant(&self, tenant_shard_id: TenantShardId) -> anyhow::Result<()> {
     299            0 :         self.dispatch(
     300            0 :             &self.download_req_tx,
     301            0 :             DownloadCommand::Download(tenant_shard_id),
     302            0 :         )
     303            0 :         .await
     304            0 :     }
     305              : }
     306              : 
     307              : pub struct GlobalTasks {
     308              :     cancel: CancellationToken,
     309              :     uploader: JoinHandle<()>,
     310              :     downloader: JoinHandle<()>,
     311              : }
     312              : 
     313              : impl GlobalTasks {
     314              :     /// Caller is responsible for requesting shutdown via the cancellation token that was
     315              :     /// passed to [`spawn_tasks`].
     316              :     ///
     317              :     /// # Panics
     318              :     ///
     319              :     /// This method panics if that token is not cancelled.
     320              :     /// This is low-risk because we're calling this during process shutdown, so, a panic
     321              :     /// will be informative but not cause undue downtime.
     322            0 :     pub async fn wait(self) {
     323            0 :         let Self {
     324            0 :             cancel,
     325            0 :             uploader,
     326            0 :             downloader,
     327            0 :         } = self;
     328            0 :         assert!(
     329            0 :             cancel.is_cancelled(),
     330            0 :             "must cancel cancellation token, otherwise the tasks will not shut down"
     331              :         );
     332              : 
     333            0 :         let (uploader, downloader) = futures::future::join(uploader, downloader).await;
     334            0 :         uploader.expect(
     335            0 :             "unreachable: exit_on_panic_or_error would catch the panic and exit the process",
     336            0 :         );
     337            0 :         downloader.expect(
     338            0 :             "unreachable: exit_on_panic_or_error would catch the panic and exit the process",
     339            0 :         );
     340            0 :     }
     341              : }
     342              : 
     343            0 : pub fn spawn_tasks(
     344            0 :     tenant_manager: Arc<TenantManager>,
     345            0 :     remote_storage: GenericRemoteStorage,
     346            0 :     background_jobs_can_start: Barrier,
     347            0 :     cancel: CancellationToken,
     348            0 : ) -> (SecondaryController, GlobalTasks) {
     349            0 :     let mgr_clone = tenant_manager.clone();
     350            0 :     let storage_clone = remote_storage.clone();
     351            0 :     let bg_jobs_clone = background_jobs_can_start.clone();
     352            0 : 
     353            0 :     let (download_req_tx, download_req_rx) =
     354            0 :         tokio::sync::mpsc::channel::<CommandRequest<DownloadCommand>>(16);
     355            0 :     let (upload_req_tx, upload_req_rx) =
     356            0 :         tokio::sync::mpsc::channel::<CommandRequest<UploadCommand>>(16);
     357            0 : 
     358            0 :     let cancel_clone = cancel.clone();
     359            0 :     let downloader = BACKGROUND_RUNTIME.spawn(task_mgr::exit_on_panic_or_error(
     360            0 :         "secondary tenant downloads",
     361            0 :         async move {
     362            0 :             downloader_task(
     363            0 :                 mgr_clone,
     364            0 :                 storage_clone,
     365            0 :                 download_req_rx,
     366            0 :                 bg_jobs_clone,
     367            0 :                 cancel_clone,
     368            0 :                 RequestContext::new(
     369            0 :                     TaskKind::SecondaryDownloads,
     370            0 :                     crate::context::DownloadBehavior::Download,
     371            0 :                 ),
     372            0 :             )
     373            0 :             .await;
     374            0 :             anyhow::Ok(())
     375            0 :         },
     376            0 :     ));
     377            0 : 
     378            0 :     let cancel_clone = cancel.clone();
     379            0 :     let uploader = BACKGROUND_RUNTIME.spawn(task_mgr::exit_on_panic_or_error(
     380            0 :         "heatmap uploads",
     381            0 :         async move {
     382            0 :             heatmap_uploader_task(
     383            0 :                 tenant_manager,
     384            0 :                 remote_storage,
     385            0 :                 upload_req_rx,
     386            0 :                 background_jobs_can_start,
     387            0 :                 cancel_clone,
     388            0 :             )
     389            0 :             .await;
     390            0 :             anyhow::Ok(())
     391            0 :         },
     392            0 :     ));
     393            0 : 
     394            0 :     (
     395            0 :         SecondaryController {
     396            0 :             upload_req_tx,
     397            0 :             download_req_tx,
     398            0 :         },
     399            0 :         GlobalTasks {
     400            0 :             cancel,
     401            0 :             uploader,
     402            0 :             downloader,
     403            0 :         },
     404            0 :     )
     405            0 : }
        

Generated by: LCOV version 2.1-beta