Line data Source code
1 : use anyhow::Context;
2 : use camino::{Utf8Path, Utf8PathBuf};
3 : use pageserver_api::keyspace::KeySpace;
4 : use pageserver_api::models::HistoricLayerInfo;
5 : use pageserver_api::shard::{ShardIdentity, ShardIndex, TenantShardId};
6 : use std::ops::Range;
7 : use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
8 : use std::sync::{Arc, Weak};
9 : use std::time::{Duration, SystemTime};
10 : use tracing::Instrument;
11 : use utils::id::TimelineId;
12 : use utils::lsn::Lsn;
13 : use utils::sync::{gate, heavier_once_cell};
14 :
15 : use crate::config::PageServerConf;
16 : use crate::context::{DownloadBehavior, RequestContext, RequestContextBuilder};
17 : use crate::span::debug_assert_current_span_has_tenant_and_timeline_id;
18 : use crate::task_mgr::TaskKind;
19 : use crate::tenant::timeline::{CompactionError, GetVectoredError};
20 : use crate::tenant::{remote_timeline_client::LayerFileMetadata, Timeline};
21 :
22 : use super::delta_layer::{self, DeltaEntry};
23 : use super::image_layer::{self};
24 : use super::{
25 : AsLayerDesc, ImageLayerWriter, LayerAccessStats, LayerAccessStatsReset, LayerName,
26 : LayerVisibilityHint, PersistentLayerDesc, ValuesReconstructState,
27 : };
28 :
29 : use utils::generation::Generation;
30 :
31 : #[cfg(test)]
32 : mod tests;
33 :
34 : #[cfg(test)]
35 : mod failpoints;
36 :
37 : pub const S3_UPLOAD_LIMIT: u64 = 4_500_000_000;
38 :
39 : /// A Layer contains all data in a "rectangle" consisting of a range of keys and
40 : /// range of LSNs.
41 : ///
42 : /// There are two kinds of layers, in-memory and on-disk layers. In-memory
43 : /// layers are used to ingest incoming WAL, and provide fast access to the
44 : /// recent page versions. On-disk layers are stored as files on disk, and are
45 : /// immutable. This type represents the on-disk kind while in-memory kind are represented by
46 : /// [`InMemoryLayer`].
47 : ///
48 : /// Furthermore, there are two kinds of on-disk layers: delta and image layers.
49 : /// A delta layer contains all modifications within a range of LSNs and keys.
50 : /// An image layer is a snapshot of all the data in a key-range, at a single
51 : /// LSN.
52 : ///
53 : /// This type models the on-disk layers, which can be evicted and on-demand downloaded. As a
54 : /// general goal, read accesses should always win eviction and eviction should not wait for
55 : /// download.
56 : ///
57 : /// ### State transitions
58 : ///
59 : /// The internal state of `Layer` is composed of most importantly the on-filesystem state and the
60 : /// [`ResidentOrWantedEvicted`] enum. On-filesystem state can be either present (fully downloaded,
61 : /// right size) or deleted.
62 : ///
63 : /// Reads will always win requests to evict until `wait_for_turn_and_evict` has acquired the
64 : /// `heavier_once_cell::InitPermit` and has started to `evict_blocking`. Before the
65 : /// `heavier_once_cell::InitPermit` has been acquired, any read request
66 : /// (`get_or_maybe_download`) can "re-initialize" using the existing downloaded file and thus
67 : /// cancelling the eviction.
68 : ///
69 : /// ```text
70 : /// +-----------------+ get_or_maybe_download +--------------------------------+
71 : /// | not initialized |--------------------------->| Resident(Arc<DownloadedLayer>) |
72 : /// | ENOENT | /->| |
73 : /// +-----------------+ | +--------------------------------+
74 : /// ^ | | ^
75 : /// | get_or_maybe_download | | | get_or_maybe_download, either:
76 : /// evict_blocking | /-------------------------/ | | - upgrade weak to strong
77 : /// | | | | - re-initialize without download
78 : /// | | evict_and_wait | |
79 : /// +-----------------+ v |
80 : /// | not initialized | on_downloaded_layer_drop +--------------------------------------+
81 : /// | file is present |<---------------------------| WantedEvicted(Weak<DownloadedLayer>) |
82 : /// +-----------------+ +--------------------------------------+
83 : /// ```
84 : ///
85 : /// ### Unsupported
86 : ///
87 : /// - Evicting by the operator deleting files from the filesystem
88 : ///
89 : /// [`InMemoryLayer`]: super::inmemory_layer::InMemoryLayer
90 : #[derive(Clone)]
91 : pub(crate) struct Layer(Arc<LayerInner>);
92 :
93 : impl std::fmt::Display for Layer {
94 5760 : fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
95 5760 : write!(
96 5760 : f,
97 5760 : "{}{}",
98 5760 : self.layer_desc().short_id(),
99 5760 : self.0.generation.get_suffix()
100 5760 : )
101 5760 : }
102 : }
103 :
104 : impl std::fmt::Debug for Layer {
105 0 : fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
106 0 : write!(f, "{}", self)
107 0 : }
108 : }
109 :
110 : impl AsLayerDesc for Layer {
111 1508510 : fn layer_desc(&self) -> &PersistentLayerDesc {
112 1508510 : self.0.layer_desc()
113 1508510 : }
114 : }
115 :
116 : impl PartialEq for Layer {
117 8 : fn eq(&self, other: &Self) -> bool {
118 8 : Arc::as_ptr(&self.0) == Arc::as_ptr(&other.0)
119 8 : }
120 : }
121 :
122 5148 : pub(crate) fn local_layer_path(
123 5148 : conf: &PageServerConf,
124 5148 : tenant_shard_id: &TenantShardId,
125 5148 : timeline_id: &TimelineId,
126 5148 : layer_file_name: &LayerName,
127 5148 : generation: &Generation,
128 5148 : ) -> Utf8PathBuf {
129 5148 : let timeline_path = conf.timeline_path(tenant_shard_id, timeline_id);
130 5148 :
131 5148 : if generation.is_none() {
132 : // Without a generation, we may only use legacy path style
133 0 : timeline_path.join(layer_file_name.to_string())
134 : } else {
135 5148 : timeline_path.join(format!("{}-v1{}", layer_file_name, generation.get_suffix()))
136 : }
137 5148 : }
138 :
139 : impl Layer {
140 : /// Creates a layer value for a file we know to not be resident.
141 0 : pub(crate) fn for_evicted(
142 0 : conf: &'static PageServerConf,
143 0 : timeline: &Arc<Timeline>,
144 0 : file_name: LayerName,
145 0 : metadata: LayerFileMetadata,
146 0 : ) -> Self {
147 0 : let local_path = local_layer_path(
148 0 : conf,
149 0 : &timeline.tenant_shard_id,
150 0 : &timeline.timeline_id,
151 0 : &file_name,
152 0 : &metadata.generation,
153 0 : );
154 0 :
155 0 : let desc = PersistentLayerDesc::from_filename(
156 0 : timeline.tenant_shard_id,
157 0 : timeline.timeline_id,
158 0 : file_name,
159 0 : metadata.file_size,
160 0 : );
161 0 :
162 0 : let owner = Layer(Arc::new(LayerInner::new(
163 0 : conf,
164 0 : timeline,
165 0 : local_path,
166 0 : desc,
167 0 : None,
168 0 : metadata.generation,
169 0 : metadata.shard,
170 0 : )));
171 0 :
172 0 : debug_assert!(owner.0.needs_download_blocking().unwrap().is_some());
173 :
174 0 : owner
175 0 : }
176 :
177 : /// Creates a Layer value for a file we know to be resident in timeline directory.
178 72 : pub(crate) fn for_resident(
179 72 : conf: &'static PageServerConf,
180 72 : timeline: &Arc<Timeline>,
181 72 : local_path: Utf8PathBuf,
182 72 : file_name: LayerName,
183 72 : metadata: LayerFileMetadata,
184 72 : ) -> ResidentLayer {
185 72 : let desc = PersistentLayerDesc::from_filename(
186 72 : timeline.tenant_shard_id,
187 72 : timeline.timeline_id,
188 72 : file_name,
189 72 : metadata.file_size,
190 72 : );
191 72 :
192 72 : let mut resident = None;
193 72 :
194 72 : let owner = Layer(Arc::new_cyclic(|owner| {
195 72 : let inner = Arc::new(DownloadedLayer {
196 72 : owner: owner.clone(),
197 72 : kind: tokio::sync::OnceCell::default(),
198 72 : version: 0,
199 72 : });
200 72 : resident = Some(inner.clone());
201 72 :
202 72 : LayerInner::new(
203 72 : conf,
204 72 : timeline,
205 72 : local_path,
206 72 : desc,
207 72 : Some(inner),
208 72 : metadata.generation,
209 72 : metadata.shard,
210 72 : )
211 72 : }));
212 72 :
213 72 : let downloaded = resident.expect("just initialized");
214 72 :
215 72 : debug_assert!(owner.0.needs_download_blocking().unwrap().is_none());
216 :
217 72 : timeline
218 72 : .metrics
219 72 : .resident_physical_size_add(metadata.file_size);
220 72 :
221 72 : ResidentLayer { downloaded, owner }
222 72 : }
223 :
224 : /// Creates a Layer value for freshly written out new layer file by renaming it from a
225 : /// temporary path.
226 5124 : pub(crate) fn finish_creating(
227 5124 : conf: &'static PageServerConf,
228 5124 : timeline: &Arc<Timeline>,
229 5124 : desc: PersistentLayerDesc,
230 5124 : temp_path: &Utf8Path,
231 5124 : ) -> anyhow::Result<ResidentLayer> {
232 5124 : let mut resident = None;
233 5124 :
234 5124 : let owner = Layer(Arc::new_cyclic(|owner| {
235 5124 : let inner = Arc::new(DownloadedLayer {
236 5124 : owner: owner.clone(),
237 5124 : kind: tokio::sync::OnceCell::default(),
238 5124 : version: 0,
239 5124 : });
240 5124 : resident = Some(inner.clone());
241 5124 :
242 5124 : let local_path = local_layer_path(
243 5124 : conf,
244 5124 : &timeline.tenant_shard_id,
245 5124 : &timeline.timeline_id,
246 5124 : &desc.layer_name(),
247 5124 : &timeline.generation,
248 5124 : );
249 5124 :
250 5124 : LayerInner::new(
251 5124 : conf,
252 5124 : timeline,
253 5124 : local_path,
254 5124 : desc,
255 5124 : Some(inner),
256 5124 : timeline.generation,
257 5124 : timeline.get_shard_index(),
258 5124 : )
259 5124 : }));
260 5124 :
261 5124 : let downloaded = resident.expect("just initialized");
262 5124 :
263 5124 : // We never want to overwrite an existing file, so we use `RENAME_NOREPLACE`.
264 5124 : // TODO: this leaves the temp file in place if the rename fails, risking us running
265 5124 : // out of space. Should we clean it up here or does the calling context deal with this?
266 5124 : utils::fs_ext::rename_noreplace(temp_path.as_std_path(), owner.local_path().as_std_path())
267 5124 : .with_context(|| format!("rename temporary file as correct path for {owner}"))?;
268 :
269 5124 : Ok(ResidentLayer { downloaded, owner })
270 5124 : }
271 :
272 : /// Requests the layer to be evicted and waits for this to be done.
273 : ///
274 : /// If the file is not resident, an [`EvictionError::NotFound`] is returned.
275 : ///
276 : /// If for a bad luck or blocking of the executor, we miss the actual eviction and the layer is
277 : /// re-downloaded, [`EvictionError::Downloaded`] is returned.
278 : ///
279 : /// Timeout is mandatory, because waiting for eviction is only needed for our tests; eviction
280 : /// will happen regardless the future returned by this method completing unless there is a
281 : /// read access before eviction gets to complete.
282 : ///
283 : /// Technically cancellation safe, but cancelling might shift the viewpoint of what generation
284 : /// of download-evict cycle on retry.
285 108 : pub(crate) async fn evict_and_wait(&self, timeout: Duration) -> Result<(), EvictionError> {
286 149 : self.0.evict_and_wait(timeout).await
287 96 : }
288 :
289 : /// Delete the layer file when the `self` gets dropped, also try to schedule a remote index upload
290 : /// then.
291 : ///
292 : /// On drop, this will cause a call to [`crate::tenant::remote_timeline_client::RemoteTimelineClient::schedule_deletion_of_unlinked`].
293 : /// This means that the unlinking by [gc] or [compaction] must have happened strictly before
294 : /// the value this is called on gets dropped.
295 : ///
296 : /// This is ensured by both of those methods accepting references to Layer.
297 : ///
298 : /// [gc]: [`RemoteTimelineClient::schedule_gc_update`]
299 : /// [compaction]: [`RemoteTimelineClient::schedule_compaction_update`]
300 1410 : pub(crate) fn delete_on_drop(&self) {
301 1410 : self.0.delete_on_drop();
302 1410 : }
303 :
304 636645 : pub(crate) async fn get_values_reconstruct_data(
305 636645 : &self,
306 636645 : keyspace: KeySpace,
307 636645 : lsn_range: Range<Lsn>,
308 636645 : reconstruct_data: &mut ValuesReconstructState,
309 636645 : ctx: &RequestContext,
310 636645 : ) -> Result<(), GetVectoredError> {
311 636645 : let layer = self
312 636645 : .0
313 636645 : .get_or_maybe_download(true, Some(ctx))
314 11 : .await
315 636645 : .map_err(|err| match err {
316 : DownloadError::TimelineShutdown | DownloadError::DownloadCancelled => {
317 0 : GetVectoredError::Cancelled
318 : }
319 0 : other => GetVectoredError::Other(anyhow::anyhow!(other)),
320 636645 : })?;
321 :
322 636645 : self.record_access(ctx);
323 636645 :
324 636645 : layer
325 636645 : .get_values_reconstruct_data(keyspace, lsn_range, reconstruct_data, &self.0, ctx)
326 636645 : .instrument(tracing::debug_span!("get_values_reconstruct_data", layer=%self))
327 285885 : .await
328 636645 : .map_err(|err| match err {
329 0 : GetVectoredError::Other(err) => GetVectoredError::Other(
330 0 : err.context(format!("get_values_reconstruct_data for layer {self}")),
331 0 : ),
332 0 : err => err,
333 636645 : })
334 636645 : }
335 :
336 : /// Download the layer if evicted.
337 : ///
338 : /// Will not error when the layer is already downloaded.
339 0 : pub(crate) async fn download(&self) -> anyhow::Result<()> {
340 0 : self.0.get_or_maybe_download(true, None).await?;
341 0 : Ok(())
342 0 : }
343 :
344 : /// Assuming the layer is already downloaded, returns a guard which will prohibit eviction
345 : /// while the guard exists.
346 : ///
347 : /// Returns None if the layer is currently evicted or becoming evicted.
348 : #[cfg(test)]
349 60 : pub(crate) async fn keep_resident(&self) -> Option<ResidentLayer> {
350 60 : let downloaded = self.0.inner.get().and_then(|rowe| rowe.get())?;
351 :
352 42 : Some(ResidentLayer {
353 42 : downloaded,
354 42 : owner: self.clone(),
355 42 : })
356 60 : }
357 :
358 : /// Weak indicator of is the layer resident or not. Good enough for eviction, which can deal
359 : /// with `EvictionError::NotFound`.
360 : ///
361 : /// Returns `true` if this layer might be resident, or `false`, if it most likely evicted or
362 : /// will be unless a read happens soon.
363 158 : pub(crate) fn is_likely_resident(&self) -> bool {
364 158 : self.0
365 158 : .inner
366 158 : .get()
367 158 : .map(|rowe| rowe.is_likely_resident())
368 158 : .unwrap_or(false)
369 158 : }
370 :
371 : /// Downloads if necessary and creates a guard, which will keep this layer from being evicted.
372 1488 : pub(crate) async fn download_and_keep_resident(&self) -> Result<ResidentLayer, DownloadError> {
373 1488 : let downloaded = self.0.get_or_maybe_download(true, None).await?;
374 :
375 1488 : Ok(ResidentLayer {
376 1488 : downloaded,
377 1488 : owner: self.clone(),
378 1488 : })
379 1488 : }
380 :
381 0 : pub(crate) fn info(&self, reset: LayerAccessStatsReset) -> HistoricLayerInfo {
382 0 : self.0.info(reset)
383 0 : }
384 :
385 24 : pub(crate) fn latest_activity(&self) -> SystemTime {
386 24 : self.0.access_stats.latest_activity()
387 24 : }
388 :
389 30 : pub(crate) fn visibility(&self) -> LayerVisibilityHint {
390 30 : self.0.access_stats.visibility()
391 30 : }
392 :
393 5130 : pub(crate) fn local_path(&self) -> &Utf8Path {
394 5130 : &self.0.path
395 5130 : }
396 :
397 5808 : pub(crate) fn metadata(&self) -> LayerFileMetadata {
398 5808 : self.0.metadata()
399 5808 : }
400 :
401 0 : pub(crate) fn get_timeline_id(&self) -> Option<TimelineId> {
402 0 : self.0
403 0 : .timeline
404 0 : .upgrade()
405 0 : .map(|timeline| timeline.timeline_id)
406 0 : }
407 :
408 : /// Traditional debug dumping facility
409 : #[allow(unused)]
410 12 : pub(crate) async fn dump(&self, verbose: bool, ctx: &RequestContext) -> anyhow::Result<()> {
411 12 : self.0.desc.dump();
412 12 :
413 12 : if verbose {
414 : // for now, unconditionally download everything, even if that might not be wanted.
415 12 : let l = self.0.get_or_maybe_download(true, Some(ctx)).await?;
416 24 : l.dump(&self.0, ctx).await?
417 0 : }
418 :
419 12 : Ok(())
420 12 : }
421 :
422 : /// Waits until this layer has been dropped (and if needed, local file deletion and remote
423 : /// deletion scheduling has completed).
424 : ///
425 : /// Does not start local deletion, use [`Self::delete_on_drop`] for that
426 : /// separatedly.
427 : #[cfg(any(feature = "testing", test))]
428 6 : pub(crate) fn wait_drop(&self) -> impl std::future::Future<Output = ()> + 'static {
429 6 : let mut rx = self.0.status.as_ref().unwrap().subscribe();
430 :
431 6 : async move {
432 : loop {
433 18 : if rx.changed().await.is_err() {
434 6 : break;
435 0 : }
436 : }
437 6 : }
438 6 : }
439 :
440 637851 : fn record_access(&self, ctx: &RequestContext) {
441 637851 : if self.0.access_stats.record_access(ctx) {
442 : // Visibility was modified to Visible: maybe log about this
443 0 : match ctx.task_kind() {
444 : TaskKind::CalculateSyntheticSize
445 : | TaskKind::GarbageCollector
446 0 : | TaskKind::MgmtRequest => {
447 0 : // This situation is expected in code paths do binary searches of the LSN space to resolve
448 0 : // an LSN to a timestamp, which happens during GC, during GC cutoff calculations in synthetic size,
449 0 : // and on-demand for certain HTTP API requests.
450 0 : }
451 : _ => {
452 : // In all other contexts, it is unusual to do I/O involving layers which are not visible at
453 : // some branch tip, so we log the fact that we are accessing something that the visibility
454 : // calculation thought should not be visible.
455 : //
456 : // This case is legal in brief time windows: for example an in-flight getpage request can hold on to a layer object
457 : // which was covered by a concurrent compaction.
458 0 : tracing::info!(
459 0 : "Layer {} became visible as a result of access",
460 0 : self.0.desc.key()
461 : );
462 : }
463 : }
464 :
465 : // Update the timeline's visible bytes count
466 0 : if let Some(tl) = self.0.timeline.upgrade() {
467 0 : tl.metrics
468 0 : .visible_physical_size_gauge
469 0 : .add(self.0.desc.file_size)
470 0 : }
471 637851 : }
472 637851 : }
473 :
474 924 : pub(crate) fn set_visibility(&self, visibility: LayerVisibilityHint) {
475 924 : let old_visibility = self.0.access_stats.set_visibility(visibility.clone());
476 : use LayerVisibilityHint::*;
477 924 : match (old_visibility, visibility) {
478 : (Visible, Covered) => {
479 : // Subtract this layer's contribution to the visible size metric
480 108 : if let Some(tl) = self.0.timeline.upgrade() {
481 108 : debug_assert!(
482 108 : tl.metrics.visible_physical_size_gauge.get() >= self.0.desc.file_size
483 : );
484 108 : tl.metrics
485 108 : .visible_physical_size_gauge
486 108 : .sub(self.0.desc.file_size)
487 0 : }
488 : }
489 : (Covered, Visible) => {
490 : // Add this layer's contribution to the visible size metric
491 0 : if let Some(tl) = self.0.timeline.upgrade() {
492 0 : tl.metrics
493 0 : .visible_physical_size_gauge
494 0 : .add(self.0.desc.file_size)
495 0 : }
496 : }
497 816 : (Covered, Covered) | (Visible, Visible) => {
498 816 : // no change
499 816 : }
500 : }
501 924 : }
502 : }
503 :
504 : /// The download-ness ([`DownloadedLayer`]) can be either resident or wanted evicted.
505 : ///
506 : /// However when we want something evicted, we cannot evict it right away as there might be current
507 : /// reads happening on it. For example: it has been searched from [`LayerMap::search`] but not yet
508 : /// read with [`Layer::get_values_reconstruct_data`].
509 : ///
510 : /// [`LayerMap::search`]: crate::tenant::layer_map::LayerMap::search
511 : #[derive(Debug)]
512 : enum ResidentOrWantedEvicted {
513 : Resident(Arc<DownloadedLayer>),
514 : WantedEvicted(Weak<DownloadedLayer>, usize),
515 : }
516 :
517 : impl ResidentOrWantedEvicted {
518 : /// Non-mutating access to the a DownloadedLayer, if possible.
519 : ///
520 : /// This is not used on the read path (anything that calls
521 : /// [`LayerInner::get_or_maybe_download`]) because it was decided that reads always win
522 : /// evictions, and part of that winning is using [`ResidentOrWantedEvicted::get_and_upgrade`].
523 : #[cfg(test)]
524 42 : fn get(&self) -> Option<Arc<DownloadedLayer>> {
525 42 : match self {
526 42 : ResidentOrWantedEvicted::Resident(strong) => Some(strong.clone()),
527 0 : ResidentOrWantedEvicted::WantedEvicted(weak, _) => weak.upgrade(),
528 : }
529 42 : }
530 :
531 : /// Best-effort query for residency right now, not as strong guarantee as receiving a strong
532 : /// reference from `ResidentOrWantedEvicted::get`.
533 140 : fn is_likely_resident(&self) -> bool {
534 140 : match self {
535 122 : ResidentOrWantedEvicted::Resident(_) => true,
536 18 : ResidentOrWantedEvicted::WantedEvicted(weak, _) => weak.strong_count() > 0,
537 : }
538 140 : }
539 :
540 : /// Upgrades any weak to strong if possible.
541 : ///
542 : /// Returns a strong reference if possible, along with a boolean telling if an upgrade
543 : /// happened.
544 638157 : fn get_and_upgrade(&mut self) -> Option<(Arc<DownloadedLayer>, bool)> {
545 638157 : match self {
546 638133 : ResidentOrWantedEvicted::Resident(strong) => Some((strong.clone(), false)),
547 24 : ResidentOrWantedEvicted::WantedEvicted(weak, _) => match weak.upgrade() {
548 0 : Some(strong) => {
549 0 : LAYER_IMPL_METRICS.inc_raced_wanted_evicted_accesses();
550 0 :
551 0 : *self = ResidentOrWantedEvicted::Resident(strong.clone());
552 0 :
553 0 : Some((strong, true))
554 : }
555 24 : None => None,
556 : },
557 : }
558 638157 : }
559 :
560 : /// When eviction is first requested, drop down to holding a [`Weak`].
561 : ///
562 : /// Returns `Some` if this was the first time eviction was requested. Care should be taken to
563 : /// drop the possibly last strong reference outside of the mutex of
564 : /// [`heavier_once_cell::OnceCell`].
565 90 : fn downgrade(&mut self) -> Option<Arc<DownloadedLayer>> {
566 90 : match self {
567 78 : ResidentOrWantedEvicted::Resident(strong) => {
568 78 : let weak = Arc::downgrade(strong);
569 78 : let mut temp = ResidentOrWantedEvicted::WantedEvicted(weak, strong.version);
570 78 : std::mem::swap(self, &mut temp);
571 78 : match temp {
572 78 : ResidentOrWantedEvicted::Resident(strong) => Some(strong),
573 0 : ResidentOrWantedEvicted::WantedEvicted(..) => unreachable!("just swapped"),
574 : }
575 : }
576 12 : ResidentOrWantedEvicted::WantedEvicted(..) => None,
577 : }
578 90 : }
579 : }
580 :
581 : struct LayerInner {
582 : /// Only needed to check ondemand_download_behavior_treat_error_as_warn and creation of
583 : /// [`Self::path`].
584 : conf: &'static PageServerConf,
585 :
586 : /// Full path to the file; unclear if this should exist anymore.
587 : path: Utf8PathBuf,
588 :
589 : desc: PersistentLayerDesc,
590 :
591 : /// Timeline access is needed for remote timeline client and metrics.
592 : ///
593 : /// There should not be an access to timeline for any reason without entering the
594 : /// [`Timeline::gate`] at the same time.
595 : timeline: Weak<Timeline>,
596 :
597 : access_stats: LayerAccessStats,
598 :
599 : /// This custom OnceCell is backed by std mutex, but only held for short time periods.
600 : ///
601 : /// Filesystem changes (download, evict) are only done while holding a permit which the
602 : /// `heavier_once_cell` provides.
603 : ///
604 : /// A number of fields in `Layer` are meant to only be updated when holding the InitPermit, but
605 : /// possibly read while not holding it.
606 : inner: heavier_once_cell::OnceCell<ResidentOrWantedEvicted>,
607 :
608 : /// Do we want to delete locally and remotely this when `LayerInner` is dropped
609 : wanted_deleted: AtomicBool,
610 :
611 : /// Version is to make sure we will only evict a specific initialization of the downloaded file.
612 : ///
613 : /// Incremented for each initialization, stored in `DownloadedLayer::version` or
614 : /// `ResidentOrWantedEvicted::WantedEvicted`.
615 : version: AtomicUsize,
616 :
617 : /// Allow subscribing to when the layer actually gets evicted, a non-cancellable download
618 : /// starts, or completes.
619 : ///
620 : /// Updates must only be posted while holding the InitPermit or the heavier_once_cell::Guard.
621 : /// Holding the InitPermit is the only time we can do state transitions, but we also need to
622 : /// cancel a pending eviction on upgrading a [`ResidentOrWantedEvicted::WantedEvicted`] back to
623 : /// [`ResidentOrWantedEvicted::Resident`] on access.
624 : ///
625 : /// The sender is wrapped in an Option to facilitate moving it out on [`LayerInner::drop`].
626 : status: Option<tokio::sync::watch::Sender<Status>>,
627 :
628 : /// Counter for exponential backoff with the download.
629 : ///
630 : /// This is atomic only for the purposes of having additional data only accessed while holding
631 : /// the InitPermit.
632 : consecutive_failures: AtomicUsize,
633 :
634 : /// The generation of this Layer.
635 : ///
636 : /// For loaded layers (resident or evicted) this comes from [`LayerFileMetadata::generation`],
637 : /// for created layers from [`Timeline::generation`].
638 : generation: Generation,
639 :
640 : /// The shard of this Layer.
641 : ///
642 : /// For layers created in this process, this will always be the [`ShardIndex`] of the
643 : /// current `ShardIdentity`` (TODO: add link once it's introduced).
644 : ///
645 : /// For loaded layers, this may be some other value if the tenant has undergone
646 : /// a shard split since the layer was originally written.
647 : shard: ShardIndex,
648 :
649 : /// When the Layer was last evicted but has not been downloaded since.
650 : ///
651 : /// This is used solely for updating metrics. See [`LayerImplMetrics::redownload_after`].
652 : last_evicted_at: std::sync::Mutex<Option<std::time::Instant>>,
653 :
654 : #[cfg(test)]
655 : failpoints: std::sync::Mutex<Vec<failpoints::Failpoint>>,
656 : }
657 :
658 : impl std::fmt::Display for LayerInner {
659 90 : fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
660 90 : write!(f, "{}", self.layer_desc().short_id())
661 90 : }
662 : }
663 :
664 : impl AsLayerDesc for LayerInner {
665 1515530 : fn layer_desc(&self) -> &PersistentLayerDesc {
666 1515530 : &self.desc
667 1515530 : }
668 : }
669 :
670 : #[derive(Debug, Clone, Copy)]
671 : enum Status {
672 : Resident,
673 : Evicted,
674 : Downloading,
675 : }
676 :
677 : impl Drop for LayerInner {
678 1722 : fn drop(&mut self) {
679 1722 : // if there was a pending eviction, mark it cancelled here to balance metrics
680 1722 : if let Some((ResidentOrWantedEvicted::WantedEvicted(..), _)) = self.inner.take_and_deinit()
681 6 : {
682 6 : // eviction has already been started
683 6 : LAYER_IMPL_METRICS.inc_eviction_cancelled(EvictionCancelled::LayerGone);
684 6 :
685 6 : // eviction request is intentionally not honored as no one is present to wait for it
686 6 : // and we could be delaying shutdown for nothing.
687 1716 : }
688 :
689 1722 : if let Some(timeline) = self.timeline.upgrade() {
690 : // Only need to decrement metrics if the timeline still exists: otherwise
691 : // it will have already de-registered these metrics via TimelineMetrics::shutdown
692 1674 : if self.desc.is_delta() {
693 1482 : timeline.metrics.layer_count_delta.dec();
694 1482 : timeline.metrics.layer_size_delta.sub(self.desc.file_size);
695 1482 : } else {
696 192 : timeline.metrics.layer_count_image.dec();
697 192 : timeline.metrics.layer_size_image.sub(self.desc.file_size);
698 192 : }
699 :
700 1674 : if matches!(self.access_stats.visibility(), LayerVisibilityHint::Visible) {
701 1656 : debug_assert!(
702 1656 : timeline.metrics.visible_physical_size_gauge.get() >= self.desc.file_size
703 : );
704 1656 : timeline
705 1656 : .metrics
706 1656 : .visible_physical_size_gauge
707 1656 : .sub(self.desc.file_size);
708 18 : }
709 48 : }
710 :
711 1722 : if !*self.wanted_deleted.get_mut() {
712 336 : return;
713 1386 : }
714 :
715 1386 : let span = tracing::info_span!(parent: None, "layer_delete", tenant_id = %self.layer_desc().tenant_shard_id.tenant_id, shard_id=%self.layer_desc().tenant_shard_id.shard_slug(), timeline_id = %self.layer_desc().timeline_id);
716 :
717 1386 : let path = std::mem::take(&mut self.path);
718 1386 : let file_name = self.layer_desc().layer_name();
719 1386 : let file_size = self.layer_desc().file_size;
720 1386 : let timeline = self.timeline.clone();
721 1386 : let meta = self.metadata();
722 1386 : let status = self.status.take();
723 1386 :
724 1386 : Self::spawn_blocking(move || {
725 1386 : let _g = span.entered();
726 1386 :
727 1386 : // carry this until we are finished for [`Layer::wait_drop`] support
728 1386 : let _status = status;
729 :
730 1386 : let Some(timeline) = timeline.upgrade() else {
731 : // no need to nag that timeline is gone: under normal situation on
732 : // task_mgr::remove_tenant_from_memory the timeline is gone before we get dropped.
733 0 : LAYER_IMPL_METRICS.inc_deletes_failed(DeleteFailed::TimelineGone);
734 0 : return;
735 : };
736 :
737 1386 : let Ok(_guard) = timeline.gate.enter() else {
738 0 : LAYER_IMPL_METRICS.inc_deletes_failed(DeleteFailed::TimelineGone);
739 0 : return;
740 : };
741 :
742 1386 : let removed = match std::fs::remove_file(path) {
743 1380 : Ok(()) => true,
744 6 : Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
745 6 : // until we no longer do detaches by removing all local files before removing the
746 6 : // tenant from the global map, we will always get these errors even if we knew what
747 6 : // is the latest state.
748 6 : //
749 6 : // we currently do not track the latest state, so we'll also end up here on evicted
750 6 : // layers.
751 6 : false
752 : }
753 0 : Err(e) => {
754 0 : tracing::error!("failed to remove wanted deleted layer: {e}");
755 0 : LAYER_IMPL_METRICS.inc_delete_removes_failed();
756 0 : false
757 : }
758 : };
759 :
760 1386 : if removed {
761 1380 : timeline.metrics.resident_physical_size_sub(file_size);
762 1380 : }
763 1386 : let res = timeline
764 1386 : .remote_client
765 1386 : .schedule_deletion_of_unlinked(vec![(file_name, meta)]);
766 :
767 1386 : if let Err(e) = res {
768 : // test_timeline_deletion_with_files_stuck_in_upload_queue is good at
769 : // demonstrating this deadlock (without spawn_blocking): stop will drop
770 : // queued items, which will have ResidentLayer's, and those drops would try
771 : // to re-entrantly lock the RemoteTimelineClient inner state.
772 0 : if !timeline.is_active() {
773 0 : tracing::info!("scheduling deletion on drop failed: {e:#}");
774 : } else {
775 0 : tracing::warn!("scheduling deletion on drop failed: {e:#}");
776 : }
777 0 : LAYER_IMPL_METRICS.inc_deletes_failed(DeleteFailed::DeleteSchedulingFailed);
778 1386 : } else {
779 1386 : LAYER_IMPL_METRICS.inc_completed_deletes();
780 1386 : }
781 1386 : });
782 1722 : }
783 : }
784 :
785 : impl LayerInner {
786 : #[allow(clippy::too_many_arguments)]
787 5196 : fn new(
788 5196 : conf: &'static PageServerConf,
789 5196 : timeline: &Arc<Timeline>,
790 5196 : local_path: Utf8PathBuf,
791 5196 : desc: PersistentLayerDesc,
792 5196 : downloaded: Option<Arc<DownloadedLayer>>,
793 5196 : generation: Generation,
794 5196 : shard: ShardIndex,
795 5196 : ) -> Self {
796 5196 : let (inner, version, init_status) = if let Some(inner) = downloaded {
797 5196 : let version = inner.version;
798 5196 : let resident = ResidentOrWantedEvicted::Resident(inner);
799 5196 : (
800 5196 : heavier_once_cell::OnceCell::new(resident),
801 5196 : version,
802 5196 : Status::Resident,
803 5196 : )
804 : } else {
805 0 : (heavier_once_cell::OnceCell::default(), 0, Status::Evicted)
806 : };
807 :
808 : // This object acts as a RAII guard on these metrics: increment on construction
809 5196 : if desc.is_delta() {
810 4266 : timeline.metrics.layer_count_delta.inc();
811 4266 : timeline.metrics.layer_size_delta.add(desc.file_size);
812 4266 : } else {
813 930 : timeline.metrics.layer_count_image.inc();
814 930 : timeline.metrics.layer_size_image.add(desc.file_size);
815 930 : }
816 :
817 : // New layers are visible by default. This metric is later updated on drop or in set_visibility
818 5196 : timeline
819 5196 : .metrics
820 5196 : .visible_physical_size_gauge
821 5196 : .add(desc.file_size);
822 5196 :
823 5196 : LayerInner {
824 5196 : conf,
825 5196 : path: local_path,
826 5196 : desc,
827 5196 : timeline: Arc::downgrade(timeline),
828 5196 : access_stats: Default::default(),
829 5196 : wanted_deleted: AtomicBool::new(false),
830 5196 : inner,
831 5196 : version: AtomicUsize::new(version),
832 5196 : status: Some(tokio::sync::watch::channel(init_status).0),
833 5196 : consecutive_failures: AtomicUsize::new(0),
834 5196 : generation,
835 5196 : shard,
836 5196 : last_evicted_at: std::sync::Mutex::default(),
837 5196 : #[cfg(test)]
838 5196 : failpoints: Default::default(),
839 5196 : }
840 5196 : }
841 :
842 1410 : fn delete_on_drop(&self) {
843 1410 : let res =
844 1410 : self.wanted_deleted
845 1410 : .compare_exchange(false, true, Ordering::Release, Ordering::Relaxed);
846 1410 :
847 1410 : if res.is_ok() {
848 1398 : LAYER_IMPL_METRICS.inc_started_deletes();
849 1398 : }
850 1410 : }
851 :
852 : /// Cancellation safe, however dropping the future and calling this method again might result
853 : /// in a new attempt to evict OR join the previously started attempt.
854 216 : #[tracing::instrument(level = tracing::Level::DEBUG, skip_all, ret, err(level = tracing::Level::DEBUG), fields(layer=%self))]
855 : pub(crate) async fn evict_and_wait(&self, timeout: Duration) -> Result<(), EvictionError> {
856 : let mut rx = self.status.as_ref().unwrap().subscribe();
857 :
858 : {
859 : let current = rx.borrow_and_update();
860 : match &*current {
861 : Status::Resident => {
862 : // we might get lucky and evict this; continue
863 : }
864 : Status::Evicted | Status::Downloading => {
865 : // it is already evicted
866 : return Err(EvictionError::NotFound);
867 : }
868 : }
869 : }
870 :
871 : let strong = {
872 : match self.inner.get() {
873 : Some(mut either) => either.downgrade(),
874 : None => {
875 : // we already have a scheduled eviction, which just has not gotten to run yet.
876 : // it might still race with a read access, but that could also get cancelled,
877 : // so let's say this is not evictable.
878 : return Err(EvictionError::NotFound);
879 : }
880 : }
881 : };
882 :
883 : if strong.is_some() {
884 : // drop the DownloadedLayer outside of the holding the guard
885 : drop(strong);
886 :
887 : // idea here is that only one evicter should ever get to witness a strong reference,
888 : // which means whenever get_or_maybe_download upgrades a weak, it must mark up a
889 : // cancelled eviction and signal us, like it currently does.
890 : //
891 : // a second concurrent evict_and_wait will not see a strong reference.
892 : LAYER_IMPL_METRICS.inc_started_evictions();
893 : }
894 :
895 : let changed = rx.changed();
896 : let changed = tokio::time::timeout(timeout, changed).await;
897 :
898 : let Ok(changed) = changed else {
899 : return Err(EvictionError::Timeout);
900 : };
901 :
902 : let _: () = changed.expect("cannot be closed, because we are holding a strong reference");
903 :
904 : let current = rx.borrow_and_update();
905 :
906 : match &*current {
907 : // the easiest case
908 : Status::Evicted => Ok(()),
909 : // it surely was evicted in between, but then there was a new access now; we can't know
910 : // if it'll succeed so lets just call it evicted
911 : Status::Downloading => Ok(()),
912 : // either the download which was started after eviction completed already, or it was
913 : // never evicted
914 : Status::Resident => Err(EvictionError::Downloaded),
915 : }
916 : }
917 :
918 : /// Cancellation safe.
919 638181 : async fn get_or_maybe_download(
920 638181 : self: &Arc<Self>,
921 638181 : allow_download: bool,
922 638181 : ctx: Option<&RequestContext>,
923 638181 : ) -> Result<Arc<DownloadedLayer>, DownloadError> {
924 48 : let (weak, permit) = {
925 : // get_or_init_detached can:
926 : // - be fast (mutex lock) OR uncontested semaphore permit acquire
927 : // - be slow (wait for semaphore permit or closing)
928 638181 : let init_cancelled = scopeguard::guard((), |_| LAYER_IMPL_METRICS.inc_init_cancelled());
929 :
930 638181 : let locked = self
931 638181 : .inner
932 638181 : .get_or_init_detached()
933 5 : .await
934 638181 : .map(|mut guard| guard.get_and_upgrade().ok_or(guard));
935 638181 :
936 638181 : scopeguard::ScopeGuard::into_inner(init_cancelled);
937 :
938 638133 : match locked {
939 : // this path could had been a RwLock::read
940 638133 : Ok(Ok((strong, upgraded))) if !upgraded => return Ok(strong),
941 0 : Ok(Ok((strong, _))) => {
942 0 : // when upgraded back, the Arc<DownloadedLayer> is still available, but
943 0 : // previously a `evict_and_wait` was received. this is the only place when we
944 0 : // send out an update without holding the InitPermit.
945 0 : //
946 0 : // note that we also have dropped the Guard; this is fine, because we just made
947 0 : // a state change and are holding a strong reference to be returned.
948 0 : self.status.as_ref().unwrap().send_replace(Status::Resident);
949 0 : LAYER_IMPL_METRICS
950 0 : .inc_eviction_cancelled(EvictionCancelled::UpgradedBackOnAccess);
951 0 :
952 0 : return Ok(strong);
953 : }
954 24 : Ok(Err(guard)) => {
955 24 : // path to here: we won the eviction, the file should still be on the disk.
956 24 : let (weak, permit) = guard.take_and_deinit();
957 24 : (Some(weak), permit)
958 : }
959 24 : Err(permit) => (None, permit),
960 : }
961 : };
962 :
963 48 : if let Some(weak) = weak {
964 : // only drop the weak after dropping the heavier_once_cell guard
965 24 : assert!(
966 24 : matches!(weak, ResidentOrWantedEvicted::WantedEvicted(..)),
967 0 : "unexpected {weak:?}, ResidentOrWantedEvicted::get_and_upgrade has a bug"
968 : );
969 24 : }
970 :
971 48 : let timeline = self
972 48 : .timeline
973 48 : .upgrade()
974 48 : .ok_or_else(|| DownloadError::TimelineShutdown)?;
975 :
976 : // count cancellations, which currently remain largely unexpected
977 48 : let init_cancelled = scopeguard::guard((), |_| LAYER_IMPL_METRICS.inc_init_cancelled());
978 :
979 : // check if we really need to be downloaded: this can happen if a read access won the
980 : // semaphore before eviction.
981 : //
982 : // if we are cancelled while doing this `stat` the `self.inner` will be uninitialized. a
983 : // pending eviction will try to evict even upon finding an uninitialized `self.inner`.
984 48 : let needs_download = self
985 48 : .needs_download()
986 48 : .await
987 48 : .map_err(DownloadError::PreStatFailed);
988 48 :
989 48 : scopeguard::ScopeGuard::into_inner(init_cancelled);
990 :
991 48 : let needs_download = needs_download?;
992 :
993 48 : let Some(reason) = needs_download else {
994 : // the file is present locally because eviction has not had a chance to run yet
995 :
996 : #[cfg(test)]
997 24 : self.failpoint(failpoints::FailpointKind::AfterDeterminingLayerNeedsNoDownload)
998 6 : .await?;
999 :
1000 18 : LAYER_IMPL_METRICS.inc_init_needed_no_download();
1001 18 :
1002 18 : return Ok(self.initialize_after_layer_is_on_disk(permit));
1003 : };
1004 :
1005 : // we must download; getting cancelled before spawning the download is not an issue as
1006 : // any still running eviction would not find anything to evict.
1007 :
1008 24 : if let NeedsDownload::NotFile(ft) = reason {
1009 0 : return Err(DownloadError::NotFile(ft));
1010 24 : }
1011 :
1012 24 : if let Some(ctx) = ctx {
1013 6 : self.check_expected_download(ctx)?;
1014 18 : }
1015 :
1016 24 : if !allow_download {
1017 : // this is only used from tests, but it is hard to test without the boolean
1018 6 : return Err(DownloadError::DownloadRequired);
1019 18 : }
1020 18 :
1021 18 : let download_ctx = ctx
1022 18 : .map(|ctx| ctx.detached_child(TaskKind::LayerDownload, DownloadBehavior::Download))
1023 18 : .unwrap_or(RequestContext::new(
1024 18 : TaskKind::LayerDownload,
1025 18 : DownloadBehavior::Download,
1026 18 : ));
1027 :
1028 18 : async move {
1029 18 : tracing::info!(%reason, "downloading on-demand");
1030 :
1031 18 : let init_cancelled = scopeguard::guard((), |_| LAYER_IMPL_METRICS.inc_init_cancelled());
1032 18 : let res = self
1033 18 : .download_init_and_wait(timeline, permit, download_ctx)
1034 30 : .await?;
1035 18 : scopeguard::ScopeGuard::into_inner(init_cancelled);
1036 18 : Ok(res)
1037 18 : }
1038 18 : .instrument(tracing::info_span!("get_or_maybe_download", layer=%self))
1039 30 : .await
1040 638181 : }
1041 :
1042 : /// Nag or fail per RequestContext policy
1043 6 : fn check_expected_download(&self, ctx: &RequestContext) -> Result<(), DownloadError> {
1044 : use crate::context::DownloadBehavior::*;
1045 6 : let b = ctx.download_behavior();
1046 6 : match b {
1047 6 : Download => Ok(()),
1048 : Warn | Error => {
1049 0 : tracing::info!(
1050 0 : "unexpectedly on-demand downloading for task kind {:?}",
1051 0 : ctx.task_kind()
1052 : );
1053 0 : crate::metrics::UNEXPECTED_ONDEMAND_DOWNLOADS.inc();
1054 :
1055 0 : let really_error =
1056 0 : matches!(b, Error) && !self.conf.ondemand_download_behavior_treat_error_as_warn;
1057 :
1058 0 : if really_error {
1059 : // this check is only probablistic, seems like flakyness footgun
1060 0 : Err(DownloadError::ContextAndConfigReallyDeniesDownloads)
1061 : } else {
1062 0 : Ok(())
1063 : }
1064 : }
1065 : }
1066 6 : }
1067 :
1068 : /// Actual download, at most one is executed at the time.
1069 18 : async fn download_init_and_wait(
1070 18 : self: &Arc<Self>,
1071 18 : timeline: Arc<Timeline>,
1072 18 : permit: heavier_once_cell::InitPermit,
1073 18 : ctx: RequestContext,
1074 18 : ) -> Result<Arc<DownloadedLayer>, DownloadError> {
1075 18 : debug_assert_current_span_has_tenant_and_timeline_id();
1076 18 :
1077 18 : let (tx, rx) = tokio::sync::oneshot::channel();
1078 18 :
1079 18 : let this: Arc<Self> = self.clone();
1080 :
1081 18 : let guard = timeline
1082 18 : .gate
1083 18 : .enter()
1084 18 : .map_err(|_| DownloadError::DownloadCancelled)?;
1085 :
1086 18 : Self::spawn(
1087 18 : async move {
1088 0 : let _guard = guard;
1089 0 :
1090 0 : // now that we have commited to downloading, send out an update to:
1091 0 : // - unhang any pending eviction
1092 0 : // - break out of evict_and_wait
1093 0 : this.status
1094 0 : .as_ref()
1095 0 : .unwrap()
1096 0 : .send_replace(Status::Downloading);
1097 18 :
1098 18 : #[cfg(test)]
1099 18 : this.failpoint(failpoints::FailpointKind::WaitBeforeDownloading)
1100 6 : .await
1101 18 : .unwrap();
1102 :
1103 271 : let res = this.download_and_init(timeline, permit, &ctx).await;
1104 :
1105 18 : if let Err(res) = tx.send(res) {
1106 0 : match res {
1107 0 : Ok(_res) => {
1108 0 : tracing::debug!("layer initialized, but caller has been cancelled");
1109 0 : LAYER_IMPL_METRICS.inc_init_completed_without_requester();
1110 : }
1111 0 : Err(e) => {
1112 0 : tracing::info!(
1113 0 : "layer file download failed, and caller has been cancelled: {e:?}"
1114 : );
1115 0 : LAYER_IMPL_METRICS.inc_download_failed_without_requester();
1116 : }
1117 : }
1118 18 : }
1119 18 : }
1120 18 : .in_current_span(),
1121 18 : );
1122 18 :
1123 30 : match rx.await {
1124 18 : Ok(Ok(res)) => Ok(res),
1125 : Ok(Err(remote_storage::DownloadError::Cancelled)) => {
1126 0 : Err(DownloadError::DownloadCancelled)
1127 : }
1128 0 : Ok(Err(_)) => Err(DownloadError::DownloadFailed),
1129 0 : Err(_gone) => Err(DownloadError::DownloadCancelled),
1130 : }
1131 18 : }
1132 :
1133 18 : async fn download_and_init(
1134 18 : self: &Arc<LayerInner>,
1135 18 : timeline: Arc<Timeline>,
1136 18 : permit: heavier_once_cell::InitPermit,
1137 18 : ctx: &RequestContext,
1138 18 : ) -> Result<Arc<DownloadedLayer>, remote_storage::DownloadError> {
1139 18 : let result = timeline
1140 18 : .remote_client
1141 18 : .download_layer_file(
1142 18 : &self.desc.layer_name(),
1143 18 : &self.metadata(),
1144 18 : &self.path,
1145 18 : &timeline.cancel,
1146 18 : ctx,
1147 18 : )
1148 255 : .await;
1149 :
1150 18 : match result {
1151 18 : Ok(size) => {
1152 18 : assert_eq!(size, self.desc.file_size);
1153 :
1154 18 : match self.needs_download().await {
1155 0 : Ok(Some(reason)) => {
1156 0 : // this is really a bug in needs_download or remote timeline client
1157 0 : panic!("post-condition failed: needs_download returned {reason:?}");
1158 : }
1159 18 : Ok(None) => {
1160 18 : // as expected
1161 18 : }
1162 0 : Err(e) => {
1163 0 : panic!("post-condition failed: needs_download errored: {e:?}");
1164 : }
1165 : }
1166 :
1167 18 : tracing::info!(size=%self.desc.file_size, "on-demand download successful");
1168 18 : timeline
1169 18 : .metrics
1170 18 : .resident_physical_size_add(self.desc.file_size);
1171 18 : self.consecutive_failures.store(0, Ordering::Relaxed);
1172 18 :
1173 18 : let since_last_eviction = self
1174 18 : .last_evicted_at
1175 18 : .lock()
1176 18 : .unwrap()
1177 18 : .take()
1178 18 : .map(|ts| ts.elapsed());
1179 18 : if let Some(since_last_eviction) = since_last_eviction {
1180 18 : LAYER_IMPL_METRICS.record_redownloaded_after(since_last_eviction);
1181 18 : }
1182 :
1183 18 : self.access_stats.record_residence_event();
1184 18 :
1185 18 : Ok(self.initialize_after_layer_is_on_disk(permit))
1186 : }
1187 0 : Err(e) => {
1188 0 : let consecutive_failures =
1189 0 : 1 + self.consecutive_failures.fetch_add(1, Ordering::Relaxed);
1190 0 :
1191 0 : if timeline.cancel.is_cancelled() {
1192 : // If we're shutting down, drop out before logging the error
1193 0 : return Err(e);
1194 0 : }
1195 0 :
1196 0 : tracing::error!(consecutive_failures, "layer file download failed: {e:#}");
1197 :
1198 0 : let backoff = utils::backoff::exponential_backoff_duration_seconds(
1199 0 : consecutive_failures.min(u32::MAX as usize) as u32,
1200 0 : 1.5,
1201 0 : 60.0,
1202 0 : );
1203 0 :
1204 0 : let backoff = std::time::Duration::from_secs_f64(backoff);
1205 0 :
1206 0 : tokio::select! {
1207 0 : _ = tokio::time::sleep(backoff) => {},
1208 0 : _ = timeline.cancel.cancelled() => {},
1209 : };
1210 :
1211 0 : Err(e)
1212 : }
1213 : }
1214 18 : }
1215 :
1216 : /// Initializes the `Self::inner` to a "resident" state.
1217 : ///
1218 : /// Callers are assumed to ensure that the file is actually on disk with `Self::needs_download`
1219 : /// before calling this method.
1220 : ///
1221 : /// If this method is ever made async, it needs to be cancellation safe so that no state
1222 : /// changes are made before we can write to the OnceCell in non-cancellable fashion.
1223 36 : fn initialize_after_layer_is_on_disk(
1224 36 : self: &Arc<LayerInner>,
1225 36 : permit: heavier_once_cell::InitPermit,
1226 36 : ) -> Arc<DownloadedLayer> {
1227 36 : debug_assert_current_span_has_tenant_and_timeline_id();
1228 36 :
1229 36 : // disable any scheduled but not yet running eviction deletions for this initialization
1230 36 : let next_version = 1 + self.version.fetch_add(1, Ordering::Relaxed);
1231 36 : self.status.as_ref().unwrap().send_replace(Status::Resident);
1232 36 :
1233 36 : let res = Arc::new(DownloadedLayer {
1234 36 : owner: Arc::downgrade(self),
1235 36 : kind: tokio::sync::OnceCell::default(),
1236 36 : version: next_version,
1237 36 : });
1238 36 :
1239 36 : let waiters = self.inner.initializer_count();
1240 36 : if waiters > 0 {
1241 0 : tracing::info!(waiters, "completing layer init for other tasks");
1242 36 : }
1243 :
1244 36 : let value = ResidentOrWantedEvicted::Resident(res.clone());
1245 36 :
1246 36 : self.inner.set(value, permit);
1247 36 :
1248 36 : res
1249 36 : }
1250 :
1251 72 : async fn needs_download(&self) -> Result<Option<NeedsDownload>, std::io::Error> {
1252 72 : match tokio::fs::metadata(&self.path).await {
1253 48 : Ok(m) => Ok(self.is_file_present_and_good_size(&m).err()),
1254 24 : Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Some(NeedsDownload::NotFound)),
1255 0 : Err(e) => Err(e),
1256 : }
1257 72 : }
1258 :
1259 72 : fn needs_download_blocking(&self) -> Result<Option<NeedsDownload>, std::io::Error> {
1260 72 : match self.path.metadata() {
1261 72 : Ok(m) => Ok(self.is_file_present_and_good_size(&m).err()),
1262 0 : Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Some(NeedsDownload::NotFound)),
1263 0 : Err(e) => Err(e),
1264 : }
1265 72 : }
1266 :
1267 120 : fn is_file_present_and_good_size(&self, m: &std::fs::Metadata) -> Result<(), NeedsDownload> {
1268 120 : // in future, this should include sha2-256 validation of the file.
1269 120 : if !m.is_file() {
1270 0 : Err(NeedsDownload::NotFile(m.file_type()))
1271 120 : } else if m.len() != self.desc.file_size {
1272 0 : Err(NeedsDownload::WrongSize {
1273 0 : actual: m.len(),
1274 0 : expected: self.desc.file_size,
1275 0 : })
1276 : } else {
1277 120 : Ok(())
1278 : }
1279 120 : }
1280 :
1281 0 : fn info(&self, reset: LayerAccessStatsReset) -> HistoricLayerInfo {
1282 0 : let layer_name = self.desc.layer_name().to_string();
1283 0 :
1284 0 : let resident = self
1285 0 : .inner
1286 0 : .get()
1287 0 : .map(|rowe| rowe.is_likely_resident())
1288 0 : .unwrap_or(false);
1289 0 :
1290 0 : let access_stats = self.access_stats.as_api_model(reset);
1291 0 :
1292 0 : if self.desc.is_delta {
1293 0 : let lsn_range = &self.desc.lsn_range;
1294 0 :
1295 0 : HistoricLayerInfo::Delta {
1296 0 : layer_file_name: layer_name,
1297 0 : layer_file_size: self.desc.file_size,
1298 0 : lsn_start: lsn_range.start,
1299 0 : lsn_end: lsn_range.end,
1300 0 : remote: !resident,
1301 0 : access_stats,
1302 0 : l0: crate::tenant::layer_map::LayerMap::is_l0(
1303 0 : &self.layer_desc().key_range,
1304 0 : self.layer_desc().is_delta,
1305 0 : ),
1306 0 : }
1307 : } else {
1308 0 : let lsn = self.desc.image_layer_lsn();
1309 0 :
1310 0 : HistoricLayerInfo::Image {
1311 0 : layer_file_name: layer_name,
1312 0 : layer_file_size: self.desc.file_size,
1313 0 : lsn_start: lsn,
1314 0 : remote: !resident,
1315 0 : access_stats,
1316 0 : }
1317 : }
1318 0 : }
1319 :
1320 : /// `DownloadedLayer` is being dropped, so it calls this method.
1321 72 : fn on_downloaded_layer_drop(self: Arc<LayerInner>, only_version: usize) {
1322 : // we cannot know without inspecting LayerInner::inner if we should evict or not, even
1323 : // though here it is very likely
1324 72 : let span = tracing::info_span!(parent: None, "layer_evict", tenant_id = %self.desc.tenant_shard_id.tenant_id, shard_id = %self.desc.tenant_shard_id.shard_slug(), timeline_id = %self.desc.timeline_id, layer=%self, version=%only_version);
1325 :
1326 : // NOTE: this scope *must* never call `self.inner.get` because evict_and_wait might
1327 : // drop while the `self.inner` is being locked, leading to a deadlock.
1328 :
1329 72 : let start_evicting = async move {
1330 72 : #[cfg(test)]
1331 72 : self.failpoint(failpoints::FailpointKind::WaitBeforeStartingEvicting)
1332 42 : .await
1333 72 : .expect("failpoint should not have errored");
1334 72 :
1335 72 : tracing::debug!("eviction started");
1336 :
1337 72 : let res = self.wait_for_turn_and_evict(only_version).await;
1338 : // metrics: ignore the Ok branch, it is not done yet
1339 72 : if let Err(e) = res {
1340 18 : tracing::debug!(res=?Err::<(), _>(&e), "eviction completed");
1341 18 : LAYER_IMPL_METRICS.inc_eviction_cancelled(e);
1342 54 : }
1343 72 : };
1344 :
1345 72 : Self::spawn(start_evicting.instrument(span));
1346 72 : }
1347 :
1348 72 : async fn wait_for_turn_and_evict(
1349 72 : self: Arc<LayerInner>,
1350 72 : only_version: usize,
1351 72 : ) -> Result<(), EvictionCancelled> {
1352 138 : fn is_good_to_continue(status: &Status) -> Result<(), EvictionCancelled> {
1353 : use Status::*;
1354 138 : match status {
1355 132 : Resident => Ok(()),
1356 6 : Evicted => Err(EvictionCancelled::UnexpectedEvictedState),
1357 0 : Downloading => Err(EvictionCancelled::LostToDownload),
1358 : }
1359 138 : }
1360 :
1361 72 : let timeline = self
1362 72 : .timeline
1363 72 : .upgrade()
1364 72 : .ok_or(EvictionCancelled::TimelineGone)?;
1365 :
1366 72 : let mut rx = self
1367 72 : .status
1368 72 : .as_ref()
1369 72 : .expect("LayerInner cannot be dropped, holding strong ref")
1370 72 : .subscribe();
1371 72 :
1372 72 : is_good_to_continue(&rx.borrow_and_update())?;
1373 :
1374 66 : let Ok(gate) = timeline.gate.enter() else {
1375 0 : return Err(EvictionCancelled::TimelineGone);
1376 : };
1377 :
1378 54 : let permit = {
1379 : // we cannot just `std::fs::remove_file` because there might already be an
1380 : // get_or_maybe_download which will inspect filesystem and reinitialize. filesystem
1381 : // operations must be done while holding the heavier_once_cell::InitPermit
1382 66 : let mut wait = std::pin::pin!(self.inner.get_or_init_detached());
1383 :
1384 66 : let waited = loop {
1385 : // we must race to the Downloading starting, otherwise we would have to wait until the
1386 : // completion of the download. waiting for download could be long and hinder our
1387 : // efforts to alert on "hanging" evictions.
1388 66 : tokio::select! {
1389 66 : res = &mut wait => break res,
1390 66 : _ = rx.changed() => {
1391 0 : is_good_to_continue(&rx.borrow_and_update())?;
1392 : // two possibilities for Status::Resident:
1393 : // - the layer was found locally from disk by a read
1394 : // - we missed a bunch of updates and now the layer is
1395 : // again downloaded -- assume we'll fail later on with
1396 : // version check or AlreadyReinitialized
1397 : }
1398 : }
1399 : };
1400 :
1401 : // re-check now that we have the guard or permit; all updates should have happened
1402 : // while holding the permit.
1403 66 : is_good_to_continue(&rx.borrow_and_update())?;
1404 :
1405 : // the term deinitialize is used here, because we clearing out the Weak will eventually
1406 : // lead to deallocating the reference counted value, and the value we
1407 : // `Guard::take_and_deinit` is likely to be the last because the Weak is never cloned.
1408 66 : let (_weak, permit) = match waited {
1409 60 : Ok(guard) => {
1410 60 : match &*guard {
1411 54 : ResidentOrWantedEvicted::WantedEvicted(_weak, version)
1412 54 : if *version == only_version =>
1413 48 : {
1414 48 : tracing::debug!(version, "deinitializing matching WantedEvicted");
1415 48 : let (weak, permit) = guard.take_and_deinit();
1416 48 : (Some(weak), permit)
1417 : }
1418 6 : ResidentOrWantedEvicted::WantedEvicted(_, version) => {
1419 6 : // if we were not doing the version check, we would need to try to
1420 6 : // upgrade the weak here to see if it really is dropped. version check
1421 6 : // is done instead assuming that it is cheaper.
1422 6 : tracing::debug!(
1423 : version,
1424 : only_version,
1425 0 : "version mismatch, not deinitializing"
1426 : );
1427 6 : return Err(EvictionCancelled::VersionCheckFailed);
1428 : }
1429 : ResidentOrWantedEvicted::Resident(_) => {
1430 6 : return Err(EvictionCancelled::AlreadyReinitialized);
1431 : }
1432 : }
1433 : }
1434 6 : Err(permit) => {
1435 6 : tracing::debug!("continuing after cancelled get_or_maybe_download or eviction");
1436 6 : (None, permit)
1437 : }
1438 : };
1439 :
1440 54 : permit
1441 54 : };
1442 54 :
1443 54 : let span = tracing::Span::current();
1444 54 :
1445 54 : let spawned_at = std::time::Instant::now();
1446 54 :
1447 54 : // this is on purpose a detached spawn; we don't need to wait for it
1448 54 : //
1449 54 : // eviction completion reporting is the only thing hinging on this, and it can be just as
1450 54 : // well from a spawn_blocking thread.
1451 54 : //
1452 54 : // important to note that now that we've acquired the permit we have made sure the evicted
1453 54 : // file is either the exact `WantedEvicted` we wanted to evict, or uninitialized in case
1454 54 : // there are multiple evictions. The rest is not cancellable, and we've now commited to
1455 54 : // evicting.
1456 54 : //
1457 54 : // If spawn_blocking has a queue and maximum number of threads are in use, we could stall
1458 54 : // reads. We will need to add cancellation for that if necessary.
1459 54 : Self::spawn_blocking(move || {
1460 54 : let _span = span.entered();
1461 54 :
1462 54 : let res = self.evict_blocking(&timeline, &gate, &permit);
1463 54 :
1464 54 : let waiters = self.inner.initializer_count();
1465 54 :
1466 54 : if waiters > 0 {
1467 0 : LAYER_IMPL_METRICS.inc_evicted_with_waiters();
1468 54 : }
1469 :
1470 54 : let completed_in = spawned_at.elapsed();
1471 54 : LAYER_IMPL_METRICS.record_time_to_evict(completed_in);
1472 54 :
1473 54 : match res {
1474 54 : Ok(()) => LAYER_IMPL_METRICS.inc_completed_evictions(),
1475 0 : Err(e) => LAYER_IMPL_METRICS.inc_eviction_cancelled(e),
1476 : }
1477 :
1478 54 : tracing::debug!(?res, elapsed_ms=%completed_in.as_millis(), %waiters, "eviction completed");
1479 54 : });
1480 54 :
1481 54 : Ok(())
1482 72 : }
1483 :
1484 : /// This is blocking only to do just one spawn_blocking hop compared to multiple via tokio::fs.
1485 54 : fn evict_blocking(
1486 54 : &self,
1487 54 : timeline: &Timeline,
1488 54 : _gate: &gate::GateGuard,
1489 54 : _permit: &heavier_once_cell::InitPermit,
1490 54 : ) -> Result<(), EvictionCancelled> {
1491 54 : // now accesses to `self.inner.get_or_init*` wait on the semaphore or the `_permit`
1492 54 :
1493 54 : match capture_mtime_and_remove(&self.path) {
1494 54 : Ok(local_layer_mtime) => {
1495 54 : let duration = SystemTime::now().duration_since(local_layer_mtime);
1496 54 : match duration {
1497 54 : Ok(elapsed) => {
1498 54 : let accessed_and_visible = self.access_stats.accessed()
1499 12 : && self.access_stats.visibility() == LayerVisibilityHint::Visible;
1500 54 : if accessed_and_visible {
1501 12 : // Only layers used for reads contribute to our "low residence" metric that is used
1502 12 : // to detect thrashing. Layers promoted for other reasons (e.g. compaction) are allowed
1503 12 : // to be rapidly evicted without contributing to this metric.
1504 12 : timeline
1505 12 : .metrics
1506 12 : .evictions_with_low_residence_duration
1507 12 : .read()
1508 12 : .unwrap()
1509 12 : .observe(elapsed);
1510 42 : }
1511 :
1512 54 : tracing::info!(
1513 0 : residence_millis = elapsed.as_millis(),
1514 0 : accessed_and_visible,
1515 0 : "evicted layer after known residence period"
1516 : );
1517 : }
1518 : Err(_) => {
1519 0 : tracing::info!("evicted layer after unknown residence period");
1520 : }
1521 : }
1522 54 : timeline.metrics.evictions.inc();
1523 54 : timeline
1524 54 : .metrics
1525 54 : .resident_physical_size_sub(self.desc.file_size);
1526 : }
1527 0 : Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
1528 0 : tracing::error!(
1529 : layer_size = %self.desc.file_size,
1530 0 : "failed to evict layer from disk, it was already gone"
1531 : );
1532 0 : return Err(EvictionCancelled::FileNotFound);
1533 : }
1534 0 : Err(e) => {
1535 0 : // FIXME: this should probably be an abort
1536 0 : tracing::error!("failed to evict file from disk: {e:#}");
1537 0 : return Err(EvictionCancelled::RemoveFailed);
1538 : }
1539 : }
1540 :
1541 54 : self.access_stats.record_residence_event();
1542 54 :
1543 54 : self.status.as_ref().unwrap().send_replace(Status::Evicted);
1544 54 :
1545 54 : *self.last_evicted_at.lock().unwrap() = Some(std::time::Instant::now());
1546 54 :
1547 54 : Ok(())
1548 54 : }
1549 :
1550 7212 : fn metadata(&self) -> LayerFileMetadata {
1551 7212 : LayerFileMetadata::new(self.desc.file_size, self.generation, self.shard)
1552 7212 : }
1553 :
1554 : /// Needed to use entered runtime in tests, but otherwise use BACKGROUND_RUNTIME.
1555 : ///
1556 : /// Synchronizing with spawned tasks is very complicated otherwise.
1557 90 : fn spawn<F>(fut: F)
1558 90 : where
1559 90 : F: std::future::Future<Output = ()> + Send + 'static,
1560 90 : {
1561 90 : #[cfg(test)]
1562 90 : tokio::task::spawn(fut);
1563 90 : #[cfg(not(test))]
1564 90 : crate::task_mgr::BACKGROUND_RUNTIME.spawn(fut);
1565 90 : }
1566 :
1567 : /// Needed to use entered runtime in tests, but otherwise use BACKGROUND_RUNTIME.
1568 1440 : fn spawn_blocking<F>(f: F)
1569 1440 : where
1570 1440 : F: FnOnce() + Send + 'static,
1571 1440 : {
1572 1440 : #[cfg(test)]
1573 1440 : tokio::task::spawn_blocking(f);
1574 1440 : #[cfg(not(test))]
1575 1440 : crate::task_mgr::BACKGROUND_RUNTIME.spawn_blocking(f);
1576 1440 : }
1577 : }
1578 :
1579 54 : fn capture_mtime_and_remove(path: &Utf8Path) -> Result<SystemTime, std::io::Error> {
1580 54 : let m = path.metadata()?;
1581 54 : let local_layer_mtime = m.modified()?;
1582 54 : std::fs::remove_file(path)?;
1583 54 : Ok(local_layer_mtime)
1584 54 : }
1585 :
1586 0 : #[derive(Debug, thiserror::Error)]
1587 : pub(crate) enum EvictionError {
1588 : #[error("layer was already evicted")]
1589 : NotFound,
1590 :
1591 : /// Evictions must always lose to downloads in races, and this time it happened.
1592 : #[error("layer was downloaded instead")]
1593 : Downloaded,
1594 :
1595 : #[error("eviction did not happen within timeout")]
1596 : Timeout,
1597 : }
1598 :
1599 : /// Error internal to the [`LayerInner::get_or_maybe_download`]
1600 0 : #[derive(Debug, thiserror::Error)]
1601 : pub(crate) enum DownloadError {
1602 : #[error("timeline has already shutdown")]
1603 : TimelineShutdown,
1604 : #[error("context denies downloading")]
1605 : ContextAndConfigReallyDeniesDownloads,
1606 : #[error("downloading is really required but not allowed by this method")]
1607 : DownloadRequired,
1608 : #[error("layer path exists, but it is not a file: {0:?}")]
1609 : NotFile(std::fs::FileType),
1610 : /// Why no error here? Because it will be reported by page_service. We should had also done
1611 : /// retries already.
1612 : #[error("downloading evicted layer file failed")]
1613 : DownloadFailed,
1614 : #[error("downloading failed, possibly for shutdown")]
1615 : DownloadCancelled,
1616 : #[error("pre-condition: stat before download failed")]
1617 : PreStatFailed(#[source] std::io::Error),
1618 :
1619 : #[cfg(test)]
1620 : #[error("failpoint: {0:?}")]
1621 : Failpoint(failpoints::FailpointKind),
1622 : }
1623 :
1624 : impl DownloadError {
1625 0 : pub(crate) fn is_cancelled(&self) -> bool {
1626 0 : matches!(self, DownloadError::DownloadCancelled)
1627 0 : }
1628 : }
1629 :
1630 : #[derive(Debug, PartialEq)]
1631 : pub(crate) enum NeedsDownload {
1632 : NotFound,
1633 : NotFile(std::fs::FileType),
1634 : WrongSize { actual: u64, expected: u64 },
1635 : }
1636 :
1637 : impl std::fmt::Display for NeedsDownload {
1638 18 : fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1639 18 : match self {
1640 18 : NeedsDownload::NotFound => write!(f, "file was not found"),
1641 0 : NeedsDownload::NotFile(ft) => write!(f, "path is not a file; {ft:?}"),
1642 0 : NeedsDownload::WrongSize { actual, expected } => {
1643 0 : write!(f, "file size mismatch {actual} vs. {expected}")
1644 : }
1645 : }
1646 18 : }
1647 : }
1648 :
1649 : /// Existence of `DownloadedLayer` means that we have the file locally, and can later evict it.
1650 : pub(crate) struct DownloadedLayer {
1651 : owner: Weak<LayerInner>,
1652 : // Use tokio OnceCell as we do not need to deinitialize this, it'll just get dropped with the
1653 : // DownloadedLayer
1654 : kind: tokio::sync::OnceCell<anyhow::Result<LayerKind>>,
1655 : version: usize,
1656 : }
1657 :
1658 : impl std::fmt::Debug for DownloadedLayer {
1659 0 : fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1660 0 : f.debug_struct("DownloadedLayer")
1661 0 : // owner omitted because it is always "Weak"
1662 0 : .field("kind", &self.kind)
1663 0 : .field("version", &self.version)
1664 0 : .finish()
1665 0 : }
1666 : }
1667 :
1668 : impl Drop for DownloadedLayer {
1669 1788 : fn drop(&mut self) {
1670 1788 : if let Some(owner) = self.owner.upgrade() {
1671 72 : owner.on_downloaded_layer_drop(self.version);
1672 1716 : } else {
1673 1716 : // Layer::drop will handle cancelling the eviction; because of drop order and
1674 1716 : // `DownloadedLayer` never leaking, we cannot know here if eviction was requested.
1675 1716 : }
1676 1788 : }
1677 : }
1678 :
1679 : impl DownloadedLayer {
1680 : /// Initializes the `DeltaLayerInner` or `ImageLayerInner` within [`LayerKind`].
1681 : /// Failure to load the layer is sticky, i.e., future `get()` calls will return
1682 : /// the initial load failure immediately.
1683 : ///
1684 : /// `owner` parameter is a strong reference at the same `LayerInner` as the
1685 : /// `DownloadedLayer::owner` would be when upgraded. Given how this method ends up called,
1686 : /// we will always have the LayerInner on the callstack, so we can just use it.
1687 639555 : async fn get<'a>(
1688 639555 : &'a self,
1689 639555 : owner: &Arc<LayerInner>,
1690 639555 : ctx: &RequestContext,
1691 639555 : ) -> anyhow::Result<&'a LayerKind> {
1692 639555 : let init = || async {
1693 3450 : assert_eq!(
1694 3450 : Weak::as_ptr(&self.owner),
1695 3450 : Arc::as_ptr(owner),
1696 0 : "these are the same, just avoiding the upgrade"
1697 : );
1698 :
1699 3450 : let res = if owner.desc.is_delta {
1700 3132 : let ctx = RequestContextBuilder::extend(ctx)
1701 3132 : .page_content_kind(crate::context::PageContentKind::DeltaLayerSummary)
1702 3132 : .build();
1703 3132 : let summary = Some(delta_layer::Summary::expected(
1704 3132 : owner.desc.tenant_shard_id.tenant_id,
1705 3132 : owner.desc.timeline_id,
1706 3132 : owner.desc.key_range.clone(),
1707 3132 : owner.desc.lsn_range.clone(),
1708 3132 : ));
1709 3132 : delta_layer::DeltaLayerInner::load(
1710 3132 : &owner.path,
1711 3132 : summary,
1712 3132 : Some(owner.conf.max_vectored_read_bytes),
1713 3132 : &ctx,
1714 3132 : )
1715 3145 : .await
1716 3132 : .map(LayerKind::Delta)
1717 : } else {
1718 318 : let ctx = RequestContextBuilder::extend(ctx)
1719 318 : .page_content_kind(crate::context::PageContentKind::ImageLayerSummary)
1720 318 : .build();
1721 318 : let lsn = owner.desc.image_layer_lsn();
1722 318 : let summary = Some(image_layer::Summary::expected(
1723 318 : owner.desc.tenant_shard_id.tenant_id,
1724 318 : owner.desc.timeline_id,
1725 318 : owner.desc.key_range.clone(),
1726 318 : lsn,
1727 318 : ));
1728 318 : image_layer::ImageLayerInner::load(
1729 318 : &owner.path,
1730 318 : lsn,
1731 318 : summary,
1732 318 : Some(owner.conf.max_vectored_read_bytes),
1733 318 : &ctx,
1734 318 : )
1735 322 : .await
1736 318 : .map(LayerKind::Image)
1737 : };
1738 :
1739 3450 : match res {
1740 3450 : Ok(layer) => Ok(layer),
1741 0 : Err(err) => {
1742 0 : LAYER_IMPL_METRICS.inc_permanent_loading_failures();
1743 0 : // We log this message once over the lifetime of `Self`
1744 0 : // => Ok and good to log backtrace and path here.
1745 0 : tracing::error!(
1746 0 : "layer load failed, assuming permanent failure: {}: {err:?}",
1747 0 : owner.path
1748 : );
1749 0 : Err(err)
1750 : }
1751 : }
1752 6900 : };
1753 639555 : self.kind
1754 639555 : .get_or_init(init)
1755 3467 : .await
1756 639555 : .as_ref()
1757 639555 : // We already logged the full backtrace above, once. Don't repeat that here.
1758 639555 : .map_err(|e| anyhow::anyhow!("layer load failed earlier: {e}"))
1759 639555 : }
1760 :
1761 636645 : async fn get_values_reconstruct_data(
1762 636645 : &self,
1763 636645 : keyspace: KeySpace,
1764 636645 : lsn_range: Range<Lsn>,
1765 636645 : reconstruct_data: &mut ValuesReconstructState,
1766 636645 : owner: &Arc<LayerInner>,
1767 636645 : ctx: &RequestContext,
1768 636645 : ) -> Result<(), GetVectoredError> {
1769 : use LayerKind::*;
1770 :
1771 636645 : match self
1772 636645 : .get(owner, ctx)
1773 2591 : .await
1774 636645 : .map_err(GetVectoredError::Other)?
1775 : {
1776 612459 : Delta(d) => {
1777 612459 : d.get_values_reconstruct_data(keyspace, lsn_range, reconstruct_data, ctx)
1778 267034 : .await
1779 : }
1780 24186 : Image(i) => {
1781 24186 : i.get_values_reconstruct_data(keyspace, reconstruct_data, ctx)
1782 16260 : .await
1783 : }
1784 : }
1785 636645 : }
1786 :
1787 12 : async fn dump(&self, owner: &Arc<LayerInner>, ctx: &RequestContext) -> anyhow::Result<()> {
1788 : use LayerKind::*;
1789 12 : match self.get(owner, ctx).await? {
1790 12 : Delta(d) => d.dump(ctx).await?,
1791 0 : Image(i) => i.dump(ctx).await?,
1792 : }
1793 :
1794 12 : Ok(())
1795 12 : }
1796 : }
1797 :
1798 : /// Wrapper around an actual layer implementation.
1799 : #[derive(Debug)]
1800 : enum LayerKind {
1801 : Delta(delta_layer::DeltaLayerInner),
1802 : Image(image_layer::ImageLayerInner),
1803 : }
1804 :
1805 : /// Guard for forcing a layer be resident while it exists.
1806 : #[derive(Clone)]
1807 : pub(crate) struct ResidentLayer {
1808 : owner: Layer,
1809 : downloaded: Arc<DownloadedLayer>,
1810 : }
1811 :
1812 : impl std::fmt::Display for ResidentLayer {
1813 5760 : fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1814 5760 : write!(f, "{}", self.owner)
1815 5760 : }
1816 : }
1817 :
1818 : impl std::fmt::Debug for ResidentLayer {
1819 0 : fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1820 0 : write!(f, "{}", self.owner)
1821 0 : }
1822 : }
1823 :
1824 : impl ResidentLayer {
1825 : /// Release the eviction guard, converting back into a plain [`Layer`].
1826 : ///
1827 : /// You can access the [`Layer`] also by using `as_ref`.
1828 1260 : pub(crate) fn drop_eviction_guard(self) -> Layer {
1829 1260 : self.into()
1830 1260 : }
1831 :
1832 : /// Loads all keys stored in the layer. Returns key, lsn and value size.
1833 2412 : #[tracing::instrument(level = tracing::Level::DEBUG, skip_all, fields(layer=%self))]
1834 : pub(crate) async fn load_keys<'a>(
1835 : &'a self,
1836 : ctx: &RequestContext,
1837 : ) -> anyhow::Result<Vec<DeltaEntry<'a>>> {
1838 : use LayerKind::*;
1839 :
1840 : let owner = &self.owner.0;
1841 : match self.downloaded.get(owner, ctx).await? {
1842 : Delta(ref d) => {
1843 : // this is valid because the DownloadedLayer::kind is a OnceCell, not a
1844 : // Mutex<OnceCell>, so we cannot go and deinitialize the value with OnceCell::take
1845 : // while it's being held.
1846 : self.owner.record_access(ctx);
1847 :
1848 : delta_layer::DeltaLayerInner::load_keys(d, ctx)
1849 : .await
1850 0 : .with_context(|| format!("Layer index is corrupted for {self}"))
1851 : }
1852 : Image(_) => anyhow::bail!(format!("cannot load_keys on a image layer {self}")),
1853 : }
1854 : }
1855 :
1856 : /// Read all they keys in this layer which match the ShardIdentity, and write them all to
1857 : /// the provided writer. Return the number of keys written.
1858 48 : #[tracing::instrument(level = tracing::Level::DEBUG, skip_all, fields(layer=%self))]
1859 : pub(crate) async fn filter(
1860 : &self,
1861 : shard_identity: &ShardIdentity,
1862 : writer: &mut ImageLayerWriter,
1863 : ctx: &RequestContext,
1864 : ) -> Result<usize, CompactionError> {
1865 : use LayerKind::*;
1866 :
1867 : match self
1868 : .downloaded
1869 : .get(&self.owner.0, ctx)
1870 : .await
1871 : .map_err(CompactionError::Other)?
1872 : {
1873 : Delta(_) => {
1874 : return Err(CompactionError::Other(anyhow::anyhow!(format!(
1875 : "cannot filter() on a delta layer {self}"
1876 : ))));
1877 : }
1878 : Image(i) => i
1879 : .filter(shard_identity, writer, ctx)
1880 : .await
1881 : .map_err(CompactionError::Other),
1882 : }
1883 : }
1884 :
1885 : /// Returns the amount of keys and values written to the writer.
1886 30 : pub(crate) async fn copy_delta_prefix(
1887 30 : &self,
1888 30 : writer: &mut super::delta_layer::DeltaLayerWriter,
1889 30 : until: Lsn,
1890 30 : ctx: &RequestContext,
1891 30 : ) -> anyhow::Result<usize> {
1892 : use LayerKind::*;
1893 :
1894 30 : let owner = &self.owner.0;
1895 30 :
1896 30 : match self.downloaded.get(owner, ctx).await? {
1897 30 : Delta(ref d) => d
1898 30 : .copy_prefix(writer, until, ctx)
1899 39 : .await
1900 30 : .with_context(|| format!("copy_delta_prefix until {until} of {self}")),
1901 0 : Image(_) => anyhow::bail!(format!("cannot copy_lsn_prefix of image layer {self}")),
1902 : }
1903 30 : }
1904 :
1905 5067 : pub(crate) fn local_path(&self) -> &Utf8Path {
1906 5067 : &self.owner.0.path
1907 5067 : }
1908 :
1909 4614 : pub(crate) fn metadata(&self) -> LayerFileMetadata {
1910 4614 : self.owner.metadata()
1911 4614 : }
1912 :
1913 : /// Cast the layer to a delta, return an error if it is an image layer.
1914 1524 : pub(crate) async fn get_as_delta(
1915 1524 : &self,
1916 1524 : ctx: &RequestContext,
1917 1524 : ) -> anyhow::Result<&delta_layer::DeltaLayerInner> {
1918 : use LayerKind::*;
1919 1524 : match self.downloaded.get(&self.owner.0, ctx).await? {
1920 1524 : Delta(ref d) => Ok(d),
1921 0 : Image(_) => Err(anyhow::anyhow!("image layer")),
1922 : }
1923 1524 : }
1924 :
1925 : /// Cast the layer to an image, return an error if it is a delta layer.
1926 114 : pub(crate) async fn get_as_image(
1927 114 : &self,
1928 114 : ctx: &RequestContext,
1929 114 : ) -> anyhow::Result<&image_layer::ImageLayerInner> {
1930 : use LayerKind::*;
1931 114 : match self.downloaded.get(&self.owner.0, ctx).await? {
1932 114 : Image(ref d) => Ok(d),
1933 0 : Delta(_) => Err(anyhow::anyhow!("delta layer")),
1934 : }
1935 114 : }
1936 : }
1937 :
1938 : impl AsLayerDesc for ResidentLayer {
1939 17787 : fn layer_desc(&self) -> &PersistentLayerDesc {
1940 17787 : self.owner.layer_desc()
1941 17787 : }
1942 : }
1943 :
1944 : impl AsRef<Layer> for ResidentLayer {
1945 5784 : fn as_ref(&self) -> &Layer {
1946 5784 : &self.owner
1947 5784 : }
1948 : }
1949 :
1950 : /// Drop the eviction guard.
1951 : impl From<ResidentLayer> for Layer {
1952 1260 : fn from(value: ResidentLayer) -> Self {
1953 1260 : value.owner
1954 1260 : }
1955 : }
1956 :
1957 : use metrics::IntCounter;
1958 :
1959 : pub(crate) struct LayerImplMetrics {
1960 : started_evictions: IntCounter,
1961 : completed_evictions: IntCounter,
1962 : cancelled_evictions: enum_map::EnumMap<EvictionCancelled, IntCounter>,
1963 :
1964 : started_deletes: IntCounter,
1965 : completed_deletes: IntCounter,
1966 : failed_deletes: enum_map::EnumMap<DeleteFailed, IntCounter>,
1967 :
1968 : rare_counters: enum_map::EnumMap<RareEvent, IntCounter>,
1969 : inits_cancelled: metrics::core::GenericCounter<metrics::core::AtomicU64>,
1970 : redownload_after: metrics::Histogram,
1971 : time_to_evict: metrics::Histogram,
1972 : }
1973 :
1974 : impl Default for LayerImplMetrics {
1975 126 : fn default() -> Self {
1976 : use enum_map::Enum;
1977 :
1978 : // reminder: these will be pageserver_layer_* with "_total" suffix
1979 :
1980 126 : let started_evictions = metrics::register_int_counter!(
1981 126 : "pageserver_layer_started_evictions",
1982 126 : "Evictions started in the Layer implementation"
1983 126 : )
1984 126 : .unwrap();
1985 126 : let completed_evictions = metrics::register_int_counter!(
1986 126 : "pageserver_layer_completed_evictions",
1987 126 : "Evictions completed in the Layer implementation"
1988 126 : )
1989 126 : .unwrap();
1990 126 :
1991 126 : let cancelled_evictions = metrics::register_int_counter_vec!(
1992 126 : "pageserver_layer_cancelled_evictions_count",
1993 126 : "Different reasons for evictions to have been cancelled or failed",
1994 126 : &["reason"]
1995 126 : )
1996 126 : .unwrap();
1997 126 :
1998 1134 : let cancelled_evictions = enum_map::EnumMap::from_array(std::array::from_fn(|i| {
1999 1134 : let reason = EvictionCancelled::from_usize(i);
2000 1134 : let s = reason.as_str();
2001 1134 : cancelled_evictions.with_label_values(&[s])
2002 1134 : }));
2003 126 :
2004 126 : let started_deletes = metrics::register_int_counter!(
2005 126 : "pageserver_layer_started_deletes",
2006 126 : "Deletions on drop pending in the Layer implementation"
2007 126 : )
2008 126 : .unwrap();
2009 126 : let completed_deletes = metrics::register_int_counter!(
2010 126 : "pageserver_layer_completed_deletes",
2011 126 : "Deletions on drop completed in the Layer implementation"
2012 126 : )
2013 126 : .unwrap();
2014 126 :
2015 126 : let failed_deletes = metrics::register_int_counter_vec!(
2016 126 : "pageserver_layer_failed_deletes_count",
2017 126 : "Different reasons for deletions on drop to have failed",
2018 126 : &["reason"]
2019 126 : )
2020 126 : .unwrap();
2021 126 :
2022 252 : let failed_deletes = enum_map::EnumMap::from_array(std::array::from_fn(|i| {
2023 252 : let reason = DeleteFailed::from_usize(i);
2024 252 : let s = reason.as_str();
2025 252 : failed_deletes.with_label_values(&[s])
2026 252 : }));
2027 126 :
2028 126 : let rare_counters = metrics::register_int_counter_vec!(
2029 126 : "pageserver_layer_assumed_rare_count",
2030 126 : "Times unexpected or assumed rare event happened",
2031 126 : &["event"]
2032 126 : )
2033 126 : .unwrap();
2034 126 :
2035 882 : let rare_counters = enum_map::EnumMap::from_array(std::array::from_fn(|i| {
2036 882 : let event = RareEvent::from_usize(i);
2037 882 : let s = event.as_str();
2038 882 : rare_counters.with_label_values(&[s])
2039 882 : }));
2040 126 :
2041 126 : let inits_cancelled = metrics::register_int_counter!(
2042 126 : "pageserver_layer_inits_cancelled_count",
2043 126 : "Times Layer initialization was cancelled",
2044 126 : )
2045 126 : .unwrap();
2046 126 :
2047 126 : let redownload_after = {
2048 126 : let minute = 60.0;
2049 126 : let hour = 60.0 * minute;
2050 126 : metrics::register_histogram!(
2051 126 : "pageserver_layer_redownloaded_after",
2052 126 : "Time between evicting and re-downloading.",
2053 126 : vec![
2054 126 : 10.0,
2055 126 : 30.0,
2056 126 : minute,
2057 126 : 5.0 * minute,
2058 126 : 15.0 * minute,
2059 126 : 30.0 * minute,
2060 126 : hour,
2061 126 : 12.0 * hour,
2062 126 : ]
2063 126 : )
2064 126 : .unwrap()
2065 126 : };
2066 126 :
2067 126 : let time_to_evict = metrics::register_histogram!(
2068 126 : "pageserver_layer_eviction_held_permit_seconds",
2069 126 : "Time eviction held the permit.",
2070 126 : vec![0.001, 0.010, 0.100, 0.500, 1.000, 5.000]
2071 126 : )
2072 126 : .unwrap();
2073 126 :
2074 126 : Self {
2075 126 : started_evictions,
2076 126 : completed_evictions,
2077 126 : cancelled_evictions,
2078 126 :
2079 126 : started_deletes,
2080 126 : completed_deletes,
2081 126 : failed_deletes,
2082 126 :
2083 126 : rare_counters,
2084 126 : inits_cancelled,
2085 126 : redownload_after,
2086 126 : time_to_evict,
2087 126 : }
2088 126 : }
2089 : }
2090 :
2091 : impl LayerImplMetrics {
2092 78 : fn inc_started_evictions(&self) {
2093 78 : self.started_evictions.inc();
2094 78 : }
2095 54 : fn inc_completed_evictions(&self) {
2096 54 : self.completed_evictions.inc();
2097 54 : }
2098 24 : fn inc_eviction_cancelled(&self, reason: EvictionCancelled) {
2099 24 : self.cancelled_evictions[reason].inc()
2100 24 : }
2101 :
2102 1398 : fn inc_started_deletes(&self) {
2103 1398 : self.started_deletes.inc();
2104 1398 : }
2105 1386 : fn inc_completed_deletes(&self) {
2106 1386 : self.completed_deletes.inc();
2107 1386 : }
2108 0 : fn inc_deletes_failed(&self, reason: DeleteFailed) {
2109 0 : self.failed_deletes[reason].inc();
2110 0 : }
2111 :
2112 : /// Counted separatedly from failed layer deletes because we will complete the layer deletion
2113 : /// attempt regardless of failure to delete local file.
2114 0 : fn inc_delete_removes_failed(&self) {
2115 0 : self.rare_counters[RareEvent::RemoveOnDropFailed].inc();
2116 0 : }
2117 :
2118 : /// Expected rare just as cancellations are rare, but we could have cancellations separate from
2119 : /// the single caller which can start the download, so use this counter to separte them.
2120 0 : fn inc_init_completed_without_requester(&self) {
2121 0 : self.rare_counters[RareEvent::InitCompletedWithoutRequester].inc();
2122 0 : }
2123 :
2124 : /// Expected rare because cancellations are unexpected, and failures are unexpected
2125 0 : fn inc_download_failed_without_requester(&self) {
2126 0 : self.rare_counters[RareEvent::DownloadFailedWithoutRequester].inc();
2127 0 : }
2128 :
2129 : /// The Weak in ResidentOrWantedEvicted::WantedEvicted was successfully upgraded.
2130 : ///
2131 : /// If this counter is always zero, we should replace ResidentOrWantedEvicted type with an
2132 : /// Option.
2133 0 : fn inc_raced_wanted_evicted_accesses(&self) {
2134 0 : self.rare_counters[RareEvent::UpgradedWantedEvicted].inc();
2135 0 : }
2136 :
2137 : /// These are only expected for [`Self::inc_init_cancelled`] amount when
2138 : /// running with remote storage.
2139 18 : fn inc_init_needed_no_download(&self) {
2140 18 : self.rare_counters[RareEvent::InitWithoutDownload].inc();
2141 18 : }
2142 :
2143 : /// Expected rare because all layer files should be readable and good
2144 0 : fn inc_permanent_loading_failures(&self) {
2145 0 : self.rare_counters[RareEvent::PermanentLoadingFailure].inc();
2146 0 : }
2147 :
2148 0 : fn inc_init_cancelled(&self) {
2149 0 : self.inits_cancelled.inc()
2150 0 : }
2151 :
2152 18 : fn record_redownloaded_after(&self, duration: std::time::Duration) {
2153 18 : self.redownload_after.observe(duration.as_secs_f64())
2154 18 : }
2155 :
2156 : /// This would be bad if it ever happened, or mean extreme disk pressure. We should probably
2157 : /// instead cancel eviction if we would have read waiters. We cannot however separate reads
2158 : /// from other evictions, so this could have noise as well.
2159 0 : fn inc_evicted_with_waiters(&self) {
2160 0 : self.rare_counters[RareEvent::EvictedWithWaiters].inc();
2161 0 : }
2162 :
2163 : /// Recorded at least initially as the permit is now acquired in async context before
2164 : /// spawn_blocking action.
2165 54 : fn record_time_to_evict(&self, duration: std::time::Duration) {
2166 54 : self.time_to_evict.observe(duration.as_secs_f64())
2167 54 : }
2168 : }
2169 :
2170 : #[derive(Debug, Clone, Copy, enum_map::Enum)]
2171 : enum EvictionCancelled {
2172 : LayerGone,
2173 : TimelineGone,
2174 : VersionCheckFailed,
2175 : FileNotFound,
2176 : RemoveFailed,
2177 : AlreadyReinitialized,
2178 : /// Not evicted because of a pending reinitialization
2179 : LostToDownload,
2180 : /// After eviction, there was a new layer access which cancelled the eviction.
2181 : UpgradedBackOnAccess,
2182 : UnexpectedEvictedState,
2183 : }
2184 :
2185 : impl EvictionCancelled {
2186 1134 : fn as_str(&self) -> &'static str {
2187 1134 : match self {
2188 126 : EvictionCancelled::LayerGone => "layer_gone",
2189 126 : EvictionCancelled::TimelineGone => "timeline_gone",
2190 126 : EvictionCancelled::VersionCheckFailed => "version_check_fail",
2191 126 : EvictionCancelled::FileNotFound => "file_not_found",
2192 126 : EvictionCancelled::RemoveFailed => "remove_failed",
2193 126 : EvictionCancelled::AlreadyReinitialized => "already_reinitialized",
2194 126 : EvictionCancelled::LostToDownload => "lost_to_download",
2195 126 : EvictionCancelled::UpgradedBackOnAccess => "upgraded_back_on_access",
2196 126 : EvictionCancelled::UnexpectedEvictedState => "unexpected_evicted_state",
2197 : }
2198 1134 : }
2199 : }
2200 :
2201 : #[derive(enum_map::Enum)]
2202 : enum DeleteFailed {
2203 : TimelineGone,
2204 : DeleteSchedulingFailed,
2205 : }
2206 :
2207 : impl DeleteFailed {
2208 252 : fn as_str(&self) -> &'static str {
2209 252 : match self {
2210 126 : DeleteFailed::TimelineGone => "timeline_gone",
2211 126 : DeleteFailed::DeleteSchedulingFailed => "delete_scheduling_failed",
2212 : }
2213 252 : }
2214 : }
2215 :
2216 : #[derive(enum_map::Enum)]
2217 : enum RareEvent {
2218 : RemoveOnDropFailed,
2219 : InitCompletedWithoutRequester,
2220 : DownloadFailedWithoutRequester,
2221 : UpgradedWantedEvicted,
2222 : InitWithoutDownload,
2223 : PermanentLoadingFailure,
2224 : EvictedWithWaiters,
2225 : }
2226 :
2227 : impl RareEvent {
2228 882 : fn as_str(&self) -> &'static str {
2229 : use RareEvent::*;
2230 :
2231 882 : match self {
2232 126 : RemoveOnDropFailed => "remove_on_drop_failed",
2233 126 : InitCompletedWithoutRequester => "init_completed_without",
2234 126 : DownloadFailedWithoutRequester => "download_failed_without",
2235 126 : UpgradedWantedEvicted => "raced_wanted_evicted",
2236 126 : InitWithoutDownload => "init_needed_no_download",
2237 126 : PermanentLoadingFailure => "permanent_loading_failure",
2238 126 : EvictedWithWaiters => "evicted_with_waiters",
2239 : }
2240 882 : }
2241 : }
2242 :
2243 : pub(crate) static LAYER_IMPL_METRICS: once_cell::sync::Lazy<LayerImplMetrics> =
2244 : once_cell::sync::Lazy::new(LayerImplMetrics::default);
|