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