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