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