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

Generated by: LCOV version 2.1-beta