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