Line data Source code
1 : use anyhow::Context;
2 : use camino::{Utf8Path, Utf8PathBuf};
3 : use pageserver_api::keyspace::KeySpace;
4 : use pageserver_api::models::HistoricLayerInfo;
5 : use pageserver_api::shard::{ShardIdentity, ShardIndex, TenantShardId};
6 : use std::ops::Range;
7 : use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
8 : use std::sync::{Arc, Weak};
9 : use std::time::{Duration, SystemTime};
10 : use tracing::Instrument;
11 : use utils::id::TimelineId;
12 : use utils::lsn::Lsn;
13 : use utils::sync::{gate, heavier_once_cell};
14 :
15 : use crate::config::PageServerConf;
16 : use crate::context::{DownloadBehavior, RequestContext, RequestContextBuilder};
17 : use crate::span::debug_assert_current_span_has_tenant_and_timeline_id;
18 : use crate::task_mgr::TaskKind;
19 : use crate::tenant::timeline::{CompactionError, GetVectoredError};
20 : use crate::tenant::{remote_timeline_client::LayerFileMetadata, Timeline};
21 :
22 : use super::delta_layer::{self, DeltaEntry};
23 : use super::image_layer::{self};
24 : use super::{
25 : AsLayerDesc, ImageLayerWriter, LayerAccessStats, LayerAccessStatsReset, LayerName,
26 : LayerVisibilityHint, PersistentLayerDesc, ValuesReconstructState,
27 : };
28 :
29 : use utils::generation::Generation;
30 :
31 : #[cfg(test)]
32 : mod tests;
33 :
34 : #[cfg(test)]
35 : mod failpoints;
36 :
37 : pub const S3_UPLOAD_LIMIT: u64 = 4_500_000_000;
38 :
39 : /// A Layer contains all data in a "rectangle" consisting of a range of keys and
40 : /// range of LSNs.
41 : ///
42 : /// There are two kinds of layers, in-memory and on-disk layers. In-memory
43 : /// layers are used to ingest incoming WAL, and provide fast access to the
44 : /// recent page versions. On-disk layers are stored as files on disk, and are
45 : /// immutable. This type represents the on-disk kind while in-memory kind are represented by
46 : /// [`InMemoryLayer`].
47 : ///
48 : /// Furthermore, there are two kinds of on-disk layers: delta and image layers.
49 : /// A delta layer contains all modifications within a range of LSNs and keys.
50 : /// An image layer is a snapshot of all the data in a key-range, at a single
51 : /// LSN.
52 : ///
53 : /// This type models the on-disk layers, which can be evicted and on-demand downloaded. As a
54 : /// general goal, read accesses should always win eviction and eviction should not wait for
55 : /// download.
56 : ///
57 : /// ### State transitions
58 : ///
59 : /// The internal state of `Layer` is composed of most importantly the on-filesystem state and the
60 : /// [`ResidentOrWantedEvicted`] enum. On-filesystem state can be either present (fully downloaded,
61 : /// right size) or deleted.
62 : ///
63 : /// Reads will always win requests to evict until `wait_for_turn_and_evict` has acquired the
64 : /// `heavier_once_cell::InitPermit` and has started to `evict_blocking`. Before the
65 : /// `heavier_once_cell::InitPermit` has been acquired, any read request
66 : /// (`get_or_maybe_download`) can "re-initialize" using the existing downloaded file and thus
67 : /// cancelling the eviction.
68 : ///
69 : /// ```text
70 : /// +-----------------+ get_or_maybe_download +--------------------------------+
71 : /// | not initialized |--------------------------->| Resident(Arc<DownloadedLayer>) |
72 : /// | ENOENT | /->| |
73 : /// +-----------------+ | +--------------------------------+
74 : /// ^ | | ^
75 : /// | get_or_maybe_download | | | get_or_maybe_download, either:
76 : /// evict_blocking | /-------------------------/ | | - upgrade weak to strong
77 : /// | | | | - re-initialize without download
78 : /// | | evict_and_wait | |
79 : /// +-----------------+ v |
80 : /// | not initialized | on_downloaded_layer_drop +--------------------------------------+
81 : /// | file is present |<---------------------------| WantedEvicted(Weak<DownloadedLayer>) |
82 : /// +-----------------+ +--------------------------------------+
83 : /// ```
84 : ///
85 : /// ### Unsupported
86 : ///
87 : /// - Evicting by the operator deleting files from the filesystem
88 : ///
89 : /// [`InMemoryLayer`]: super::inmemory_layer::InMemoryLayer
90 : #[derive(Clone)]
91 : pub(crate) struct Layer(Arc<LayerInner>);
92 :
93 : impl std::fmt::Display for Layer {
94 1916 : fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
95 1916 : write!(
96 1916 : f,
97 1916 : "{}{}",
98 1916 : self.layer_desc().short_id(),
99 1916 : self.0.generation.get_suffix()
100 1916 : )
101 1916 : }
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 502542 : fn layer_desc(&self) -> &PersistentLayerDesc {
112 502542 : self.0.layer_desc()
113 502542 : }
114 : }
115 :
116 : impl PartialEq for Layer {
117 3 : fn eq(&self, other: &Self) -> bool {
118 3 : Arc::as_ptr(&self.0) == Arc::as_ptr(&other.0)
119 3 : }
120 : }
121 :
122 1698 : pub(crate) fn local_layer_path(
123 1698 : conf: &PageServerConf,
124 1698 : tenant_shard_id: &TenantShardId,
125 1698 : timeline_id: &TimelineId,
126 1698 : layer_file_name: &LayerName,
127 1698 : generation: &Generation,
128 1698 : ) -> Utf8PathBuf {
129 1698 : let timeline_path = conf.timeline_path(tenant_shard_id, timeline_id);
130 1698 :
131 1698 : 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 1698 : timeline_path.join(format!("{}-v1{}", layer_file_name, generation.get_suffix()))
136 : }
137 1698 : }
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 1690 : pub(crate) fn finish_creating(
227 1690 : conf: &'static PageServerConf,
228 1690 : timeline: &Arc<Timeline>,
229 1690 : desc: PersistentLayerDesc,
230 1690 : temp_path: &Utf8Path,
231 1690 : ) -> anyhow::Result<ResidentLayer> {
232 1690 : let mut resident = None;
233 1690 :
234 1690 : let owner = Layer(Arc::new_cyclic(|owner| {
235 1690 : let inner = Arc::new(DownloadedLayer {
236 1690 : owner: owner.clone(),
237 1690 : kind: tokio::sync::OnceCell::default(),
238 1690 : version: 0,
239 1690 : });
240 1690 : resident = Some(inner.clone());
241 1690 :
242 1690 : let local_path = local_layer_path(
243 1690 : conf,
244 1690 : &timeline.tenant_shard_id,
245 1690 : &timeline.timeline_id,
246 1690 : &desc.layer_name(),
247 1690 : &timeline.generation,
248 1690 : );
249 1690 :
250 1690 : LayerInner::new(
251 1690 : conf,
252 1690 : timeline,
253 1690 : local_path,
254 1690 : desc,
255 1690 : Some(inner),
256 1690 : timeline.generation,
257 1690 : timeline.get_shard_index(),
258 1690 : )
259 1690 : }));
260 1690 :
261 1690 : let downloaded = resident.expect("just initialized");
262 1690 :
263 1690 : // We never want to overwrite an existing file, so we use `RENAME_NOREPLACE`.
264 1690 : // TODO: this leaves the temp file in place if the rename fails, risking us running
265 1690 : // out of space. Should we clean it up here or does the calling context deal with this?
266 1690 : utils::fs_ext::rename_noreplace(temp_path.as_std_path(), owner.local_path().as_std_path())
267 1690 : .with_context(|| format!("rename temporary file as correct path for {owner}"))?;
268 :
269 1690 : Ok(ResidentLayer { downloaded, owner })
270 1690 : }
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 50 : 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 464 : pub(crate) fn delete_on_drop(&self) {
301 464 : self.0.delete_on_drop();
302 464 : }
303 :
304 212061 : pub(crate) async fn get_values_reconstruct_data(
305 212061 : &self,
306 212061 : keyspace: KeySpace,
307 212061 : lsn_range: Range<Lsn>,
308 212061 : reconstruct_data: &mut ValuesReconstructState,
309 212061 : ctx: &RequestContext,
310 212061 : ) -> Result<(), GetVectoredError> {
311 212061 : let layer = self
312 212061 : .0
313 212061 : .get_or_maybe_download(true, Some(ctx))
314 3 : .await
315 212061 : .map_err(|err| match err {
316 : DownloadError::TimelineShutdown | DownloadError::DownloadCancelled => {
317 0 : GetVectoredError::Cancelled
318 : }
319 0 : other => GetVectoredError::Other(anyhow::anyhow!(other)),
320 212061 : })?;
321 :
322 212061 : self.record_access(ctx);
323 212061 :
324 212061 : layer
325 212061 : .get_values_reconstruct_data(keyspace, lsn_range, reconstruct_data, &self.0, ctx)
326 212061 : .instrument(tracing::debug_span!("get_values_reconstruct_data", layer=%self))
327 90234 : .await
328 212061 : .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 212061 : })
334 212061 : }
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 82 : pub(crate) async fn needs_download(&self) -> Result<Option<NeedsDownload>, std::io::Error> {
345 82 : self.0.needs_download().await
346 82 : }
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 53 : pub(crate) fn is_likely_resident(&self) -> bool {
368 53 : self.0
369 53 : .inner
370 53 : .get()
371 53 : .map(|rowe| rowe.is_likely_resident())
372 53 : .unwrap_or(false)
373 53 : }
374 :
375 : /// Downloads if necessary and creates a guard, which will keep this layer from being evicted.
376 496 : pub(crate) async fn download_and_keep_resident(&self) -> Result<ResidentLayer, DownloadError> {
377 496 : let downloaded = self.0.get_or_maybe_download(true, None).await?;
378 :
379 496 : Ok(ResidentLayer {
380 496 : downloaded,
381 496 : owner: self.clone(),
382 496 : })
383 496 : }
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 1692 : pub(crate) fn local_path(&self) -> &Utf8Path {
398 1692 : &self.0.path
399 1692 : }
400 :
401 1932 : pub(crate) fn metadata(&self) -> LayerFileMetadata {
402 1932 : self.0.metadata()
403 1932 : }
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 212463 : fn record_access(&self, ctx: &RequestContext) {
445 212463 : 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 212463 : }
478 212463 : }
479 :
480 312 : pub(crate) fn set_visibility(&self, visibility: LayerVisibilityHint) {
481 312 : let old_visibility = self.0.access_stats.set_visibility(visibility.clone());
482 : use LayerVisibilityHint::*;
483 312 : 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 276 : (Covered, Covered) | (Visible, Visible) => {
504 276 : // no change
505 276 : }
506 : }
507 312 : }
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 47 : fn is_likely_resident(&self) -> bool {
540 47 : match self {
541 41 : ResidentOrWantedEvicted::Resident(_) => true,
542 6 : ResidentOrWantedEvicted::WantedEvicted(weak, _) => weak.strong_count() > 0,
543 : }
544 47 : }
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 212565 : fn get_and_upgrade(&mut self) -> Option<(Arc<DownloadedLayer>, bool)> {
551 212565 : match self {
552 212557 : 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 212565 : }
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 504862 : fn layer_desc(&self) -> &PersistentLayerDesc {
672 504862 : &self.desc
673 504862 : }
674 : }
675 :
676 : #[derive(Debug, Clone, Copy)]
677 : enum Status {
678 : Resident,
679 : Evicted,
680 : Downloading,
681 : }
682 :
683 : impl Drop for LayerInner {
684 556 : fn drop(&mut self) {
685 556 : // if there was a pending eviction, mark it cancelled here to balance metrics
686 556 : 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 554 : }
694 :
695 556 : let timeline = self.timeline.upgrade();
696 :
697 556 : 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 540 : if self.desc.is_delta() {
701 489 : timeline.metrics.layer_count_delta.dec();
702 489 : timeline.metrics.layer_size_delta.sub(self.desc.file_size);
703 489 : } else {
704 51 : timeline.metrics.layer_count_image.dec();
705 51 : timeline.metrics.layer_size_image.sub(self.desc.file_size);
706 51 : }
707 :
708 540 : if matches!(self.access_stats.visibility(), LayerVisibilityHint::Visible) {
709 540 : debug_assert!(
710 540 : timeline.metrics.visible_physical_size_gauge.get() >= self.desc.file_size
711 : );
712 540 : timeline
713 540 : .metrics
714 540 : .visible_physical_size_gauge
715 540 : .sub(self.desc.file_size);
716 0 : }
717 16 : }
718 :
719 556 : if !*self.wanted_deleted.get_mut() {
720 98 : return;
721 458 : }
722 :
723 458 : 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 458 : let path = std::mem::take(&mut self.path);
726 458 : let file_name = self.layer_desc().layer_name();
727 458 : let file_size = self.layer_desc().file_size;
728 458 : let meta = self.metadata();
729 458 : let status = self.status.take();
730 458 :
731 458 : Self::spawn_blocking(move || {
732 457 : let _g = span.entered();
733 457 :
734 457 : // carry this until we are finished for [`Layer::wait_drop`] support
735 457 : let _status = status;
736 :
737 457 : 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 457 : let Ok(_guard) = timeline.gate.enter() else {
745 0 : LAYER_IMPL_METRICS.inc_deletes_failed(DeleteFailed::TimelineGone);
746 0 : return;
747 : };
748 :
749 457 : let removed = match std::fs::remove_file(path) {
750 455 : 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 457 : if removed {
768 455 : timeline.metrics.resident_physical_size_sub(file_size);
769 455 : }
770 457 : let res = timeline
771 457 : .remote_client
772 457 : .schedule_deletion_of_unlinked(vec![(file_name, meta)]);
773 :
774 457 : 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 457 : } else {
786 457 : LAYER_IMPL_METRICS.inc_completed_deletes();
787 457 : }
788 458 : });
789 556 : }
790 : }
791 :
792 : impl LayerInner {
793 : #[allow(clippy::too_many_arguments)]
794 1714 : fn new(
795 1714 : conf: &'static PageServerConf,
796 1714 : timeline: &Arc<Timeline>,
797 1714 : local_path: Utf8PathBuf,
798 1714 : desc: PersistentLayerDesc,
799 1714 : downloaded: Option<Arc<DownloadedLayer>>,
800 1714 : generation: Generation,
801 1714 : shard: ShardIndex,
802 1714 : ) -> Self {
803 1714 : let (inner, version, init_status) = if let Some(inner) = downloaded {
804 1714 : let version = inner.version;
805 1714 : let resident = ResidentOrWantedEvicted::Resident(inner);
806 1714 : (
807 1714 : heavier_once_cell::OnceCell::new(resident),
808 1714 : version,
809 1714 : Status::Resident,
810 1714 : )
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 1714 : if desc.is_delta() {
817 1416 : timeline.metrics.layer_count_delta.inc();
818 1416 : timeline.metrics.layer_size_delta.add(desc.file_size);
819 1416 : } else {
820 298 : timeline.metrics.layer_count_image.inc();
821 298 : timeline.metrics.layer_size_image.add(desc.file_size);
822 298 : }
823 :
824 : // New layers are visible by default. This metric is later updated on drop or in set_visibility
825 1714 : timeline
826 1714 : .metrics
827 1714 : .visible_physical_size_gauge
828 1714 : .add(desc.file_size);
829 1714 :
830 1714 : LayerInner {
831 1714 : conf,
832 1714 : path: local_path,
833 1714 : desc,
834 1714 : timeline: Arc::downgrade(timeline),
835 1714 : access_stats: Default::default(),
836 1714 : wanted_deleted: AtomicBool::new(false),
837 1714 : inner,
838 1714 : version: AtomicUsize::new(version),
839 1714 : status: Some(tokio::sync::watch::channel(init_status).0),
840 1714 : consecutive_failures: AtomicUsize::new(0),
841 1714 : generation,
842 1714 : shard,
843 1714 : last_evicted_at: std::sync::Mutex::default(),
844 1714 : #[cfg(test)]
845 1714 : failpoints: Default::default(),
846 1714 : }
847 1714 : }
848 :
849 464 : fn delete_on_drop(&self) {
850 464 : let res =
851 464 : self.wanted_deleted
852 464 : .compare_exchange(false, true, Ordering::Release, Ordering::Relaxed);
853 464 :
854 464 : if res.is_ok() {
855 460 : LAYER_IMPL_METRICS.inc_started_deletes();
856 460 : }
857 464 : }
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 212573 : async fn get_or_maybe_download(
927 212573 : self: &Arc<Self>,
928 212573 : allow_download: bool,
929 212573 : ctx: Option<&RequestContext>,
930 212573 : ) -> 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 212573 : let init_cancelled = scopeguard::guard((), |_| LAYER_IMPL_METRICS.inc_init_cancelled());
936 :
937 212573 : let locked = self
938 212573 : .inner
939 212573 : .get_or_init_detached()
940 2 : .await
941 212573 : .map(|mut guard| guard.get_and_upgrade().ok_or(guard));
942 212573 :
943 212573 : scopeguard::ScopeGuard::into_inner(init_cancelled);
944 :
945 212557 : match locked {
946 : // this path could had been a RwLock::read
947 212557 : 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 11 : .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 10 : .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 10 : .await
1047 212573 : }
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 76 : 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 10 : 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 72 : .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 106 : async fn needs_download(&self) -> Result<Option<NeedsDownload>, std::io::Error> {
1259 106 : match tokio::fs::metadata(&self.path).await {
1260 98 : 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 106 : }
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 122 : fn is_file_present_and_good_size(&self, m: &std::fs::Metadata) -> Result<(), NeedsDownload> {
1275 122 : // in future, this should include sha2-256 validation of the file.
1276 122 : if !m.is_file() {
1277 0 : Err(NeedsDownload::NotFile(m.file_type()))
1278 122 : } 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 122 : Ok(())
1285 : }
1286 122 : }
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 2396 : fn metadata(&self) -> LayerFileMetadata {
1558 2396 : LayerFileMetadata::new(self.desc.file_size, self.generation, self.shard)
1559 2396 : }
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 476 : fn spawn_blocking<F>(f: F)
1576 476 : where
1577 476 : F: FnOnce() + Send + 'static,
1578 476 : {
1579 476 : #[cfg(test)]
1580 476 : tokio::task::spawn_blocking(f);
1581 476 : #[cfg(not(test))]
1582 476 : crate::task_mgr::BACKGROUND_RUNTIME.spawn_blocking(f);
1583 476 : }
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 578 : fn drop(&mut self) {
1677 578 : if let Some(owner) = self.owner.upgrade() {
1678 24 : owner.on_downloaded_layer_drop(self.version);
1679 554 : } else {
1680 554 : // Layer::drop will handle cancelling the eviction; because of drop order and
1681 554 : // `DownloadedLayer` never leaking, we cannot know here if eviction was requested.
1682 554 : }
1683 578 : }
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 213035 : async fn get<'a>(
1695 213035 : &'a self,
1696 213035 : owner: &Arc<LayerInner>,
1697 213035 : ctx: &RequestContext,
1698 213035 : ) -> anyhow::Result<&'a LayerKind> {
1699 213035 : let init = || async {
1700 1148 : assert_eq!(
1701 1148 : Weak::as_ptr(&self.owner),
1702 1148 : Arc::as_ptr(owner),
1703 0 : "these are the same, just avoiding the upgrade"
1704 : );
1705 :
1706 1148 : let res = if owner.desc.is_delta {
1707 1046 : let ctx = RequestContextBuilder::extend(ctx)
1708 1046 : .page_content_kind(crate::context::PageContentKind::DeltaLayerSummary)
1709 1046 : .build();
1710 1046 : let summary = Some(delta_layer::Summary::expected(
1711 1046 : owner.desc.tenant_shard_id.tenant_id,
1712 1046 : owner.desc.timeline_id,
1713 1046 : owner.desc.key_range.clone(),
1714 1046 : owner.desc.lsn_range.clone(),
1715 1046 : ));
1716 1046 : delta_layer::DeltaLayerInner::load(
1717 1046 : &owner.path,
1718 1046 : summary,
1719 1046 : Some(owner.conf.max_vectored_read_bytes),
1720 1046 : &ctx,
1721 1046 : )
1722 1049 : .await
1723 1046 : .map(LayerKind::Delta)
1724 : } else {
1725 102 : let ctx = RequestContextBuilder::extend(ctx)
1726 102 : .page_content_kind(crate::context::PageContentKind::ImageLayerSummary)
1727 102 : .build();
1728 102 : let lsn = owner.desc.image_layer_lsn();
1729 102 : let summary = Some(image_layer::Summary::expected(
1730 102 : owner.desc.tenant_shard_id.tenant_id,
1731 102 : owner.desc.timeline_id,
1732 102 : owner.desc.key_range.clone(),
1733 102 : lsn,
1734 102 : ));
1735 102 : image_layer::ImageLayerInner::load(
1736 102 : &owner.path,
1737 102 : lsn,
1738 102 : summary,
1739 102 : Some(owner.conf.max_vectored_read_bytes),
1740 102 : &ctx,
1741 102 : )
1742 103 : .await
1743 102 : .map(LayerKind::Image)
1744 : };
1745 :
1746 1148 : match res {
1747 1148 : 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 2296 : };
1760 213035 : self.kind
1761 213035 : .get_or_init(init)
1762 1152 : .await
1763 213035 : .as_ref()
1764 213035 : // We already logged the full backtrace above, once. Don't repeat that here.
1765 213035 : .map_err(|e| anyhow::anyhow!("layer load failed earlier: {e}"))
1766 213035 : }
1767 :
1768 212061 : async fn get_values_reconstruct_data(
1769 212061 : &self,
1770 212061 : keyspace: KeySpace,
1771 212061 : lsn_range: Range<Lsn>,
1772 212061 : reconstruct_data: &mut ValuesReconstructState,
1773 212061 : owner: &Arc<LayerInner>,
1774 212061 : ctx: &RequestContext,
1775 212061 : ) -> Result<(), GetVectoredError> {
1776 : use LayerKind::*;
1777 :
1778 212061 : match self
1779 212061 : .get(owner, ctx)
1780 858 : .await
1781 212061 : .map_err(GetVectoredError::Other)?
1782 : {
1783 204092 : Delta(d) => {
1784 204092 : d.get_values_reconstruct_data(keyspace, lsn_range, reconstruct_data, ctx)
1785 84431 : .await
1786 : }
1787 7969 : Image(i) => {
1788 7969 : i.get_values_reconstruct_data(keyspace, reconstruct_data, ctx)
1789 4945 : .await
1790 : }
1791 : }
1792 212061 : }
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 1916 : fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1821 1916 : write!(f, "{}", self.owner)
1822 1916 : }
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 804 : #[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<DeltaEntry<'a>>> {
1845 : use LayerKind::*;
1846 :
1847 : let owner = &self.owner.0;
1848 : match self.downloaded.get(owner, ctx).await? {
1849 : Delta(ref d) => {
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 : delta_layer::DeltaLayerInner::load_keys(d, ctx)
1856 : .await
1857 0 : .with_context(|| format!("Layer index is corrupted for {self}"))
1858 : }
1859 : Image(_) => anyhow::bail!(format!("cannot load_keys on a image layer {self}")),
1860 : }
1861 : }
1862 :
1863 : /// Read all they keys in this layer which match the ShardIdentity, and write them all to
1864 : /// the provided writer. Return the number of keys written.
1865 16 : #[tracing::instrument(level = tracing::Level::DEBUG, skip_all, fields(layer=%self))]
1866 : pub(crate) async fn filter(
1867 : &self,
1868 : shard_identity: &ShardIdentity,
1869 : writer: &mut ImageLayerWriter,
1870 : ctx: &RequestContext,
1871 : ) -> Result<usize, CompactionError> {
1872 : use LayerKind::*;
1873 :
1874 : match self
1875 : .downloaded
1876 : .get(&self.owner.0, ctx)
1877 : .await
1878 : .map_err(CompactionError::Other)?
1879 : {
1880 : Delta(_) => {
1881 : return Err(CompactionError::Other(anyhow::anyhow!(format!(
1882 : "cannot filter() on a delta layer {self}"
1883 : ))));
1884 : }
1885 : Image(i) => i
1886 : .filter(shard_identity, writer, ctx)
1887 : .await
1888 : .map_err(CompactionError::Other),
1889 : }
1890 : }
1891 :
1892 : /// Returns the amount of keys and values written to the writer.
1893 10 : pub(crate) async fn copy_delta_prefix(
1894 10 : &self,
1895 10 : writer: &mut super::delta_layer::DeltaLayerWriter,
1896 10 : until: Lsn,
1897 10 : ctx: &RequestContext,
1898 10 : ) -> anyhow::Result<usize> {
1899 : use LayerKind::*;
1900 :
1901 10 : let owner = &self.owner.0;
1902 10 :
1903 10 : match self.downloaded.get(owner, ctx).await? {
1904 10 : Delta(ref d) => d
1905 10 : .copy_prefix(writer, until, ctx)
1906 13 : .await
1907 10 : .with_context(|| format!("copy_delta_prefix until {until} of {self}")),
1908 0 : Image(_) => anyhow::bail!(format!("cannot copy_lsn_prefix of image layer {self}")),
1909 : }
1910 10 : }
1911 :
1912 1737 : pub(crate) fn local_path(&self) -> &Utf8Path {
1913 1737 : &self.owner.0.path
1914 1737 : }
1915 :
1916 1534 : pub(crate) fn metadata(&self) -> LayerFileMetadata {
1917 1534 : self.owner.metadata()
1918 1534 : }
1919 :
1920 : /// Cast the layer to a delta, return an error if it is an image layer.
1921 512 : pub(crate) async fn get_as_delta(
1922 512 : &self,
1923 512 : ctx: &RequestContext,
1924 512 : ) -> anyhow::Result<&delta_layer::DeltaLayerInner> {
1925 : use LayerKind::*;
1926 512 : match self.downloaded.get(&self.owner.0, ctx).await? {
1927 512 : Delta(ref d) => Ok(d),
1928 0 : Image(_) => Err(anyhow::anyhow!("image layer")),
1929 : }
1930 512 : }
1931 :
1932 : /// Cast the layer to an image, return an error if it is a delta layer.
1933 38 : pub(crate) async fn get_as_image(
1934 38 : &self,
1935 38 : ctx: &RequestContext,
1936 38 : ) -> anyhow::Result<&image_layer::ImageLayerInner> {
1937 : use LayerKind::*;
1938 38 : match self.downloaded.get(&self.owner.0, ctx).await? {
1939 38 : Image(ref d) => Ok(d),
1940 0 : Delta(_) => Err(anyhow::anyhow!("delta layer")),
1941 : }
1942 38 : }
1943 : }
1944 :
1945 : impl AsLayerDesc for ResidentLayer {
1946 5869 : fn layer_desc(&self) -> &PersistentLayerDesc {
1947 5869 : self.owner.layer_desc()
1948 5869 : }
1949 : }
1950 :
1951 : impl AsRef<Layer> for ResidentLayer {
1952 1924 : fn as_ref(&self) -> &Layer {
1953 1924 : &self.owner
1954 1924 : }
1955 : }
1956 :
1957 : /// Drop the eviction guard.
1958 : impl From<ResidentLayer> for Layer {
1959 420 : fn from(value: ResidentLayer) -> Self {
1960 420 : value.owner
1961 420 : }
1962 : }
1963 :
1964 : use metrics::IntCounter;
1965 :
1966 : pub(crate) struct LayerImplMetrics {
1967 : started_evictions: IntCounter,
1968 : completed_evictions: IntCounter,
1969 : cancelled_evictions: enum_map::EnumMap<EvictionCancelled, IntCounter>,
1970 :
1971 : started_deletes: IntCounter,
1972 : completed_deletes: IntCounter,
1973 : failed_deletes: enum_map::EnumMap<DeleteFailed, IntCounter>,
1974 :
1975 : rare_counters: enum_map::EnumMap<RareEvent, IntCounter>,
1976 : inits_cancelled: metrics::core::GenericCounter<metrics::core::AtomicU64>,
1977 : redownload_after: metrics::Histogram,
1978 : time_to_evict: metrics::Histogram,
1979 : }
1980 :
1981 : impl Default for LayerImplMetrics {
1982 42 : fn default() -> Self {
1983 : use enum_map::Enum;
1984 :
1985 : // reminder: these will be pageserver_layer_* with "_total" suffix
1986 :
1987 42 : let started_evictions = metrics::register_int_counter!(
1988 42 : "pageserver_layer_started_evictions",
1989 42 : "Evictions started in the Layer implementation"
1990 42 : )
1991 42 : .unwrap();
1992 42 : let completed_evictions = metrics::register_int_counter!(
1993 42 : "pageserver_layer_completed_evictions",
1994 42 : "Evictions completed in the Layer implementation"
1995 42 : )
1996 42 : .unwrap();
1997 42 :
1998 42 : let cancelled_evictions = metrics::register_int_counter_vec!(
1999 42 : "pageserver_layer_cancelled_evictions_count",
2000 42 : "Different reasons for evictions to have been cancelled or failed",
2001 42 : &["reason"]
2002 42 : )
2003 42 : .unwrap();
2004 42 :
2005 378 : let cancelled_evictions = enum_map::EnumMap::from_array(std::array::from_fn(|i| {
2006 378 : let reason = EvictionCancelled::from_usize(i);
2007 378 : let s = reason.as_str();
2008 378 : cancelled_evictions.with_label_values(&[s])
2009 378 : }));
2010 42 :
2011 42 : let started_deletes = metrics::register_int_counter!(
2012 42 : "pageserver_layer_started_deletes",
2013 42 : "Deletions on drop pending in the Layer implementation"
2014 42 : )
2015 42 : .unwrap();
2016 42 : let completed_deletes = metrics::register_int_counter!(
2017 42 : "pageserver_layer_completed_deletes",
2018 42 : "Deletions on drop completed in the Layer implementation"
2019 42 : )
2020 42 : .unwrap();
2021 42 :
2022 42 : let failed_deletes = metrics::register_int_counter_vec!(
2023 42 : "pageserver_layer_failed_deletes_count",
2024 42 : "Different reasons for deletions on drop to have failed",
2025 42 : &["reason"]
2026 42 : )
2027 42 : .unwrap();
2028 42 :
2029 84 : let failed_deletes = enum_map::EnumMap::from_array(std::array::from_fn(|i| {
2030 84 : let reason = DeleteFailed::from_usize(i);
2031 84 : let s = reason.as_str();
2032 84 : failed_deletes.with_label_values(&[s])
2033 84 : }));
2034 42 :
2035 42 : let rare_counters = metrics::register_int_counter_vec!(
2036 42 : "pageserver_layer_assumed_rare_count",
2037 42 : "Times unexpected or assumed rare event happened",
2038 42 : &["event"]
2039 42 : )
2040 42 : .unwrap();
2041 42 :
2042 294 : let rare_counters = enum_map::EnumMap::from_array(std::array::from_fn(|i| {
2043 294 : let event = RareEvent::from_usize(i);
2044 294 : let s = event.as_str();
2045 294 : rare_counters.with_label_values(&[s])
2046 294 : }));
2047 42 :
2048 42 : let inits_cancelled = metrics::register_int_counter!(
2049 42 : "pageserver_layer_inits_cancelled_count",
2050 42 : "Times Layer initialization was cancelled",
2051 42 : )
2052 42 : .unwrap();
2053 42 :
2054 42 : let redownload_after = {
2055 42 : let minute = 60.0;
2056 42 : let hour = 60.0 * minute;
2057 42 : metrics::register_histogram!(
2058 42 : "pageserver_layer_redownloaded_after",
2059 42 : "Time between evicting and re-downloading.",
2060 42 : vec![
2061 42 : 10.0,
2062 42 : 30.0,
2063 42 : minute,
2064 42 : 5.0 * minute,
2065 42 : 15.0 * minute,
2066 42 : 30.0 * minute,
2067 42 : hour,
2068 42 : 12.0 * hour,
2069 42 : ]
2070 42 : )
2071 42 : .unwrap()
2072 42 : };
2073 42 :
2074 42 : let time_to_evict = metrics::register_histogram!(
2075 42 : "pageserver_layer_eviction_held_permit_seconds",
2076 42 : "Time eviction held the permit.",
2077 42 : vec![0.001, 0.010, 0.100, 0.500, 1.000, 5.000]
2078 42 : )
2079 42 : .unwrap();
2080 42 :
2081 42 : Self {
2082 42 : started_evictions,
2083 42 : completed_evictions,
2084 42 : cancelled_evictions,
2085 42 :
2086 42 : started_deletes,
2087 42 : completed_deletes,
2088 42 : failed_deletes,
2089 42 :
2090 42 : rare_counters,
2091 42 : inits_cancelled,
2092 42 : redownload_after,
2093 42 : time_to_evict,
2094 42 : }
2095 42 : }
2096 : }
2097 :
2098 : impl LayerImplMetrics {
2099 26 : fn inc_started_evictions(&self) {
2100 26 : self.started_evictions.inc();
2101 26 : }
2102 18 : fn inc_completed_evictions(&self) {
2103 18 : self.completed_evictions.inc();
2104 18 : }
2105 8 : fn inc_eviction_cancelled(&self, reason: EvictionCancelled) {
2106 8 : self.cancelled_evictions[reason].inc()
2107 8 : }
2108 :
2109 460 : fn inc_started_deletes(&self) {
2110 460 : self.started_deletes.inc();
2111 460 : }
2112 457 : fn inc_completed_deletes(&self) {
2113 457 : self.completed_deletes.inc();
2114 457 : }
2115 0 : fn inc_deletes_failed(&self, reason: DeleteFailed) {
2116 0 : self.failed_deletes[reason].inc();
2117 0 : }
2118 :
2119 : /// Counted separatedly from failed layer deletes because we will complete the layer deletion
2120 : /// attempt regardless of failure to delete local file.
2121 0 : fn inc_delete_removes_failed(&self) {
2122 0 : self.rare_counters[RareEvent::RemoveOnDropFailed].inc();
2123 0 : }
2124 :
2125 : /// Expected rare just as cancellations are rare, but we could have cancellations separate from
2126 : /// the single caller which can start the download, so use this counter to separte them.
2127 0 : fn inc_init_completed_without_requester(&self) {
2128 0 : self.rare_counters[RareEvent::InitCompletedWithoutRequester].inc();
2129 0 : }
2130 :
2131 : /// Expected rare because cancellations are unexpected, and failures are unexpected
2132 0 : fn inc_download_failed_without_requester(&self) {
2133 0 : self.rare_counters[RareEvent::DownloadFailedWithoutRequester].inc();
2134 0 : }
2135 :
2136 : /// The Weak in ResidentOrWantedEvicted::WantedEvicted was successfully upgraded.
2137 : ///
2138 : /// If this counter is always zero, we should replace ResidentOrWantedEvicted type with an
2139 : /// Option.
2140 0 : fn inc_raced_wanted_evicted_accesses(&self) {
2141 0 : self.rare_counters[RareEvent::UpgradedWantedEvicted].inc();
2142 0 : }
2143 :
2144 : /// These are only expected for [`Self::inc_init_cancelled`] amount when
2145 : /// running with remote storage.
2146 6 : fn inc_init_needed_no_download(&self) {
2147 6 : self.rare_counters[RareEvent::InitWithoutDownload].inc();
2148 6 : }
2149 :
2150 : /// Expected rare because all layer files should be readable and good
2151 0 : fn inc_permanent_loading_failures(&self) {
2152 0 : self.rare_counters[RareEvent::PermanentLoadingFailure].inc();
2153 0 : }
2154 :
2155 0 : fn inc_init_cancelled(&self) {
2156 0 : self.inits_cancelled.inc()
2157 0 : }
2158 :
2159 6 : fn record_redownloaded_after(&self, duration: std::time::Duration) {
2160 6 : self.redownload_after.observe(duration.as_secs_f64())
2161 6 : }
2162 :
2163 : /// This would be bad if it ever happened, or mean extreme disk pressure. We should probably
2164 : /// instead cancel eviction if we would have read waiters. We cannot however separate reads
2165 : /// from other evictions, so this could have noise as well.
2166 0 : fn inc_evicted_with_waiters(&self) {
2167 0 : self.rare_counters[RareEvent::EvictedWithWaiters].inc();
2168 0 : }
2169 :
2170 : /// Recorded at least initially as the permit is now acquired in async context before
2171 : /// spawn_blocking action.
2172 18 : fn record_time_to_evict(&self, duration: std::time::Duration) {
2173 18 : self.time_to_evict.observe(duration.as_secs_f64())
2174 18 : }
2175 : }
2176 :
2177 : #[derive(Debug, Clone, Copy, enum_map::Enum)]
2178 : enum EvictionCancelled {
2179 : LayerGone,
2180 : TimelineGone,
2181 : VersionCheckFailed,
2182 : FileNotFound,
2183 : RemoveFailed,
2184 : AlreadyReinitialized,
2185 : /// Not evicted because of a pending reinitialization
2186 : LostToDownload,
2187 : /// After eviction, there was a new layer access which cancelled the eviction.
2188 : UpgradedBackOnAccess,
2189 : UnexpectedEvictedState,
2190 : }
2191 :
2192 : impl EvictionCancelled {
2193 378 : fn as_str(&self) -> &'static str {
2194 378 : match self {
2195 42 : EvictionCancelled::LayerGone => "layer_gone",
2196 42 : EvictionCancelled::TimelineGone => "timeline_gone",
2197 42 : EvictionCancelled::VersionCheckFailed => "version_check_fail",
2198 42 : EvictionCancelled::FileNotFound => "file_not_found",
2199 42 : EvictionCancelled::RemoveFailed => "remove_failed",
2200 42 : EvictionCancelled::AlreadyReinitialized => "already_reinitialized",
2201 42 : EvictionCancelled::LostToDownload => "lost_to_download",
2202 42 : EvictionCancelled::UpgradedBackOnAccess => "upgraded_back_on_access",
2203 42 : EvictionCancelled::UnexpectedEvictedState => "unexpected_evicted_state",
2204 : }
2205 378 : }
2206 : }
2207 :
2208 : #[derive(enum_map::Enum)]
2209 : enum DeleteFailed {
2210 : TimelineGone,
2211 : DeleteSchedulingFailed,
2212 : }
2213 :
2214 : impl DeleteFailed {
2215 84 : fn as_str(&self) -> &'static str {
2216 84 : match self {
2217 42 : DeleteFailed::TimelineGone => "timeline_gone",
2218 42 : DeleteFailed::DeleteSchedulingFailed => "delete_scheduling_failed",
2219 : }
2220 84 : }
2221 : }
2222 :
2223 : #[derive(enum_map::Enum)]
2224 : enum RareEvent {
2225 : RemoveOnDropFailed,
2226 : InitCompletedWithoutRequester,
2227 : DownloadFailedWithoutRequester,
2228 : UpgradedWantedEvicted,
2229 : InitWithoutDownload,
2230 : PermanentLoadingFailure,
2231 : EvictedWithWaiters,
2232 : }
2233 :
2234 : impl RareEvent {
2235 294 : fn as_str(&self) -> &'static str {
2236 : use RareEvent::*;
2237 :
2238 294 : match self {
2239 42 : RemoveOnDropFailed => "remove_on_drop_failed",
2240 42 : InitCompletedWithoutRequester => "init_completed_without",
2241 42 : DownloadFailedWithoutRequester => "download_failed_without",
2242 42 : UpgradedWantedEvicted => "raced_wanted_evicted",
2243 42 : InitWithoutDownload => "init_needed_no_download",
2244 42 : PermanentLoadingFailure => "permanent_loading_failure",
2245 42 : EvictedWithWaiters => "evicted_with_waiters",
2246 : }
2247 294 : }
2248 : }
2249 :
2250 : pub(crate) static LAYER_IMPL_METRICS: once_cell::sync::Lazy<LayerImplMetrics> =
2251 : once_cell::sync::Lazy::new(LayerImplMetrics::default);
|