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

Generated by: LCOV version 2.1-beta