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