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