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