LCOV - code coverage report
Current view: top level - pageserver/src/tenant/secondary - downloader.rs (source / functions) Coverage Total Hit
Test: 20b6afc7b7f34578dcaab2b3acdaecfe91cd8bf1.info Lines: 0.0 % 868 0
Test Date: 2024-11-25 17:48:16 Functions: 0.0 % 72 0

            Line data    Source code
       1              : use std::{
       2              :     collections::{HashMap, HashSet},
       3              :     pin::Pin,
       4              :     str::FromStr,
       5              :     sync::Arc,
       6              :     time::{Duration, Instant, SystemTime},
       7              : };
       8              : 
       9              : use crate::{
      10              :     config::PageServerConf,
      11              :     context::RequestContext,
      12              :     disk_usage_eviction_task::{
      13              :         finite_f32, DiskUsageEvictionInfo, EvictionCandidate, EvictionLayer, EvictionSecondaryLayer,
      14              :     },
      15              :     metrics::SECONDARY_MODE,
      16              :     tenant::{
      17              :         config::SecondaryLocationConfig,
      18              :         debug_assert_current_span_has_tenant_and_timeline_id,
      19              :         ephemeral_file::is_ephemeral_file,
      20              :         remote_timeline_client::{
      21              :             index::LayerFileMetadata, is_temp_download_file, FAILED_DOWNLOAD_WARN_THRESHOLD,
      22              :             FAILED_REMOTE_OP_RETRIES,
      23              :         },
      24              :         span::debug_assert_current_span_has_tenant_id,
      25              :         storage_layer::{layer::local_layer_path, LayerName, LayerVisibilityHint},
      26              :         tasks::{warn_when_period_overrun, BackgroundLoopKind},
      27              :     },
      28              :     virtual_file::{on_fatal_io_error, MaybeFatalIo, VirtualFile},
      29              :     TEMP_FILE_SUFFIX,
      30              : };
      31              : 
      32              : use super::{
      33              :     heatmap::HeatMapLayer,
      34              :     scheduler::{
      35              :         self, period_jitter, period_warmup, Completion, JobGenerator, SchedulingResult,
      36              :         TenantBackgroundJobs,
      37              :     },
      38              :     SecondaryTenant,
      39              : };
      40              : 
      41              : use crate::tenant::{
      42              :     mgr::TenantManager,
      43              :     remote_timeline_client::{download::download_layer_file, remote_heatmap_path},
      44              : };
      45              : 
      46              : use camino::Utf8PathBuf;
      47              : use chrono::format::{DelayedFormat, StrftimeItems};
      48              : use futures::Future;
      49              : use metrics::UIntGauge;
      50              : use pageserver_api::models::SecondaryProgress;
      51              : use pageserver_api::shard::TenantShardId;
      52              : use remote_storage::{DownloadError, DownloadOpts, Etag, GenericRemoteStorage};
      53              : 
      54              : use tokio_util::sync::CancellationToken;
      55              : use tracing::{info_span, instrument, warn, Instrument};
      56              : use utils::{
      57              :     backoff, completion::Barrier, crashsafe::path_with_suffix_extension, failpoint_support, fs_ext,
      58              :     id::TimelineId, pausable_failpoint, serde_system_time,
      59              : };
      60              : 
      61              : use super::{
      62              :     heatmap::{HeatMapTenant, HeatMapTimeline},
      63              :     CommandRequest, DownloadCommand,
      64              : };
      65              : 
      66              : /// For each tenant, default period for how long must have passed since the last download_tenant call before
      67              : /// calling it again.  This default is replaced with the value of [`HeatMapTenant::upload_period_ms`] after first
      68              : /// download, if the uploader populated it.
      69              : const DEFAULT_DOWNLOAD_INTERVAL: Duration = Duration::from_millis(60000);
      70              : 
      71            0 : pub(super) async fn downloader_task(
      72            0 :     tenant_manager: Arc<TenantManager>,
      73            0 :     remote_storage: GenericRemoteStorage,
      74            0 :     command_queue: tokio::sync::mpsc::Receiver<CommandRequest<DownloadCommand>>,
      75            0 :     background_jobs_can_start: Barrier,
      76            0 :     cancel: CancellationToken,
      77            0 :     root_ctx: RequestContext,
      78            0 : ) {
      79            0 :     let concurrency = tenant_manager.get_conf().secondary_download_concurrency;
      80            0 : 
      81            0 :     let generator = SecondaryDownloader {
      82            0 :         tenant_manager,
      83            0 :         remote_storage,
      84            0 :         root_ctx,
      85            0 :     };
      86            0 :     let mut scheduler = Scheduler::new(generator, concurrency);
      87            0 : 
      88            0 :     scheduler
      89            0 :         .run(command_queue, background_jobs_can_start, cancel)
      90            0 :         .instrument(info_span!("secondary_download_scheduler"))
      91            0 :         .await
      92            0 : }
      93              : 
      94              : struct SecondaryDownloader {
      95              :     tenant_manager: Arc<TenantManager>,
      96              :     remote_storage: GenericRemoteStorage,
      97              :     root_ctx: RequestContext,
      98              : }
      99              : 
     100              : #[derive(Debug, Clone)]
     101              : pub(super) struct OnDiskState {
     102              :     metadata: LayerFileMetadata,
     103              :     access_time: SystemTime,
     104              :     local_path: Utf8PathBuf,
     105              : }
     106              : 
     107              : impl OnDiskState {
     108            0 :     fn new(
     109            0 :         _conf: &'static PageServerConf,
     110            0 :         _tenant_shard_id: &TenantShardId,
     111            0 :         _imeline_id: &TimelineId,
     112            0 :         _ame: LayerName,
     113            0 :         metadata: LayerFileMetadata,
     114            0 :         access_time: SystemTime,
     115            0 :         local_path: Utf8PathBuf,
     116            0 :     ) -> Self {
     117            0 :         Self {
     118            0 :             metadata,
     119            0 :             access_time,
     120            0 :             local_path,
     121            0 :         }
     122            0 :     }
     123              : 
     124              :     // This is infallible, because all errors are either acceptable (ENOENT), or totally
     125              :     // unexpected (fatal).
     126            0 :     pub(super) fn remove_blocking(&self) {
     127            0 :         // We tolerate ENOENT, because between planning eviction and executing
     128            0 :         // it, the secondary downloader could have seen an updated heatmap that
     129            0 :         // resulted in a layer being deleted.
     130            0 :         // Other local I/O errors are process-fatal: these should never happen.
     131            0 :         std::fs::remove_file(&self.local_path)
     132            0 :             .or_else(fs_ext::ignore_not_found)
     133            0 :             .fatal_err("Deleting secondary layer")
     134            0 :     }
     135              : 
     136            0 :     pub(crate) fn file_size(&self) -> u64 {
     137            0 :         self.metadata.file_size
     138            0 :     }
     139              : }
     140              : 
     141              : #[derive(Debug, Clone, Default)]
     142              : pub(super) struct SecondaryDetailTimeline {
     143              :     on_disk_layers: HashMap<LayerName, OnDiskState>,
     144              : 
     145              :     /// We remember when layers were evicted, to prevent re-downloading them.
     146              :     pub(super) evicted_at: HashMap<LayerName, SystemTime>,
     147              : }
     148              : 
     149              : impl SecondaryDetailTimeline {
     150            0 :     pub(super) fn remove_layer(
     151            0 :         &mut self,
     152            0 :         name: &LayerName,
     153            0 :         resident_metric: &UIntGauge,
     154            0 :     ) -> Option<OnDiskState> {
     155            0 :         let removed = self.on_disk_layers.remove(name);
     156            0 :         if let Some(removed) = &removed {
     157            0 :             resident_metric.sub(removed.file_size());
     158            0 :         }
     159            0 :         removed
     160            0 :     }
     161              : 
     162              :     /// `local_path`
     163            0 :     fn touch_layer<F>(
     164            0 :         &mut self,
     165            0 :         conf: &'static PageServerConf,
     166            0 :         tenant_shard_id: &TenantShardId,
     167            0 :         timeline_id: &TimelineId,
     168            0 :         touched: &HeatMapLayer,
     169            0 :         resident_metric: &UIntGauge,
     170            0 :         local_path: F,
     171            0 :     ) where
     172            0 :         F: FnOnce() -> Utf8PathBuf,
     173            0 :     {
     174              :         use std::collections::hash_map::Entry;
     175            0 :         match self.on_disk_layers.entry(touched.name.clone()) {
     176            0 :             Entry::Occupied(mut v) => {
     177            0 :                 v.get_mut().access_time = touched.access_time;
     178            0 :             }
     179            0 :             Entry::Vacant(e) => {
     180            0 :                 e.insert(OnDiskState::new(
     181            0 :                     conf,
     182            0 :                     tenant_shard_id,
     183            0 :                     timeline_id,
     184            0 :                     touched.name.clone(),
     185            0 :                     touched.metadata.clone(),
     186            0 :                     touched.access_time,
     187            0 :                     local_path(),
     188            0 :                 ));
     189            0 :                 resident_metric.add(touched.metadata.file_size);
     190            0 :             }
     191              :         }
     192            0 :     }
     193              : }
     194              : 
     195              : // Aspects of a heatmap that we remember after downloading it
     196              : #[derive(Clone, Debug)]
     197              : struct DownloadSummary {
     198              :     etag: Etag,
     199              :     #[allow(unused)]
     200              :     mtime: SystemTime,
     201              :     upload_period: Duration,
     202              : }
     203              : 
     204              : /// This state is written by the secondary downloader, it is opaque
     205              : /// to TenantManager
     206              : #[derive(Debug)]
     207              : pub(super) struct SecondaryDetail {
     208              :     pub(super) config: SecondaryLocationConfig,
     209              : 
     210              :     last_download: Option<DownloadSummary>,
     211              :     next_download: Option<Instant>,
     212              :     timelines: HashMap<TimelineId, SecondaryDetailTimeline>,
     213              : }
     214              : 
     215              : /// Helper for logging SystemTime
     216            0 : fn strftime(t: &'_ SystemTime) -> DelayedFormat<StrftimeItems<'_>> {
     217            0 :     let datetime: chrono::DateTime<chrono::Utc> = (*t).into();
     218            0 :     datetime.format("%d/%m/%Y %T")
     219            0 : }
     220              : 
     221              : /// Information returned from download function when it detects the heatmap has changed
     222              : struct HeatMapModified {
     223              :     etag: Etag,
     224              :     last_modified: SystemTime,
     225              :     bytes: Vec<u8>,
     226              : }
     227              : 
     228              : enum HeatMapDownload {
     229              :     // The heatmap's etag has changed: return the new etag, mtime and the body bytes
     230              :     Modified(HeatMapModified),
     231              :     // The heatmap's etag is unchanged
     232              :     Unmodified,
     233              : }
     234              : 
     235              : impl SecondaryDetail {
     236            0 :     pub(super) fn new(config: SecondaryLocationConfig) -> Self {
     237            0 :         Self {
     238            0 :             config,
     239            0 :             last_download: None,
     240            0 :             next_download: None,
     241            0 :             timelines: HashMap::new(),
     242            0 :         }
     243            0 :     }
     244              : 
     245              :     #[cfg(feature = "testing")]
     246            0 :     pub(crate) fn total_resident_size(&self) -> u64 {
     247            0 :         self.timelines
     248            0 :             .values()
     249            0 :             .map(|tl| {
     250            0 :                 tl.on_disk_layers
     251            0 :                     .values()
     252            0 :                     .map(|v| v.metadata.file_size)
     253            0 :                     .sum::<u64>()
     254            0 :             })
     255            0 :             .sum::<u64>()
     256            0 :     }
     257              : 
     258            0 :     pub(super) fn evict_layer(
     259            0 :         &mut self,
     260            0 :         name: LayerName,
     261            0 :         timeline_id: &TimelineId,
     262            0 :         now: SystemTime,
     263            0 :         resident_metric: &UIntGauge,
     264            0 :     ) -> Option<OnDiskState> {
     265            0 :         let timeline = self.timelines.get_mut(timeline_id)?;
     266            0 :         let removed = timeline.remove_layer(&name, resident_metric);
     267            0 :         if removed.is_some() {
     268            0 :             timeline.evicted_at.insert(name, now);
     269            0 :         }
     270            0 :         removed
     271            0 :     }
     272              : 
     273            0 :     pub(super) fn remove_timeline(
     274            0 :         &mut self,
     275            0 :         timeline_id: &TimelineId,
     276            0 :         resident_metric: &UIntGauge,
     277            0 :     ) {
     278            0 :         let removed = self.timelines.remove(timeline_id);
     279            0 :         if let Some(removed) = removed {
     280            0 :             resident_metric.sub(
     281            0 :                 removed
     282            0 :                     .on_disk_layers
     283            0 :                     .values()
     284            0 :                     .map(|l| l.metadata.file_size)
     285            0 :                     .sum(),
     286            0 :             );
     287            0 :         }
     288            0 :     }
     289              : 
     290              :     /// Additionally returns the total number of layers, used for more stable relative access time
     291              :     /// based eviction.
     292            0 :     pub(super) fn get_layers_for_eviction(
     293            0 :         &self,
     294            0 :         parent: &Arc<SecondaryTenant>,
     295            0 :     ) -> (DiskUsageEvictionInfo, usize) {
     296            0 :         let mut result = DiskUsageEvictionInfo::default();
     297            0 :         let mut total_layers = 0;
     298              : 
     299            0 :         for (timeline_id, timeline_detail) in &self.timelines {
     300            0 :             result
     301            0 :                 .resident_layers
     302            0 :                 .extend(timeline_detail.on_disk_layers.iter().map(|(name, ods)| {
     303            0 :                     EvictionCandidate {
     304            0 :                         layer: EvictionLayer::Secondary(EvictionSecondaryLayer {
     305            0 :                             secondary_tenant: parent.clone(),
     306            0 :                             timeline_id: *timeline_id,
     307            0 :                             name: name.clone(),
     308            0 :                             metadata: ods.metadata.clone(),
     309            0 :                         }),
     310            0 :                         last_activity_ts: ods.access_time,
     311            0 :                         relative_last_activity: finite_f32::FiniteF32::ZERO,
     312            0 :                         // Secondary location layers are presumed visible, because Covered layers
     313            0 :                         // are excluded from the heatmap
     314            0 :                         visibility: LayerVisibilityHint::Visible,
     315            0 :                     }
     316            0 :                 }));
     317            0 : 
     318            0 :             // total might be missing currently downloading layers, but as a lower than actual
     319            0 :             // value it is good enough approximation.
     320            0 :             total_layers += timeline_detail.on_disk_layers.len() + timeline_detail.evicted_at.len();
     321            0 :         }
     322            0 :         result.max_layer_size = result
     323            0 :             .resident_layers
     324            0 :             .iter()
     325            0 :             .map(|l| l.layer.get_file_size())
     326            0 :             .max();
     327            0 : 
     328            0 :         tracing::debug!(
     329            0 :             "eviction: secondary tenant {} found {} timelines, {} layers",
     330            0 :             parent.get_tenant_shard_id(),
     331            0 :             self.timelines.len(),
     332            0 :             result.resident_layers.len()
     333              :         );
     334              : 
     335            0 :         (result, total_layers)
     336            0 :     }
     337              : }
     338              : 
     339              : struct PendingDownload {
     340              :     secondary_state: Arc<SecondaryTenant>,
     341              :     last_download: Option<DownloadSummary>,
     342              :     target_time: Option<Instant>,
     343              : }
     344              : 
     345              : impl scheduler::PendingJob for PendingDownload {
     346            0 :     fn get_tenant_shard_id(&self) -> &TenantShardId {
     347            0 :         self.secondary_state.get_tenant_shard_id()
     348            0 :     }
     349              : }
     350              : 
     351              : struct RunningDownload {
     352              :     barrier: Barrier,
     353              : }
     354              : 
     355              : impl scheduler::RunningJob for RunningDownload {
     356            0 :     fn get_barrier(&self) -> Barrier {
     357            0 :         self.barrier.clone()
     358            0 :     }
     359              : }
     360              : 
     361              : struct CompleteDownload {
     362              :     secondary_state: Arc<SecondaryTenant>,
     363              :     completed_at: Instant,
     364              :     result: Result<(), UpdateError>,
     365              : }
     366              : 
     367              : impl scheduler::Completion for CompleteDownload {
     368            0 :     fn get_tenant_shard_id(&self) -> &TenantShardId {
     369            0 :         self.secondary_state.get_tenant_shard_id()
     370            0 :     }
     371              : }
     372              : 
     373              : type Scheduler = TenantBackgroundJobs<
     374              :     SecondaryDownloader,
     375              :     PendingDownload,
     376              :     RunningDownload,
     377              :     CompleteDownload,
     378              :     DownloadCommand,
     379              : >;
     380              : 
     381              : impl JobGenerator<PendingDownload, RunningDownload, CompleteDownload, DownloadCommand>
     382              :     for SecondaryDownloader
     383              : {
     384            0 :     #[instrument(skip_all, fields(tenant_id=%completion.get_tenant_shard_id().tenant_id, shard_id=%completion.get_tenant_shard_id().shard_slug()))]
     385              :     fn on_completion(&mut self, completion: CompleteDownload) {
     386              :         let CompleteDownload {
     387              :             secondary_state,
     388              :             completed_at: _completed_at,
     389              :             result,
     390              :         } = completion;
     391              : 
     392              :         tracing::debug!("Secondary tenant download completed");
     393              : 
     394              :         let mut detail = secondary_state.detail.lock().unwrap();
     395              : 
     396              :         match result {
     397              :             Err(UpdateError::Restart) => {
     398              :                 // Start downloading again as soon as we can.  This will involve waiting for the scheduler's
     399              :                 // scheduling interval.  This slightly reduces the peak download speed of tenants that hit their
     400              :                 // deadline and keep restarting, but that also helps give other tenants a chance to execute rather
     401              :                 // that letting one big tenant dominate for a long time.
     402              :                 detail.next_download = Some(Instant::now());
     403              :             }
     404              :             _ => {
     405              :                 let period = detail
     406              :                     .last_download
     407              :                     .as_ref()
     408            0 :                     .map(|d| d.upload_period)
     409              :                     .unwrap_or(DEFAULT_DOWNLOAD_INTERVAL);
     410              : 
     411              :                 // We advance next_download irrespective of errors: we don't want error cases to result in
     412              :                 // expensive busy-polling.
     413              :                 detail.next_download = Some(Instant::now() + period_jitter(period, 5));
     414              :             }
     415              :         }
     416              :     }
     417              : 
     418            0 :     async fn schedule(&mut self) -> SchedulingResult<PendingDownload> {
     419            0 :         let mut result = SchedulingResult {
     420            0 :             jobs: Vec::new(),
     421            0 :             want_interval: None,
     422            0 :         };
     423            0 : 
     424            0 :         // Step 1: identify some tenants that we may work on
     425            0 :         let mut tenants: Vec<Arc<SecondaryTenant>> = Vec::new();
     426            0 :         self.tenant_manager
     427            0 :             .foreach_secondary_tenants(|_id, secondary_state| {
     428            0 :                 tenants.push(secondary_state.clone());
     429            0 :             });
     430            0 : 
     431            0 :         // Step 2: filter out tenants which are not yet elegible to run
     432            0 :         let now = Instant::now();
     433            0 :         result.jobs = tenants
     434            0 :             .into_iter()
     435            0 :             .filter_map(|secondary_tenant| {
     436            0 :                 let (last_download, next_download) = {
     437            0 :                     let mut detail = secondary_tenant.detail.lock().unwrap();
     438            0 : 
     439            0 :                     if !detail.config.warm {
     440              :                         // Downloads are disabled for this tenant
     441            0 :                         detail.next_download = None;
     442            0 :                         return None;
     443            0 :                     }
     444            0 : 
     445            0 :                     if detail.next_download.is_none() {
     446            0 :                         // Initialize randomly in the range from 0 to our interval: this uniformly spreads the start times.  Subsequent
     447            0 :                         // rounds will use a smaller jitter to avoid accidentally synchronizing later.
     448            0 :                         detail.next_download = Some(now.checked_add(period_warmup(DEFAULT_DOWNLOAD_INTERVAL)).expect(
     449            0 :                         "Using our constant, which is known to be small compared with clock range",
     450            0 :                     ));
     451            0 :                     }
     452            0 :                     (detail.last_download.clone(), detail.next_download.unwrap())
     453            0 :                 };
     454            0 : 
     455            0 :                 if now > next_download {
     456            0 :                     Some(PendingDownload {
     457            0 :                         secondary_state: secondary_tenant,
     458            0 :                         last_download,
     459            0 :                         target_time: Some(next_download),
     460            0 :                     })
     461              :                 } else {
     462            0 :                     None
     463              :                 }
     464            0 :             })
     465            0 :             .collect();
     466            0 : 
     467            0 :         // Step 3: sort by target execution time to run most urgent first.
     468            0 :         result.jobs.sort_by_key(|j| j.target_time);
     469            0 : 
     470            0 :         result
     471            0 :     }
     472              : 
     473            0 :     fn on_command(&mut self, command: DownloadCommand) -> anyhow::Result<PendingDownload> {
     474            0 :         let tenant_shard_id = command.get_tenant_shard_id();
     475            0 : 
     476            0 :         let tenant = self
     477            0 :             .tenant_manager
     478            0 :             .get_secondary_tenant_shard(*tenant_shard_id);
     479            0 :         let Some(tenant) = tenant else {
     480            0 :             return Err(anyhow::anyhow!("Not found or not in Secondary mode"));
     481              :         };
     482              : 
     483            0 :         Ok(PendingDownload {
     484            0 :             target_time: None,
     485            0 :             last_download: None,
     486            0 :             secondary_state: tenant,
     487            0 :         })
     488            0 :     }
     489              : 
     490            0 :     fn spawn(
     491            0 :         &mut self,
     492            0 :         job: PendingDownload,
     493            0 :     ) -> (
     494            0 :         RunningDownload,
     495            0 :         Pin<Box<dyn Future<Output = CompleteDownload> + Send>>,
     496            0 :     ) {
     497            0 :         let PendingDownload {
     498            0 :             secondary_state,
     499            0 :             last_download,
     500            0 :             target_time,
     501            0 :         } = job;
     502            0 : 
     503            0 :         let (completion, barrier) = utils::completion::channel();
     504            0 :         let remote_storage = self.remote_storage.clone();
     505            0 :         let conf = self.tenant_manager.get_conf();
     506            0 :         let tenant_shard_id = *secondary_state.get_tenant_shard_id();
     507            0 :         let download_ctx = self.root_ctx.attached_child();
     508            0 :         (RunningDownload { barrier }, Box::pin(async move {
     509            0 :             let _completion = completion;
     510              : 
     511            0 :             let result = TenantDownloader::new(conf, &remote_storage, &secondary_state)
     512            0 :                 .download(&download_ctx)
     513            0 :                 .await;
     514            0 :             match &result
     515              :             {
     516              :                 Err(UpdateError::NoData) => {
     517            0 :                     tracing::info!("No heatmap found for tenant.  This is fine if it is new.");
     518              :                 },
     519              :                 Err(UpdateError::NoSpace) => {
     520            0 :                     tracing::warn!("Insufficient space while downloading.  Will retry later.");
     521              :                 }
     522              :                 Err(UpdateError::Cancelled) => {
     523            0 :                     tracing::info!("Shut down while downloading");
     524              :                 },
     525            0 :                 Err(UpdateError::Deserialize(e)) => {
     526            0 :                     tracing::error!("Corrupt content while downloading tenant: {e}");
     527              :                 },
     528            0 :                 Err(e @ (UpdateError::DownloadError(_) | UpdateError::Other(_))) => {
     529            0 :                     tracing::error!("Error while downloading tenant: {e}");
     530              :                 },
     531              :                 Err(UpdateError::Restart) => {
     532            0 :                     tracing::info!("Download reached deadline & will restart to update heatmap")
     533              :                 }
     534            0 :                 Ok(()) => {}
     535              :             };
     536              : 
     537              :             // Irrespective of the result, we will reschedule ourselves to run after our usual period.
     538              : 
     539              :             // If the job had a target execution time, we may check our final execution
     540              :             // time against that for observability purposes.
     541            0 :             if let (Some(target_time), Some(last_download)) = (target_time, last_download) {
     542            0 :                 // Elapsed time includes any scheduling lag as well as the execution of the job
     543            0 :                 let elapsed = Instant::now().duration_since(target_time);
     544            0 : 
     545            0 :                 warn_when_period_overrun(
     546            0 :                     elapsed,
     547            0 :                     last_download.upload_period,
     548            0 :                     BackgroundLoopKind::SecondaryDownload,
     549            0 :                 );
     550            0 :             }
     551              : 
     552            0 :             CompleteDownload {
     553            0 :                 secondary_state,
     554            0 :                 completed_at: Instant::now(),
     555            0 :                 result
     556            0 :             }
     557            0 :         }.instrument(info_span!(parent: None, "secondary_download", tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug()))))
     558            0 :     }
     559              : }
     560              : 
     561              : /// This type is a convenience to group together the various functions involved in
     562              : /// freshening a secondary tenant.
     563              : struct TenantDownloader<'a> {
     564              :     conf: &'static PageServerConf,
     565              :     remote_storage: &'a GenericRemoteStorage,
     566              :     secondary_state: &'a SecondaryTenant,
     567              : }
     568              : 
     569              : /// Errors that may be encountered while updating a tenant
     570            0 : #[derive(thiserror::Error, Debug)]
     571              : enum UpdateError {
     572              :     /// This is not a true failure, but it's how a download indicates that it would like to be restarted by
     573              :     /// the scheduler, to pick up the latest heatmap
     574              :     #[error("Reached deadline, restarting downloads")]
     575              :     Restart,
     576              : 
     577              :     #[error("No remote data found")]
     578              :     NoData,
     579              :     #[error("Insufficient local storage space")]
     580              :     NoSpace,
     581              :     #[error("Failed to download")]
     582              :     DownloadError(DownloadError),
     583              :     #[error(transparent)]
     584              :     Deserialize(#[from] serde_json::Error),
     585              :     #[error("Cancelled")]
     586              :     Cancelled,
     587              :     #[error(transparent)]
     588              :     Other(#[from] anyhow::Error),
     589              : }
     590              : 
     591              : impl From<DownloadError> for UpdateError {
     592            0 :     fn from(value: DownloadError) -> Self {
     593            0 :         match &value {
     594            0 :             DownloadError::Cancelled => Self::Cancelled,
     595            0 :             DownloadError::NotFound => Self::NoData,
     596            0 :             _ => Self::DownloadError(value),
     597              :         }
     598            0 :     }
     599              : }
     600              : 
     601              : impl From<std::io::Error> for UpdateError {
     602            0 :     fn from(value: std::io::Error) -> Self {
     603            0 :         if let Some(nix::errno::Errno::ENOSPC) = value.raw_os_error().map(nix::errno::from_i32) {
     604            0 :             UpdateError::NoSpace
     605            0 :         } else if value
     606            0 :             .get_ref()
     607            0 :             .and_then(|x| x.downcast_ref::<DownloadError>())
     608            0 :             .is_some()
     609              :         {
     610            0 :             UpdateError::from(DownloadError::from(value))
     611              :         } else {
     612              :             // An I/O error from e.g. tokio::io::copy_buf is most likely a remote storage issue
     613            0 :             UpdateError::Other(anyhow::anyhow!(value))
     614              :         }
     615            0 :     }
     616              : }
     617              : 
     618              : impl<'a> TenantDownloader<'a> {
     619            0 :     fn new(
     620            0 :         conf: &'static PageServerConf,
     621            0 :         remote_storage: &'a GenericRemoteStorage,
     622            0 :         secondary_state: &'a SecondaryTenant,
     623            0 :     ) -> Self {
     624            0 :         Self {
     625            0 :             conf,
     626            0 :             remote_storage,
     627            0 :             secondary_state,
     628            0 :         }
     629            0 :     }
     630              : 
     631            0 :     async fn download(&self, ctx: &RequestContext) -> Result<(), UpdateError> {
     632            0 :         debug_assert_current_span_has_tenant_id();
     633              : 
     634              :         // For the duration of a download, we must hold the SecondaryTenant::gate, to ensure
     635              :         // cover our access to local storage.
     636            0 :         let Ok(_guard) = self.secondary_state.gate.enter() else {
     637              :             // Shutting down
     638            0 :             return Err(UpdateError::Cancelled);
     639              :         };
     640              : 
     641            0 :         let tenant_shard_id = self.secondary_state.get_tenant_shard_id();
     642            0 : 
     643            0 :         // We will use the etag from last successful download to make the download conditional on changes
     644            0 :         let last_download = self
     645            0 :             .secondary_state
     646            0 :             .detail
     647            0 :             .lock()
     648            0 :             .unwrap()
     649            0 :             .last_download
     650            0 :             .clone();
     651              : 
     652              :         // Download the tenant's heatmap
     653              :         let HeatMapModified {
     654            0 :             last_modified: heatmap_mtime,
     655            0 :             etag: heatmap_etag,
     656            0 :             bytes: heatmap_bytes,
     657            0 :         } = match tokio::select!(
     658            0 :             bytes = self.download_heatmap(last_download.as_ref().map(|d| &d.etag)) => {bytes?},
     659            0 :             _ = self.secondary_state.cancel.cancelled() => return Ok(())
     660              :         ) {
     661              :             HeatMapDownload::Unmodified => {
     662            0 :                 tracing::info!("Heatmap unchanged since last successful download");
     663            0 :                 return Ok(());
     664              :             }
     665            0 :             HeatMapDownload::Modified(m) => m,
     666              :         };
     667              : 
     668            0 :         let heatmap = serde_json::from_slice::<HeatMapTenant>(&heatmap_bytes)?;
     669              : 
     670              :         // Save the heatmap: this will be useful on restart, allowing us to reconstruct
     671              :         // layer metadata without having to re-download it.
     672            0 :         let heatmap_path = self.conf.tenant_heatmap_path(tenant_shard_id);
     673            0 : 
     674            0 :         let temp_path = path_with_suffix_extension(&heatmap_path, TEMP_FILE_SUFFIX);
     675            0 :         let context_msg = format!("write tenant {tenant_shard_id} heatmap to {heatmap_path}");
     676            0 :         let heatmap_path_bg = heatmap_path.clone();
     677            0 :         VirtualFile::crashsafe_overwrite(heatmap_path_bg, temp_path, heatmap_bytes)
     678            0 :             .await
     679            0 :             .maybe_fatal_err(&context_msg)?;
     680              : 
     681            0 :         tracing::debug!(
     682            0 :             "Wrote local heatmap to {}, with {} timelines",
     683            0 :             heatmap_path,
     684            0 :             heatmap.timelines.len()
     685              :         );
     686              : 
     687              :         // Get or initialize the local disk state for the timelines we will update
     688            0 :         let mut timeline_states = HashMap::new();
     689            0 :         for timeline in &heatmap.timelines {
     690            0 :             let timeline_state = self
     691            0 :                 .secondary_state
     692            0 :                 .detail
     693            0 :                 .lock()
     694            0 :                 .unwrap()
     695            0 :                 .timelines
     696            0 :                 .get(&timeline.timeline_id)
     697            0 :                 .cloned();
     698              : 
     699            0 :             let timeline_state = match timeline_state {
     700            0 :                 Some(t) => t,
     701              :                 None => {
     702              :                     // We have no existing state: need to scan local disk for layers first.
     703            0 :                     let timeline_state = init_timeline_state(
     704            0 :                         self.conf,
     705            0 :                         tenant_shard_id,
     706            0 :                         timeline,
     707            0 :                         &self.secondary_state.resident_size_metric,
     708            0 :                     )
     709            0 :                     .await;
     710              : 
     711              :                     // Re-acquire detail lock now that we're done with async load from local FS
     712            0 :                     self.secondary_state
     713            0 :                         .detail
     714            0 :                         .lock()
     715            0 :                         .unwrap()
     716            0 :                         .timelines
     717            0 :                         .insert(timeline.timeline_id, timeline_state.clone());
     718            0 :                     timeline_state
     719              :                 }
     720              :             };
     721              : 
     722            0 :             timeline_states.insert(timeline.timeline_id, timeline_state);
     723              :         }
     724              : 
     725              :         // Clean up any local layers that aren't in the heatmap.  We do this first for all timelines, on the general
     726              :         // principle that deletions should be done before writes wherever possible, and so that we can use this
     727              :         // phase to initialize our SecondaryProgress.
     728              :         {
     729            0 :             *self.secondary_state.progress.lock().unwrap() =
     730            0 :                 self.prepare_timelines(&heatmap, heatmap_mtime).await?;
     731              :         }
     732              : 
     733              :         // Calculate a deadline for downloads: if downloading takes longer than this, it is useful to drop out and start again,
     734              :         // so that we are always using reasonably a fresh heatmap.  Otherwise, if we had really huge content to download, we might
     735              :         // spend 10s of minutes downloading layers we don't need.
     736              :         // (see https://github.com/neondatabase/neon/issues/8182)
     737            0 :         let deadline = {
     738            0 :             let period = self
     739            0 :                 .secondary_state
     740            0 :                 .detail
     741            0 :                 .lock()
     742            0 :                 .unwrap()
     743            0 :                 .last_download
     744            0 :                 .as_ref()
     745            0 :                 .map(|d| d.upload_period)
     746            0 :                 .unwrap_or(DEFAULT_DOWNLOAD_INTERVAL);
     747            0 : 
     748            0 :             // Use double the period: we are not promising to complete within the period, this is just a heuristic
     749            0 :             // to keep using a "reasonably fresh" heatmap.
     750            0 :             Instant::now() + period * 2
     751              :         };
     752              : 
     753              :         // Download the layers in the heatmap
     754            0 :         for timeline in heatmap.timelines {
     755            0 :             let timeline_state = timeline_states
     756            0 :                 .remove(&timeline.timeline_id)
     757            0 :                 .expect("Just populated above");
     758            0 : 
     759            0 :             if self.secondary_state.cancel.is_cancelled() {
     760            0 :                 tracing::debug!(
     761            0 :                     "Cancelled before downloading timeline {}",
     762              :                     timeline.timeline_id
     763              :                 );
     764            0 :                 return Ok(());
     765            0 :             }
     766            0 : 
     767            0 :             let timeline_id = timeline.timeline_id;
     768            0 :             self.download_timeline(timeline, timeline_state, deadline, ctx)
     769            0 :                 .instrument(tracing::info_span!(
     770              :                     "secondary_download_timeline",
     771              :                     tenant_id=%tenant_shard_id.tenant_id,
     772            0 :                     shard_id=%tenant_shard_id.shard_slug(),
     773              :                     %timeline_id
     774              :                 ))
     775            0 :                 .await?;
     776              :         }
     777              : 
     778              :         // Metrics consistency check in testing builds
     779            0 :         self.secondary_state.validate_metrics();
     780            0 :         // Only update last_etag after a full successful download: this way will not skip
     781            0 :         // the next download, even if the heatmap's actual etag is unchanged.
     782            0 :         self.secondary_state.detail.lock().unwrap().last_download = Some(DownloadSummary {
     783            0 :             etag: heatmap_etag,
     784            0 :             mtime: heatmap_mtime,
     785            0 :             upload_period: heatmap
     786            0 :                 .upload_period_ms
     787            0 :                 .map(|ms| Duration::from_millis(ms as u64))
     788            0 :                 .unwrap_or(DEFAULT_DOWNLOAD_INTERVAL),
     789            0 :         });
     790            0 : 
     791            0 :         // Robustness: we should have updated progress properly, but in case we didn't, make sure
     792            0 :         // we don't leave the tenant in a state where we claim to have successfully downloaded
     793            0 :         // everything, but our progress is incomplete.  The invariant here should be that if
     794            0 :         // we have set `last_download` to this heatmap's etag, then the next time we see that
     795            0 :         // etag we can safely do no work (i.e. we must be complete).
     796            0 :         let mut progress = self.secondary_state.progress.lock().unwrap();
     797            0 :         debug_assert!(progress.layers_downloaded == progress.layers_total);
     798            0 :         debug_assert!(progress.bytes_downloaded == progress.bytes_total);
     799            0 :         if progress.layers_downloaded != progress.layers_total
     800            0 :             || progress.bytes_downloaded != progress.bytes_total
     801              :         {
     802            0 :             tracing::warn!("Correcting drift in progress stats ({progress:?})");
     803            0 :             progress.layers_downloaded = progress.layers_total;
     804            0 :             progress.bytes_downloaded = progress.bytes_total;
     805            0 :         }
     806              : 
     807            0 :         Ok(())
     808            0 :     }
     809              : 
     810              :     /// Do any fast local cleanup that comes before the much slower process of downloading
     811              :     /// layers from remote storage.  In the process, initialize the SecondaryProgress object
     812              :     /// that will later be updated incrementally as we download layers.
     813            0 :     async fn prepare_timelines(
     814            0 :         &self,
     815            0 :         heatmap: &HeatMapTenant,
     816            0 :         heatmap_mtime: SystemTime,
     817            0 :     ) -> Result<SecondaryProgress, UpdateError> {
     818            0 :         let heatmap_stats = heatmap.get_stats();
     819            0 :         // We will construct a progress object, and then populate its initial "downloaded" numbers
     820            0 :         // while iterating through local layer state in [`Self::prepare_timelines`]
     821            0 :         let mut progress = SecondaryProgress {
     822            0 :             layers_total: heatmap_stats.layers,
     823            0 :             bytes_total: heatmap_stats.bytes,
     824            0 :             heatmap_mtime: Some(serde_system_time::SystemTime(heatmap_mtime)),
     825            0 :             layers_downloaded: 0,
     826            0 :             bytes_downloaded: 0,
     827            0 :         };
     828            0 : 
     829            0 :         // Also expose heatmap bytes_total as a metric
     830            0 :         self.secondary_state
     831            0 :             .heatmap_total_size_metric
     832            0 :             .set(heatmap_stats.bytes);
     833            0 : 
     834            0 :         // Accumulate list of things to delete while holding the detail lock, for execution after dropping the lock
     835            0 :         let mut delete_layers = Vec::new();
     836            0 :         let mut delete_timelines = Vec::new();
     837            0 :         {
     838            0 :             let mut detail = self.secondary_state.detail.lock().unwrap();
     839            0 :             for (timeline_id, timeline_state) in &mut detail.timelines {
     840            0 :                 let Some(heatmap_timeline_index) = heatmap
     841            0 :                     .timelines
     842            0 :                     .iter()
     843            0 :                     .position(|t| t.timeline_id == *timeline_id)
     844              :                 else {
     845              :                     // This timeline is no longer referenced in the heatmap: delete it locally
     846            0 :                     delete_timelines.push(*timeline_id);
     847            0 :                     continue;
     848              :                 };
     849              : 
     850            0 :                 let heatmap_timeline = heatmap.timelines.get(heatmap_timeline_index).unwrap();
     851            0 : 
     852            0 :                 let layers_in_heatmap = heatmap_timeline
     853            0 :                     .layers
     854            0 :                     .iter()
     855            0 :                     .map(|l| (&l.name, l.metadata.generation))
     856            0 :                     .collect::<HashSet<_>>();
     857            0 :                 let layers_on_disk = timeline_state
     858            0 :                     .on_disk_layers
     859            0 :                     .iter()
     860            0 :                     .map(|l| (l.0, l.1.metadata.generation))
     861            0 :                     .collect::<HashSet<_>>();
     862            0 : 
     863            0 :                 let mut layer_count = layers_on_disk.len();
     864            0 :                 let mut layer_byte_count: u64 = timeline_state
     865            0 :                     .on_disk_layers
     866            0 :                     .values()
     867            0 :                     .map(|l| l.metadata.file_size)
     868            0 :                     .sum();
     869              : 
     870              :                 // Remove on-disk layers that are no longer present in heatmap
     871            0 :                 for (layer_file_name, generation) in layers_on_disk.difference(&layers_in_heatmap) {
     872            0 :                     layer_count -= 1;
     873            0 :                     layer_byte_count -= timeline_state
     874            0 :                         .on_disk_layers
     875            0 :                         .get(layer_file_name)
     876            0 :                         .unwrap()
     877            0 :                         .metadata
     878            0 :                         .file_size;
     879            0 : 
     880            0 :                     let local_path = local_layer_path(
     881            0 :                         self.conf,
     882            0 :                         self.secondary_state.get_tenant_shard_id(),
     883            0 :                         timeline_id,
     884            0 :                         layer_file_name,
     885            0 :                         generation,
     886            0 :                     );
     887            0 : 
     888            0 :                     delete_layers.push((*timeline_id, (*layer_file_name).clone(), local_path));
     889            0 :                 }
     890              : 
     891            0 :                 progress.bytes_downloaded += layer_byte_count;
     892            0 :                 progress.layers_downloaded += layer_count;
     893              :             }
     894              : 
     895            0 :             for delete_timeline in &delete_timelines {
     896            0 :                 // We haven't removed from disk yet, but optimistically remove from in-memory state: if removal
     897            0 :                 // from disk fails that will be a fatal error.
     898            0 :                 detail.remove_timeline(delete_timeline, &self.secondary_state.resident_size_metric);
     899            0 :             }
     900              :         }
     901              : 
     902              :         // Execute accumulated deletions
     903            0 :         for (timeline_id, layer_name, local_path) in delete_layers {
     904            0 :             tracing::info!(timeline_id=%timeline_id, "Removing secondary local layer {layer_name} because it's absent in heatmap",);
     905              : 
     906            0 :             tokio::fs::remove_file(&local_path)
     907            0 :                 .await
     908            0 :                 .or_else(fs_ext::ignore_not_found)
     909            0 :                 .maybe_fatal_err("Removing secondary layer")?;
     910              : 
     911              :             // Update in-memory housekeeping to reflect the absence of the deleted layer
     912            0 :             let mut detail = self.secondary_state.detail.lock().unwrap();
     913            0 :             let Some(timeline_state) = detail.timelines.get_mut(&timeline_id) else {
     914            0 :                 continue;
     915              :             };
     916            0 :             timeline_state.remove_layer(&layer_name, &self.secondary_state.resident_size_metric);
     917              :         }
     918              : 
     919            0 :         for timeline_id in delete_timelines {
     920            0 :             let timeline_path = self
     921            0 :                 .conf
     922            0 :                 .timeline_path(self.secondary_state.get_tenant_shard_id(), &timeline_id);
     923            0 :             tracing::info!(timeline_id=%timeline_id,
     924            0 :                 "Timeline no longer in heatmap, removing from secondary location"
     925              :             );
     926            0 :             tokio::fs::remove_dir_all(&timeline_path)
     927            0 :                 .await
     928            0 :                 .or_else(fs_ext::ignore_not_found)
     929            0 :                 .maybe_fatal_err("Removing secondary timeline")?;
     930              :         }
     931              : 
     932            0 :         Ok(progress)
     933            0 :     }
     934              : 
     935              :     /// Returns downloaded bytes if the etag differs from `prev_etag`, or None if the object
     936              :     /// still matches `prev_etag`.
     937            0 :     async fn download_heatmap(
     938            0 :         &self,
     939            0 :         prev_etag: Option<&Etag>,
     940            0 :     ) -> Result<HeatMapDownload, UpdateError> {
     941            0 :         debug_assert_current_span_has_tenant_id();
     942            0 :         let tenant_shard_id = self.secondary_state.get_tenant_shard_id();
     943            0 :         tracing::debug!("Downloading heatmap for secondary tenant",);
     944              : 
     945            0 :         let heatmap_path = remote_heatmap_path(tenant_shard_id);
     946            0 :         let cancel = &self.secondary_state.cancel;
     947            0 :         let opts = DownloadOpts {
     948            0 :             etag: prev_etag.cloned(),
     949            0 :             ..Default::default()
     950            0 :         };
     951            0 : 
     952            0 :         backoff::retry(
     953            0 :             || async {
     954            0 :                 let download = match self
     955            0 :                     .remote_storage
     956            0 :                     .download(&heatmap_path, &opts, cancel)
     957            0 :                     .await
     958              :                 {
     959            0 :                     Ok(download) => download,
     960            0 :                     Err(DownloadError::Unmodified) => return Ok(HeatMapDownload::Unmodified),
     961            0 :                     Err(err) => return Err(err.into()),
     962              :                 };
     963              : 
     964            0 :                 let mut heatmap_bytes = Vec::new();
     965            0 :                 let mut body = tokio_util::io::StreamReader::new(download.download_stream);
     966            0 :                 let _size = tokio::io::copy_buf(&mut body, &mut heatmap_bytes).await?;
     967            0 :                 Ok(HeatMapDownload::Modified(HeatMapModified {
     968            0 :                     etag: download.etag,
     969            0 :                     last_modified: download.last_modified,
     970            0 :                     bytes: heatmap_bytes,
     971            0 :                 }))
     972            0 :             },
     973            0 :             |e| matches!(e, UpdateError::NoData | UpdateError::Cancelled),
     974            0 :             FAILED_DOWNLOAD_WARN_THRESHOLD,
     975            0 :             FAILED_REMOTE_OP_RETRIES,
     976            0 :             "download heatmap",
     977            0 :             cancel,
     978            0 :         )
     979            0 :         .await
     980            0 :         .ok_or_else(|| UpdateError::Cancelled)
     981            0 :         .and_then(|x| x)
     982            0 :         .inspect(|_| SECONDARY_MODE.download_heatmap.inc())
     983            0 :     }
     984              : 
     985              :     /// Download heatmap layers that are not present on local disk, or update their
     986              :     /// access time if they are already present.
     987            0 :     async fn download_timeline_layers(
     988            0 :         &self,
     989            0 :         tenant_shard_id: &TenantShardId,
     990            0 :         timeline: HeatMapTimeline,
     991            0 :         timeline_state: SecondaryDetailTimeline,
     992            0 :         deadline: Instant,
     993            0 :         ctx: &RequestContext,
     994            0 :     ) -> (Result<(), UpdateError>, Vec<HeatMapLayer>) {
     995            0 :         // Accumulate updates to the state
     996            0 :         let mut touched = Vec::new();
     997              : 
     998            0 :         for layer in timeline.layers {
     999            0 :             if self.secondary_state.cancel.is_cancelled() {
    1000            0 :                 tracing::debug!("Cancelled -- dropping out of layer loop");
    1001            0 :                 return (Err(UpdateError::Cancelled), touched);
    1002            0 :             }
    1003            0 : 
    1004            0 :             if Instant::now() > deadline {
    1005              :                 // We've been running downloads for a while, restart to download latest heatmap.
    1006            0 :                 return (Err(UpdateError::Restart), touched);
    1007            0 :             }
    1008              : 
    1009              :             // Existing on-disk layers: just update their access time.
    1010            0 :             if let Some(on_disk) = timeline_state.on_disk_layers.get(&layer.name) {
    1011            0 :                 tracing::debug!("Layer {} is already on disk", layer.name);
    1012              : 
    1013            0 :                 if cfg!(debug_assertions) {
    1014              :                     // Debug for https://github.com/neondatabase/neon/issues/6966: check that the files we think
    1015              :                     // are already present on disk are really there.
    1016            0 :                     match tokio::fs::metadata(&on_disk.local_path).await {
    1017            0 :                         Ok(meta) => {
    1018            0 :                             tracing::debug!(
    1019            0 :                                 "Layer {} present at {}, size {}",
    1020            0 :                                 layer.name,
    1021            0 :                                 on_disk.local_path,
    1022            0 :                                 meta.len(),
    1023              :                             );
    1024              :                         }
    1025            0 :                         Err(e) => {
    1026            0 :                             tracing::warn!(
    1027            0 :                                 "Layer {} not found at {} ({})",
    1028              :                                 layer.name,
    1029              :                                 on_disk.local_path,
    1030              :                                 e
    1031              :                             );
    1032            0 :                             debug_assert!(false);
    1033              :                         }
    1034              :                     }
    1035            0 :                 }
    1036              : 
    1037            0 :                 if on_disk.metadata != layer.metadata || on_disk.access_time != layer.access_time {
    1038              :                     // We already have this layer on disk.  Update its access time.
    1039            0 :                     tracing::debug!(
    1040            0 :                         "Access time updated for layer {}: {} -> {}",
    1041            0 :                         layer.name,
    1042            0 :                         strftime(&on_disk.access_time),
    1043            0 :                         strftime(&layer.access_time)
    1044              :                     );
    1045            0 :                     touched.push(layer);
    1046            0 :                 }
    1047            0 :                 continue;
    1048              :             } else {
    1049            0 :                 tracing::debug!("Layer {} not present on disk yet", layer.name);
    1050              :             }
    1051              : 
    1052              :             // Eviction: if we evicted a layer, then do not re-download it unless it was accessed more
    1053              :             // recently than it was evicted.
    1054            0 :             if let Some(evicted_at) = timeline_state.evicted_at.get(&layer.name) {
    1055            0 :                 if &layer.access_time > evicted_at {
    1056            0 :                     tracing::info!(
    1057            0 :                         "Re-downloading evicted layer {}, accessed at {}, evicted at {}",
    1058            0 :                         layer.name,
    1059            0 :                         strftime(&layer.access_time),
    1060            0 :                         strftime(evicted_at)
    1061              :                     );
    1062              :                 } else {
    1063            0 :                     tracing::trace!(
    1064            0 :                         "Not re-downloading evicted layer {}, accessed at {}, evicted at {}",
    1065            0 :                         layer.name,
    1066            0 :                         strftime(&layer.access_time),
    1067            0 :                         strftime(evicted_at)
    1068              :                     );
    1069            0 :                     self.skip_layer(layer);
    1070            0 :                     continue;
    1071              :                 }
    1072            0 :             }
    1073              : 
    1074            0 :             match self
    1075            0 :                 .download_layer(tenant_shard_id, &timeline.timeline_id, layer, ctx)
    1076            0 :                 .await
    1077              :             {
    1078            0 :                 Ok(Some(layer)) => touched.push(layer),
    1079            0 :                 Ok(None) => {
    1080            0 :                     // Not an error but we didn't download it: remote layer is missing.  Don't add it to the list of
    1081            0 :                     // things to consider touched.
    1082            0 :                 }
    1083            0 :                 Err(e) => {
    1084            0 :                     return (Err(e), touched);
    1085              :                 }
    1086              :             }
    1087              :         }
    1088              : 
    1089            0 :         (Ok(()), touched)
    1090            0 :     }
    1091              : 
    1092            0 :     async fn download_timeline(
    1093            0 :         &self,
    1094            0 :         timeline: HeatMapTimeline,
    1095            0 :         timeline_state: SecondaryDetailTimeline,
    1096            0 :         deadline: Instant,
    1097            0 :         ctx: &RequestContext,
    1098            0 :     ) -> Result<(), UpdateError> {
    1099            0 :         debug_assert_current_span_has_tenant_and_timeline_id();
    1100            0 :         let tenant_shard_id = self.secondary_state.get_tenant_shard_id();
    1101            0 :         let timeline_id = timeline.timeline_id;
    1102            0 : 
    1103            0 :         tracing::debug!(timeline_id=%timeline_id, "Downloading layers, {} in heatmap", timeline.layers.len());
    1104              : 
    1105            0 :         let (result, touched) = self
    1106            0 :             .download_timeline_layers(tenant_shard_id, timeline, timeline_state, deadline, ctx)
    1107            0 :             .await;
    1108              : 
    1109              :         // Write updates to state to record layers we just downloaded or touched, irrespective of whether the overall result was successful
    1110              :         {
    1111            0 :             let mut detail = self.secondary_state.detail.lock().unwrap();
    1112            0 :             let timeline_detail = detail.timelines.entry(timeline_id).or_default();
    1113            0 : 
    1114            0 :             tracing::info!("Wrote timeline_detail for {} touched layers", touched.len());
    1115            0 :             touched.into_iter().for_each(|t| {
    1116            0 :                 timeline_detail.touch_layer(
    1117            0 :                     self.conf,
    1118            0 :                     tenant_shard_id,
    1119            0 :                     &timeline_id,
    1120            0 :                     &t,
    1121            0 :                     &self.secondary_state.resident_size_metric,
    1122            0 :                     || {
    1123            0 :                         local_layer_path(
    1124            0 :                             self.conf,
    1125            0 :                             tenant_shard_id,
    1126            0 :                             &timeline_id,
    1127            0 :                             &t.name,
    1128            0 :                             &t.metadata.generation,
    1129            0 :                         )
    1130            0 :                     },
    1131            0 :                 )
    1132            0 :             });
    1133            0 :         }
    1134            0 : 
    1135            0 :         result
    1136            0 :     }
    1137              : 
    1138              :     /// Call this during timeline download if a layer will _not_ be downloaded, to update progress statistics
    1139            0 :     fn skip_layer(&self, layer: HeatMapLayer) {
    1140            0 :         let mut progress = self.secondary_state.progress.lock().unwrap();
    1141            0 :         progress.layers_total = progress.layers_total.saturating_sub(1);
    1142            0 :         progress.bytes_total = progress
    1143            0 :             .bytes_total
    1144            0 :             .saturating_sub(layer.metadata.file_size);
    1145            0 :     }
    1146              : 
    1147            0 :     async fn download_layer(
    1148            0 :         &self,
    1149            0 :         tenant_shard_id: &TenantShardId,
    1150            0 :         timeline_id: &TimelineId,
    1151            0 :         layer: HeatMapLayer,
    1152            0 :         ctx: &RequestContext,
    1153            0 :     ) -> Result<Option<HeatMapLayer>, UpdateError> {
    1154            0 :         // Failpoints for simulating slow remote storage
    1155            0 :         failpoint_support::sleep_millis_async!(
    1156              :             "secondary-layer-download-sleep",
    1157            0 :             &self.secondary_state.cancel
    1158              :         );
    1159              : 
    1160            0 :         pausable_failpoint!("secondary-layer-download-pausable");
    1161              : 
    1162            0 :         let local_path = local_layer_path(
    1163            0 :             self.conf,
    1164            0 :             tenant_shard_id,
    1165            0 :             timeline_id,
    1166            0 :             &layer.name,
    1167            0 :             &layer.metadata.generation,
    1168            0 :         );
    1169            0 : 
    1170            0 :         // Note: no backoff::retry wrapper here because download_layer_file does its own retries internally
    1171            0 :         tracing::info!(
    1172            0 :             "Starting download of layer {}, size {}",
    1173              :             layer.name,
    1174              :             layer.metadata.file_size
    1175              :         );
    1176            0 :         let downloaded_bytes = download_layer_file(
    1177            0 :             self.conf,
    1178            0 :             self.remote_storage,
    1179            0 :             *tenant_shard_id,
    1180            0 :             *timeline_id,
    1181            0 :             &layer.name,
    1182            0 :             &layer.metadata,
    1183            0 :             &local_path,
    1184            0 :             &self.secondary_state.cancel,
    1185            0 :             ctx,
    1186            0 :         )
    1187            0 :         .await;
    1188              : 
    1189            0 :         let downloaded_bytes = match downloaded_bytes {
    1190            0 :             Ok(bytes) => bytes,
    1191              :             Err(DownloadError::NotFound) => {
    1192              :                 // A heatmap might be out of date and refer to a layer that doesn't exist any more.
    1193              :                 // This is harmless: continue to download the next layer. It is expected during compaction
    1194              :                 // GC.
    1195            0 :                 tracing::debug!(
    1196            0 :                     "Skipped downloading missing layer {}, raced with compaction/gc?",
    1197              :                     layer.name
    1198              :                 );
    1199            0 :                 self.skip_layer(layer);
    1200            0 : 
    1201            0 :                 return Ok(None);
    1202              :             }
    1203            0 :             Err(e) => return Err(e.into()),
    1204              :         };
    1205              : 
    1206            0 :         if downloaded_bytes != layer.metadata.file_size {
    1207            0 :             let local_path = local_layer_path(
    1208            0 :                 self.conf,
    1209            0 :                 tenant_shard_id,
    1210            0 :                 timeline_id,
    1211            0 :                 &layer.name,
    1212            0 :                 &layer.metadata.generation,
    1213            0 :             );
    1214            0 : 
    1215            0 :             tracing::warn!(
    1216            0 :                 "Downloaded layer {} with unexpected size {} != {}.  Removing download.",
    1217              :                 layer.name,
    1218              :                 downloaded_bytes,
    1219              :                 layer.metadata.file_size
    1220              :             );
    1221              : 
    1222            0 :             tokio::fs::remove_file(&local_path)
    1223            0 :                 .await
    1224            0 :                 .or_else(fs_ext::ignore_not_found)?;
    1225              :         } else {
    1226            0 :             tracing::info!("Downloaded layer {}, size {}", layer.name, downloaded_bytes);
    1227            0 :             let mut progress = self.secondary_state.progress.lock().unwrap();
    1228            0 :             progress.bytes_downloaded += downloaded_bytes;
    1229            0 :             progress.layers_downloaded += 1;
    1230              :         }
    1231              : 
    1232            0 :         SECONDARY_MODE.download_layer.inc();
    1233            0 : 
    1234            0 :         Ok(Some(layer))
    1235            0 :     }
    1236              : }
    1237              : 
    1238              : /// Scan local storage and build up Layer objects based on the metadata in a HeatMapTimeline
    1239            0 : async fn init_timeline_state(
    1240            0 :     conf: &'static PageServerConf,
    1241            0 :     tenant_shard_id: &TenantShardId,
    1242            0 :     heatmap: &HeatMapTimeline,
    1243            0 :     resident_metric: &UIntGauge,
    1244            0 : ) -> SecondaryDetailTimeline {
    1245            0 :     let timeline_path = conf.timeline_path(tenant_shard_id, &heatmap.timeline_id);
    1246            0 :     let mut detail = SecondaryDetailTimeline::default();
    1247              : 
    1248            0 :     let mut dir = match tokio::fs::read_dir(&timeline_path).await {
    1249            0 :         Ok(d) => d,
    1250            0 :         Err(e) => {
    1251            0 :             if e.kind() == std::io::ErrorKind::NotFound {
    1252            0 :                 let context = format!("Creating timeline directory {timeline_path}");
    1253            0 :                 tracing::info!("{}", context);
    1254            0 :                 tokio::fs::create_dir_all(&timeline_path)
    1255            0 :                     .await
    1256            0 :                     .fatal_err(&context);
    1257            0 : 
    1258            0 :                 // No entries to report: drop out.
    1259            0 :                 return detail;
    1260              :             } else {
    1261            0 :                 on_fatal_io_error(&e, &format!("Reading timeline dir {timeline_path}"));
    1262              :             }
    1263              :         }
    1264              :     };
    1265              : 
    1266              :     // As we iterate through layers found on disk, we will look up their metadata from this map.
    1267              :     // Layers not present in metadata will be discarded.
    1268            0 :     let heatmap_metadata: HashMap<&LayerName, &HeatMapLayer> =
    1269            0 :         heatmap.layers.iter().map(|l| (&l.name, l)).collect();
    1270              : 
    1271            0 :     while let Some(dentry) = dir
    1272            0 :         .next_entry()
    1273            0 :         .await
    1274            0 :         .fatal_err(&format!("Listing {timeline_path}"))
    1275              :     {
    1276            0 :         let Ok(file_path) = Utf8PathBuf::from_path_buf(dentry.path()) else {
    1277            0 :             tracing::warn!("Malformed filename at {}", dentry.path().to_string_lossy());
    1278            0 :             continue;
    1279              :         };
    1280            0 :         let local_meta = dentry
    1281            0 :             .metadata()
    1282            0 :             .await
    1283            0 :             .fatal_err(&format!("Read metadata on {}", file_path));
    1284            0 : 
    1285            0 :         let file_name = file_path.file_name().expect("created it from the dentry");
    1286            0 :         if crate::is_temporary(&file_path)
    1287            0 :             || is_temp_download_file(&file_path)
    1288            0 :             || is_ephemeral_file(file_name)
    1289              :         {
    1290              :             // Temporary files are frequently left behind from restarting during downloads
    1291            0 :             tracing::info!("Cleaning up temporary file {file_path}");
    1292            0 :             if let Err(e) = tokio::fs::remove_file(&file_path)
    1293            0 :                 .await
    1294            0 :                 .or_else(fs_ext::ignore_not_found)
    1295              :             {
    1296            0 :                 tracing::error!("Failed to remove temporary file {file_path}: {e}");
    1297            0 :             }
    1298            0 :             continue;
    1299            0 :         }
    1300            0 : 
    1301            0 :         match LayerName::from_str(file_name) {
    1302            0 :             Ok(name) => {
    1303            0 :                 let remote_meta = heatmap_metadata.get(&name);
    1304            0 :                 match remote_meta {
    1305            0 :                     Some(remote_meta) => {
    1306            0 :                         // TODO: checksums for layers (https://github.com/neondatabase/neon/issues/2784)
    1307            0 :                         if local_meta.len() != remote_meta.metadata.file_size {
    1308              :                             // This should not happen, because we do crashsafe write-then-rename when downloading
    1309              :                             // layers, and layers in remote storage are immutable.  Remove the local file because
    1310              :                             // we cannot trust it.
    1311            0 :                             tracing::warn!(
    1312            0 :                                 "Removing local layer {name} with unexpected local size {} != {}",
    1313            0 :                                 local_meta.len(),
    1314              :                                 remote_meta.metadata.file_size
    1315              :                             );
    1316            0 :                         } else {
    1317            0 :                             // We expect the access time to be initialized immediately afterwards, when
    1318            0 :                             // the latest heatmap is applied to the state.
    1319            0 :                             detail.touch_layer(
    1320            0 :                                 conf,
    1321            0 :                                 tenant_shard_id,
    1322            0 :                                 &heatmap.timeline_id,
    1323            0 :                                 remote_meta,
    1324            0 :                                 resident_metric,
    1325            0 :                                 || file_path,
    1326            0 :                             );
    1327            0 :                         }
    1328              :                     }
    1329              :                     None => {
    1330              :                         // FIXME: consider some optimization when transitioning from attached to secondary: maybe
    1331              :                         // wait until we have seen a heatmap that is more recent than the most recent on-disk state?  Otherwise
    1332              :                         // we will end up deleting any layers which were created+uploaded more recently than the heatmap.
    1333            0 :                         tracing::info!(
    1334            0 :                             "Removing secondary local layer {} because it's absent in heatmap",
    1335              :                             name
    1336              :                         );
    1337            0 :                         tokio::fs::remove_file(&dentry.path())
    1338            0 :                             .await
    1339            0 :                             .or_else(fs_ext::ignore_not_found)
    1340            0 :                             .fatal_err(&format!(
    1341            0 :                                 "Removing layer {}",
    1342            0 :                                 dentry.path().to_string_lossy()
    1343            0 :                             ));
    1344              :                     }
    1345              :                 }
    1346              :             }
    1347              :             Err(_) => {
    1348              :                 // Ignore it.
    1349            0 :                 tracing::warn!("Unexpected file in timeline directory: {file_name}");
    1350              :             }
    1351              :         }
    1352              :     }
    1353              : 
    1354            0 :     detail
    1355            0 : }
        

Generated by: LCOV version 2.1-beta