LCOV - code coverage report
Current view: top level - pageserver/src - disk_usage_eviction_task.rs (source / functions) Coverage Total Hit
Test: ccf45ed1c149555259baec52d6229a81013dcd6a.info Lines: 18.4 % 664 122
Test Date: 2024-08-21 17:32:46 Functions: 15.3 % 131 20

            Line data    Source code
       1              : //! This module implements the pageserver-global disk-usage-based layer eviction task.
       2              : //!
       3              : //! # Mechanics
       4              : //!
       5              : //! Function `launch_disk_usage_global_eviction_task` starts a pageserver-global background
       6              : //! loop that evicts layers in response to a shortage of available bytes
       7              : //! in the $repo/tenants directory's filesystem.
       8              : //!
       9              : //! The loop runs periodically at a configurable `period`.
      10              : //!
      11              : //! Each loop iteration uses `statvfs` to determine filesystem-level space usage.
      12              : //! It compares the returned usage data against two different types of thresholds.
      13              : //! The iteration tries to evict layers until app-internal accounting says we should be below the thresholds.
      14              : //! We cross-check this internal accounting with the real world by making another `statvfs` at the end of the iteration.
      15              : //! We're good if that second statvfs shows that we're _actually_ below the configured thresholds.
      16              : //! If we're still above one or more thresholds, we emit a warning log message, leaving it to the operator to investigate further.
      17              : //!
      18              : //! # Eviction Policy
      19              : //!
      20              : //! There are two thresholds:
      21              : //! `max_usage_pct` is the relative available space, expressed in percent of the total filesystem space.
      22              : //! If the actual usage is higher, the threshold is exceeded.
      23              : //! `min_avail_bytes` is the absolute available space in bytes.
      24              : //! If the actual usage is lower, the threshold is exceeded.
      25              : //! If either of these thresholds is exceeded, the system is considered to have "disk pressure", and eviction
      26              : //! is performed on the next iteration, to release disk space and bring the usage below the thresholds again.
      27              : //! The iteration evicts layers in LRU fashion, but, with a weak reservation per tenant.
      28              : //! The reservation is to keep the most recently accessed X bytes per tenant resident.
      29              : //! If we cannot relieve pressure by evicting layers outside of the reservation, we
      30              : //! start evicting layers that are part of the reservation, LRU first.
      31              : //!
      32              : //! The value for the per-tenant reservation is referred to as `tenant_min_resident_size`
      33              : //! throughout the code, but, no actual variable carries that name.
      34              : //! The per-tenant default value is the `max(tenant's layer file sizes, regardless of local or remote)`.
      35              : //! The idea is to allow at least one layer to be resident per tenant, to ensure it can make forward progress
      36              : //! during page reconstruction.
      37              : //! An alternative default for all tenants can be specified in the `tenant_config` section of the config.
      38              : //! Lastly, each tenant can have an override in their respective tenant config (`min_resident_size_override`).
      39              : 
      40              : // Implementation notes:
      41              : // - The `#[allow(dead_code)]` above various structs are to suppress warnings about only the Debug impl
      42              : //   reading these fields. We use the Debug impl for semi-structured logging, though.
      43              : 
      44              : use std::{
      45              :     sync::Arc,
      46              :     time::{Duration, SystemTime},
      47              : };
      48              : 
      49              : use anyhow::Context;
      50              : use pageserver_api::shard::TenantShardId;
      51              : use remote_storage::GenericRemoteStorage;
      52              : use serde::{Deserialize, Serialize};
      53              : use tokio::time::Instant;
      54              : use tokio_util::sync::CancellationToken;
      55              : use tracing::{debug, error, info, instrument, warn, Instrument};
      56              : use utils::serde_percent::Percent;
      57              : use utils::{completion, id::TimelineId};
      58              : 
      59              : use crate::{
      60              :     config::PageServerConf,
      61              :     metrics::disk_usage_based_eviction::METRICS,
      62              :     task_mgr::{self, BACKGROUND_RUNTIME},
      63              :     tenant::{
      64              :         mgr::TenantManager,
      65              :         remote_timeline_client::LayerFileMetadata,
      66              :         secondary::SecondaryTenant,
      67              :         storage_layer::{AsLayerDesc, EvictionError, Layer, LayerName, LayerVisibilityHint},
      68              :     },
      69              :     CancellableTask, DiskUsageEvictionTask,
      70              : };
      71              : 
      72           10 : #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
      73              : pub struct DiskUsageEvictionTaskConfig {
      74              :     pub max_usage_pct: Percent,
      75              :     pub min_avail_bytes: u64,
      76              :     #[serde(with = "humantime_serde")]
      77              :     pub period: Duration,
      78              :     #[cfg(feature = "testing")]
      79              :     pub mock_statvfs: Option<crate::statvfs::mock::Behavior>,
      80              :     /// Select sorting for evicted layers
      81              :     #[serde(default)]
      82              :     pub eviction_order: EvictionOrder,
      83              : }
      84              : 
      85              : /// Selects the sort order for eviction candidates *after* per tenant `min_resident_size`
      86              : /// partitioning.
      87            0 : #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
      88              : #[serde(tag = "type", content = "args")]
      89              : pub enum EvictionOrder {
      90              :     /// Order the layers to be evicted by how recently they have been accessed relatively within
      91              :     /// the set of resident layers of a tenant.
      92              :     RelativeAccessed {
      93              :         /// Determines if the tenant with most layers should lose first.
      94              :         ///
      95              :         /// Having this enabled is currently the only reasonable option, because the order in which
      96              :         /// we read tenants is deterministic. If we find the need to use this as `false`, we need
      97              :         /// to ensure nondeterminism by adding in a random number to break the
      98              :         /// `relative_last_activity==0.0` ties.
      99              :         #[serde(default = "default_highest_layer_count_loses_first")]
     100              :         highest_layer_count_loses_first: bool,
     101              :     },
     102              : }
     103              : 
     104              : impl Default for EvictionOrder {
     105            6 :     fn default() -> Self {
     106            6 :         Self::RelativeAccessed {
     107            6 :             highest_layer_count_loses_first: true,
     108            6 :         }
     109            6 :     }
     110              : }
     111              : 
     112            0 : fn default_highest_layer_count_loses_first() -> bool {
     113            0 :     true
     114            0 : }
     115              : 
     116              : impl EvictionOrder {
     117            0 :     fn sort(&self, candidates: &mut [(EvictionPartition, EvictionCandidate)]) {
     118            0 :         use EvictionOrder::*;
     119            0 : 
     120            0 :         match self {
     121            0 :             RelativeAccessed { .. } => candidates.sort_unstable_by_key(|(partition, candidate)| {
     122            0 :                 (*partition, candidate.relative_last_activity)
     123            0 :             }),
     124            0 :         }
     125            0 :     }
     126              : 
     127              :     /// Called to fill in the [`EvictionCandidate::relative_last_activity`] while iterating tenants
     128              :     /// layers in **most** recently used order.
     129           40 :     fn relative_last_activity(&self, total: usize, index: usize) -> finite_f32::FiniteF32 {
     130           40 :         use EvictionOrder::*;
     131           40 : 
     132           40 :         match self {
     133           40 :             RelativeAccessed {
     134           40 :                 highest_layer_count_loses_first,
     135              :             } => {
     136              :                 // keeping the -1 or not decides if every tenant should lose their least recently accessed
     137              :                 // layer OR if this should happen in the order of having highest layer count:
     138           40 :                 let fudge = if *highest_layer_count_loses_first {
     139              :                     // relative_last_activity vs. tenant layer count:
     140              :                     // - 0.1..=1.0 (10 layers)
     141              :                     // - 0.01..=1.0 (100 layers)
     142              :                     // - 0.001..=1.0 (1000 layers)
     143              :                     //
     144              :                     // leading to evicting less of the smallest tenants.
     145           20 :                     0
     146              :                 } else {
     147              :                     // use full 0.0..=1.0 range, which means even the smallest tenants could always lose a
     148              :                     // layer. the actual ordering is unspecified: for 10k tenants on a pageserver it could
     149              :                     // be that less than 10k layer evictions is enough, so we would not need to evict from
     150              :                     // all tenants.
     151              :                     //
     152              :                     // as the tenant ordering is now deterministic this could hit the same tenants
     153              :                     // disproportionetly on multiple invocations. alternative could be to remember how many
     154              :                     // layers did we evict last time from this tenant, and inject that as an additional
     155              :                     // fudge here.
     156           20 :                     1
     157              :                 };
     158              : 
     159           40 :                 let total = total.checked_sub(fudge).filter(|&x| x > 1).unwrap_or(1);
     160           40 :                 let divider = total as f32;
     161           40 : 
     162           40 :                 // most recently used is always (total - 0) / divider == 1.0
     163           40 :                 // least recently used depends on the fudge:
     164           40 :                 // -       (total - 1) - (total - 1) / total => 0 / total
     165           40 :                 // -             total - (total - 1) / total => 1 / total
     166           40 :                 let distance = (total - index) as f32;
     167           40 : 
     168           40 :                 finite_f32::FiniteF32::try_from_normalized(distance / divider)
     169           40 :                     .unwrap_or_else(|val| {
     170            0 :                         tracing::warn!(%fudge, "calculated invalid relative_last_activity for i={index}, total={total}: {val}");
     171            0 :                         finite_f32::FiniteF32::ZERO
     172           40 :                     })
     173           40 :             }
     174           40 :         }
     175           40 :     }
     176              : }
     177              : 
     178              : #[derive(Default)]
     179              : pub struct State {
     180              :     /// Exclude http requests and background task from running at the same time.
     181              :     mutex: tokio::sync::Mutex<()>,
     182              : }
     183              : 
     184            0 : pub fn launch_disk_usage_global_eviction_task(
     185            0 :     conf: &'static PageServerConf,
     186            0 :     storage: GenericRemoteStorage,
     187            0 :     state: Arc<State>,
     188            0 :     tenant_manager: Arc<TenantManager>,
     189            0 :     background_jobs_barrier: completion::Barrier,
     190            0 : ) -> Option<DiskUsageEvictionTask> {
     191            0 :     let Some(task_config) = &conf.disk_usage_based_eviction else {
     192            0 :         info!("disk usage based eviction task not configured");
     193            0 :         return None;
     194              :     };
     195              : 
     196            0 :     info!("launching disk usage based eviction task");
     197              : 
     198            0 :     let cancel = CancellationToken::new();
     199            0 :     let task = BACKGROUND_RUNTIME.spawn(task_mgr::exit_on_panic_or_error(
     200            0 :         "disk usage based eviction",
     201            0 :         {
     202            0 :             let cancel = cancel.clone();
     203            0 :             async move {
     204              :                 // wait until initial load is complete, because we cannot evict from loading tenants.
     205              :                 tokio::select! {
     206              :                     _ = cancel.cancelled() => { return anyhow::Ok(()); },
     207              :                     _ = background_jobs_barrier.wait() => { }
     208              :                 };
     209              : 
     210            0 :                 disk_usage_eviction_task(&state, task_config, &storage, tenant_manager, cancel)
     211            0 :                     .await;
     212            0 :                 anyhow::Ok(())
     213            0 :             }
     214            0 :         },
     215            0 :     ));
     216            0 : 
     217            0 :     Some(DiskUsageEvictionTask(CancellableTask { cancel, task }))
     218            0 : }
     219              : 
     220            0 : #[instrument(skip_all)]
     221              : async fn disk_usage_eviction_task(
     222              :     state: &State,
     223              :     task_config: &DiskUsageEvictionTaskConfig,
     224              :     storage: &GenericRemoteStorage,
     225              :     tenant_manager: Arc<TenantManager>,
     226              :     cancel: CancellationToken,
     227              : ) {
     228              :     scopeguard::defer! {
     229              :         info!("disk usage based eviction task finishing");
     230              :     };
     231              : 
     232              :     use crate::tenant::tasks::random_init_delay;
     233              :     {
     234              :         if random_init_delay(task_config.period, &cancel)
     235              :             .await
     236              :             .is_err()
     237              :         {
     238              :             return;
     239              :         }
     240              :     }
     241              : 
     242              :     let mut iteration_no = 0;
     243              :     loop {
     244              :         iteration_no += 1;
     245              :         let start = Instant::now();
     246              : 
     247            0 :         async {
     248            0 :             let res = disk_usage_eviction_task_iteration(
     249            0 :                 state,
     250            0 :                 task_config,
     251            0 :                 storage,
     252            0 :                 &tenant_manager,
     253            0 :                 &cancel,
     254            0 :             )
     255            0 :             .await;
     256              : 
     257            0 :             match res {
     258            0 :                 Ok(()) => {}
     259            0 :                 Err(e) => {
     260            0 :                     // these stat failures are expected to be very rare
     261            0 :                     warn!("iteration failed, unexpected error: {e:#}");
     262              :                 }
     263              :             }
     264            0 :         }
     265              :         .instrument(tracing::info_span!("iteration", iteration_no))
     266              :         .await;
     267              : 
     268              :         let sleep_until = start + task_config.period;
     269              :         if tokio::time::timeout_at(sleep_until, cancel.cancelled())
     270              :             .await
     271              :             .is_ok()
     272              :         {
     273              :             break;
     274              :         }
     275              :     }
     276              : }
     277              : 
     278              : pub trait Usage: Clone + Copy + std::fmt::Debug {
     279              :     fn has_pressure(&self) -> bool;
     280              :     fn add_available_bytes(&mut self, bytes: u64);
     281              : }
     282              : 
     283            0 : async fn disk_usage_eviction_task_iteration(
     284            0 :     state: &State,
     285            0 :     task_config: &DiskUsageEvictionTaskConfig,
     286            0 :     storage: &GenericRemoteStorage,
     287            0 :     tenant_manager: &Arc<TenantManager>,
     288            0 :     cancel: &CancellationToken,
     289            0 : ) -> anyhow::Result<()> {
     290            0 :     let tenants_dir = tenant_manager.get_conf().tenants_path();
     291            0 :     let usage_pre = filesystem_level_usage::get(&tenants_dir, task_config)
     292            0 :         .context("get filesystem-level disk usage before evictions")?;
     293            0 :     let res = disk_usage_eviction_task_iteration_impl(
     294            0 :         state,
     295            0 :         storage,
     296            0 :         usage_pre,
     297            0 :         tenant_manager,
     298            0 :         task_config.eviction_order,
     299            0 :         cancel,
     300            0 :     )
     301            0 :     .await;
     302            0 :     match res {
     303            0 :         Ok(outcome) => {
     304            0 :             debug!(?outcome, "disk_usage_eviction_iteration finished");
     305            0 :             match outcome {
     306            0 :                 IterationOutcome::NoPressure | IterationOutcome::Cancelled => {
     307            0 :                     // nothing to do, select statement below will handle things
     308            0 :                 }
     309            0 :                 IterationOutcome::Finished(outcome) => {
     310              :                     // Verify with statvfs whether we made any real progress
     311            0 :                     let after = filesystem_level_usage::get(&tenants_dir, task_config)
     312            0 :                         // It's quite unlikely to hit the error here. Keep the code simple and bail out.
     313            0 :                         .context("get filesystem-level disk usage after evictions")?;
     314              : 
     315            0 :                     debug!(?after, "disk usage");
     316              : 
     317            0 :                     if after.has_pressure() {
     318              :                         // Don't bother doing an out-of-order iteration here now.
     319              :                         // In practice, the task period is set to a value in the tens-of-seconds range,
     320              :                         // which will cause another iteration to happen soon enough.
     321              :                         // TODO: deltas between the three different usages would be helpful,
     322              :                         // consider MiB, GiB, TiB
     323            0 :                         warn!(?outcome, ?after, "disk usage still high");
     324              :                     } else {
     325            0 :                         info!(?outcome, ?after, "disk usage pressure relieved");
     326              :                     }
     327              :                 }
     328              :             }
     329              :         }
     330            0 :         Err(e) => {
     331            0 :             error!("disk_usage_eviction_iteration failed: {:#}", e);
     332              :         }
     333              :     }
     334              : 
     335            0 :     Ok(())
     336            0 : }
     337              : 
     338              : #[derive(Debug, Serialize)]
     339              : #[allow(clippy::large_enum_variant)]
     340              : pub enum IterationOutcome<U> {
     341              :     NoPressure,
     342              :     Cancelled,
     343              :     Finished(IterationOutcomeFinished<U>),
     344              : }
     345              : 
     346              : #[derive(Debug, Serialize)]
     347              : pub struct IterationOutcomeFinished<U> {
     348              :     /// The actual usage observed before we started the iteration.
     349              :     before: U,
     350              :     /// The expected value for `after`, according to internal accounting, after phase 1.
     351              :     planned: PlannedUsage<U>,
     352              :     /// The outcome of phase 2, where we actually do the evictions.
     353              :     ///
     354              :     /// If all layers that phase 1 planned to evict _can_ actually get evicted, this will
     355              :     /// be the same as `planned`.
     356              :     assumed: AssumedUsage<U>,
     357              : }
     358              : 
     359              : #[derive(Debug, Serialize)]
     360              : struct AssumedUsage<U> {
     361              :     /// The expected value for `after`, after phase 2.
     362              :     projected_after: U,
     363              :     /// The layers we failed to evict during phase 2.
     364              :     failed: LayerCount,
     365              : }
     366              : 
     367              : #[derive(Debug, Serialize)]
     368              : struct PlannedUsage<U> {
     369              :     respecting_tenant_min_resident_size: U,
     370              :     fallback_to_global_lru: Option<U>,
     371              : }
     372              : 
     373              : #[derive(Debug, Default, Serialize)]
     374              : struct LayerCount {
     375              :     file_sizes: u64,
     376              :     count: usize,
     377              : }
     378              : 
     379            0 : pub(crate) async fn disk_usage_eviction_task_iteration_impl<U: Usage>(
     380            0 :     state: &State,
     381            0 :     _storage: &GenericRemoteStorage,
     382            0 :     usage_pre: U,
     383            0 :     tenant_manager: &Arc<TenantManager>,
     384            0 :     eviction_order: EvictionOrder,
     385            0 :     cancel: &CancellationToken,
     386            0 : ) -> anyhow::Result<IterationOutcome<U>> {
     387              :     // use tokio's mutex to get a Sync guard (instead of std::sync::Mutex)
     388            0 :     let _g = state
     389            0 :         .mutex
     390            0 :         .try_lock()
     391            0 :         .map_err(|_| anyhow::anyhow!("iteration is already executing"))?;
     392              : 
     393            0 :     debug!(?usage_pre, "disk usage");
     394              : 
     395            0 :     if !usage_pre.has_pressure() {
     396            0 :         return Ok(IterationOutcome::NoPressure);
     397            0 :     }
     398            0 : 
     399            0 :     warn!(
     400              :         ?usage_pre,
     401            0 :         "running disk usage based eviction due to pressure"
     402              :     );
     403              : 
     404            0 :     let (candidates, collection_time) = {
     405            0 :         let started_at = std::time::Instant::now();
     406            0 :         match collect_eviction_candidates(tenant_manager, eviction_order, cancel).await? {
     407              :             EvictionCandidates::Cancelled => {
     408            0 :                 return Ok(IterationOutcome::Cancelled);
     409              :             }
     410            0 :             EvictionCandidates::Finished(partitioned) => (partitioned, started_at.elapsed()),
     411            0 :         }
     412            0 :     };
     413            0 : 
     414            0 :     METRICS.layers_collected.inc_by(candidates.len() as u64);
     415            0 : 
     416            0 :     tracing::info!(
     417            0 :         elapsed_ms = collection_time.as_millis(),
     418            0 :         total_layers = candidates.len(),
     419            0 :         "collection completed"
     420              :     );
     421              : 
     422              :     // Debug-log the list of candidates
     423            0 :     let now = SystemTime::now();
     424            0 :     for (i, (partition, candidate)) in candidates.iter().enumerate() {
     425            0 :         let nth = i + 1;
     426            0 :         let total_candidates = candidates.len();
     427            0 :         let size = candidate.layer.get_file_size();
     428            0 :         let rel = candidate.relative_last_activity;
     429            0 :         debug!(
     430            0 :             "cand {nth}/{total_candidates}: size={size}, rel_last_activity={rel}, no_access_for={}us, partition={partition:?}, {}/{}/{}",
     431            0 :             now.duration_since(candidate.last_activity_ts)
     432            0 :                 .unwrap()
     433            0 :                 .as_micros(),
     434            0 :             candidate.layer.get_tenant_shard_id(),
     435            0 :             candidate.layer.get_timeline_id(),
     436            0 :             candidate.layer.get_name(),
     437              :         );
     438              :     }
     439              : 
     440              :     // phase1: select victims to relieve pressure
     441              :     //
     442              :     // Walk through the list of candidates, until we have accumulated enough layers to get
     443              :     // us back under the pressure threshold. 'usage_planned' is updated so that it tracks
     444              :     // how much disk space would be used after evicting all the layers up to the current
     445              :     // point in the list.
     446              :     //
     447              :     // If we get far enough in the list that we start to evict layers that are below
     448              :     // the tenant's min-resident-size threshold, print a warning, and memorize the disk
     449              :     // usage at that point, in 'usage_planned_min_resident_size_respecting'.
     450              : 
     451            0 :     let (evicted_amount, usage_planned) =
     452            0 :         select_victims(&candidates, usage_pre).into_amount_and_planned();
     453            0 : 
     454            0 :     METRICS.layers_selected.inc_by(evicted_amount as u64);
     455            0 : 
     456            0 :     // phase2: evict layers
     457            0 : 
     458            0 :     let mut js = tokio::task::JoinSet::new();
     459            0 :     let limit = 1000;
     460            0 : 
     461            0 :     let mut evicted = candidates.into_iter().take(evicted_amount).fuse();
     462            0 :     let mut consumed_all = false;
     463            0 : 
     464            0 :     // After the evictions, `usage_assumed` is the post-eviction usage,
     465            0 :     // according to internal accounting.
     466            0 :     let mut usage_assumed = usage_pre;
     467            0 :     let mut evictions_failed = LayerCount::default();
     468            0 : 
     469            0 :     let evict_layers = async move {
     470              :         loop {
     471            0 :             let next = if js.len() >= limit || consumed_all {
     472            0 :                 js.join_next().await
     473            0 :             } else if !js.is_empty() {
     474              :                 // opportunistically consume ready result, one per each new evicted
     475            0 :                 futures::future::FutureExt::now_or_never(js.join_next()).and_then(|x| x)
     476              :             } else {
     477            0 :                 None
     478              :             };
     479              : 
     480            0 :             if let Some(next) = next {
     481            0 :                 match next {
     482            0 :                     Ok(Ok(file_size)) => {
     483            0 :                         METRICS.layers_evicted.inc();
     484            0 :                         usage_assumed.add_available_bytes(file_size);
     485            0 :                     }
     486              :                     Ok(Err((
     487            0 :                         file_size,
     488            0 :                         EvictionError::NotFound
     489            0 :                         | EvictionError::Downloaded
     490            0 :                         | EvictionError::Timeout,
     491            0 :                     ))) => {
     492            0 :                         evictions_failed.file_sizes += file_size;
     493            0 :                         evictions_failed.count += 1;
     494            0 :                     }
     495            0 :                     Err(je) if je.is_cancelled() => unreachable!("not used"),
     496            0 :                     Err(je) if je.is_panic() => { /* already logged */ }
     497            0 :                     Err(je) => tracing::error!("unknown JoinError: {je:?}"),
     498              :                 }
     499            0 :             }
     500              : 
     501            0 :             if consumed_all && js.is_empty() {
     502            0 :                 break;
     503            0 :             }
     504              : 
     505              :             // calling again when consumed_all is fine as evicted is fused.
     506            0 :             let Some((_partition, candidate)) = evicted.next() else {
     507            0 :                 if !consumed_all {
     508            0 :                     tracing::info!("all evictions started, waiting");
     509            0 :                     consumed_all = true;
     510            0 :                 }
     511            0 :                 continue;
     512              :             };
     513              : 
     514            0 :             match candidate.layer {
     515            0 :                 EvictionLayer::Attached(layer) => {
     516            0 :                     let file_size = layer.layer_desc().file_size;
     517            0 :                     js.spawn(async move {
     518            0 :                         // have a low eviction waiting timeout because our LRU calculations go stale fast;
     519            0 :                         // also individual layer evictions could hang because of bugs and we do not want to
     520            0 :                         // pause disk_usage_based_eviction for such.
     521            0 :                         let timeout = std::time::Duration::from_secs(5);
     522            0 : 
     523            0 :                         match layer.evict_and_wait(timeout).await {
     524            0 :                             Ok(()) => Ok(file_size),
     525            0 :                             Err(e) => Err((file_size, e)),
     526              :                         }
     527            0 :                     });
     528            0 :                 }
     529            0 :                 EvictionLayer::Secondary(layer) => {
     530            0 :                     let file_size = layer.metadata.file_size;
     531            0 : 
     532            0 :                     js.spawn(async move {
     533            0 :                         layer
     534            0 :                             .secondary_tenant
     535            0 :                             .evict_layer(layer.timeline_id, layer.name)
     536            0 :                             .await;
     537            0 :                         Ok(file_size)
     538            0 :                     });
     539            0 :                 }
     540              :             }
     541            0 :             tokio::task::yield_now().await;
     542              :         }
     543              : 
     544            0 :         (usage_assumed, evictions_failed)
     545            0 :     };
     546              : 
     547            0 :     let started_at = std::time::Instant::now();
     548            0 : 
     549            0 :     let evict_layers = async move {
     550            0 :         let mut evict_layers = std::pin::pin!(evict_layers);
     551            0 : 
     552            0 :         let maximum_expected = std::time::Duration::from_secs(10);
     553              : 
     554            0 :         let res = tokio::time::timeout(maximum_expected, &mut evict_layers).await;
     555            0 :         let tuple = if let Ok(tuple) = res {
     556            0 :             tuple
     557              :         } else {
     558            0 :             let elapsed = started_at.elapsed();
     559            0 :             tracing::info!(elapsed_ms = elapsed.as_millis(), "still ongoing");
     560            0 :             evict_layers.await
     561              :         };
     562              : 
     563            0 :         let elapsed = started_at.elapsed();
     564            0 :         tracing::info!(elapsed_ms = elapsed.as_millis(), "completed");
     565            0 :         tuple
     566            0 :     };
     567              : 
     568            0 :     let evict_layers =
     569            0 :         evict_layers.instrument(tracing::info_span!("evict_layers", layers=%evicted_amount));
     570              : 
     571            0 :     let (usage_assumed, evictions_failed) = tokio::select! {
     572              :         tuple = evict_layers => { tuple },
     573              :         _ = cancel.cancelled() => {
     574              :             // dropping joinset will abort all pending evict_and_waits and that is fine, our
     575              :             // requests will still stand
     576              :             return Ok(IterationOutcome::Cancelled);
     577              :         }
     578              :     };
     579              : 
     580            0 :     Ok(IterationOutcome::Finished(IterationOutcomeFinished {
     581            0 :         before: usage_pre,
     582            0 :         planned: usage_planned,
     583            0 :         assumed: AssumedUsage {
     584            0 :             projected_after: usage_assumed,
     585            0 :             failed: evictions_failed,
     586            0 :         },
     587            0 :     }))
     588            0 : }
     589              : 
     590              : #[derive(Clone)]
     591              : pub(crate) struct EvictionSecondaryLayer {
     592              :     pub(crate) secondary_tenant: Arc<SecondaryTenant>,
     593              :     pub(crate) timeline_id: TimelineId,
     594              :     pub(crate) name: LayerName,
     595              :     pub(crate) metadata: LayerFileMetadata,
     596              : }
     597              : 
     598              : /// Full [`Layer`] objects are specific to tenants in attached mode.  This type is a layer
     599              : /// of indirection to store either a `Layer`, or a reference to a secondary tenant and a layer name.
     600              : #[derive(Clone)]
     601              : pub(crate) enum EvictionLayer {
     602              :     Attached(Layer),
     603              :     Secondary(EvictionSecondaryLayer),
     604              : }
     605              : 
     606              : impl From<Layer> for EvictionLayer {
     607            0 :     fn from(value: Layer) -> Self {
     608            0 :         Self::Attached(value)
     609            0 :     }
     610              : }
     611              : 
     612              : impl EvictionLayer {
     613            0 :     pub(crate) fn get_tenant_shard_id(&self) -> &TenantShardId {
     614            0 :         match self {
     615            0 :             Self::Attached(l) => &l.layer_desc().tenant_shard_id,
     616            0 :             Self::Secondary(sl) => sl.secondary_tenant.get_tenant_shard_id(),
     617              :         }
     618            0 :     }
     619              : 
     620            0 :     pub(crate) fn get_timeline_id(&self) -> &TimelineId {
     621            0 :         match self {
     622            0 :             Self::Attached(l) => &l.layer_desc().timeline_id,
     623            0 :             Self::Secondary(sl) => &sl.timeline_id,
     624              :         }
     625            0 :     }
     626              : 
     627            0 :     pub(crate) fn get_name(&self) -> LayerName {
     628            0 :         match self {
     629            0 :             Self::Attached(l) => l.layer_desc().layer_name(),
     630            0 :             Self::Secondary(sl) => sl.name.clone(),
     631              :         }
     632            0 :     }
     633              : 
     634            0 :     pub(crate) fn get_file_size(&self) -> u64 {
     635            0 :         match self {
     636            0 :             Self::Attached(l) => l.layer_desc().file_size,
     637            0 :             Self::Secondary(sl) => sl.metadata.file_size,
     638              :         }
     639            0 :     }
     640              : }
     641              : 
     642              : #[derive(Clone)]
     643              : pub(crate) struct EvictionCandidate {
     644              :     pub(crate) layer: EvictionLayer,
     645              :     pub(crate) last_activity_ts: SystemTime,
     646              :     pub(crate) relative_last_activity: finite_f32::FiniteF32,
     647              :     pub(crate) visibility: LayerVisibilityHint,
     648              : }
     649              : 
     650              : impl std::fmt::Display for EvictionLayer {
     651            0 :     fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
     652            0 :         match self {
     653            0 :             Self::Attached(l) => l.fmt(f),
     654            0 :             Self::Secondary(sl) => {
     655            0 :                 write!(f, "{}/{}", sl.timeline_id, sl.name)
     656              :             }
     657              :         }
     658            0 :     }
     659              : }
     660              : 
     661              : #[derive(Default)]
     662              : pub(crate) struct DiskUsageEvictionInfo {
     663              :     /// Timeline's largest layer (remote or resident)
     664              :     pub max_layer_size: Option<u64>,
     665              :     /// Timeline's resident layers
     666              :     pub resident_layers: Vec<EvictionCandidate>,
     667              : }
     668              : 
     669              : impl std::fmt::Debug for EvictionCandidate {
     670            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     671            0 :         // format the tv_sec, tv_nsec into rfc3339 in case someone is looking at it
     672            0 :         // having to allocate a string to this is bad, but it will rarely be formatted
     673            0 :         let ts = chrono::DateTime::<chrono::Utc>::from(self.last_activity_ts);
     674            0 :         let ts = ts.to_rfc3339_opts(chrono::SecondsFormat::Nanos, true);
     675            0 :         struct DisplayIsDebug<'a, T>(&'a T);
     676            0 :         impl<'a, T: std::fmt::Display> std::fmt::Debug for DisplayIsDebug<'a, T> {
     677            0 :             fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     678            0 :                 write!(f, "{}", self.0)
     679            0 :             }
     680            0 :         }
     681            0 :         f.debug_struct("LocalLayerInfoForDiskUsageEviction")
     682            0 :             .field("layer", &DisplayIsDebug(&self.layer))
     683            0 :             .field("last_activity", &ts)
     684            0 :             .finish()
     685            0 :     }
     686              : }
     687              : 
     688              : #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
     689              : enum EvictionPartition {
     690              :     // A layer that is un-wanted by the tenant: evict all these first, before considering
     691              :     // any other layers
     692              :     EvictNow,
     693              : 
     694              :     // Above the minimum size threshold: this layer is a candidate for eviction.
     695              :     Above,
     696              : 
     697              :     // Below the minimum size threshold: this layer should only be evicted if all the
     698              :     // tenants' layers above the minimum size threshold have already been considered.
     699              :     Below,
     700              : }
     701              : 
     702              : enum EvictionCandidates {
     703              :     Cancelled,
     704              :     Finished(Vec<(EvictionPartition, EvictionCandidate)>),
     705              : }
     706              : 
     707              : /// Gather the eviction candidates.
     708              : ///
     709              : /// The returned `Ok(EvictionCandidates::Finished(candidates))` is sorted in eviction
     710              : /// order. A caller that evicts in that order, until pressure is relieved, implements
     711              : /// the eviction policy outlined in the module comment.
     712              : ///
     713              : /// # Example with EvictionOrder::AbsoluteAccessed
     714              : ///
     715              : /// Imagine that there are two tenants, A and B, with five layers each, a-e.
     716              : /// Each layer has size 100, and both tenant's min_resident_size is 150.
     717              : /// The eviction order would be
     718              : ///
     719              : /// ```text
     720              : /// partition last_activity_ts tenant/layer
     721              : /// Above     18:30            A/c
     722              : /// Above     19:00            A/b
     723              : /// Above     18:29            B/c
     724              : /// Above     19:05            B/b
     725              : /// Above     20:00            B/a
     726              : /// Above     20:03            A/a
     727              : /// Below     20:30            A/d
     728              : /// Below     20:40            B/d
     729              : /// Below     20:45            B/e
     730              : /// Below     20:58            A/e
     731              : /// ```
     732              : ///
     733              : /// Now, if we need to evict 300 bytes to relieve pressure, we'd evict `A/c, A/b, B/c`.
     734              : /// They are all in the `Above` partition, so, we respected each tenant's min_resident_size.
     735              : ///
     736              : /// But, if we need to evict 900 bytes to relieve pressure, we'd evict
     737              : /// `A/c, A/b, B/c, B/b, B/a, A/a, A/d, B/d, B/e`, reaching into the `Below` partition
     738              : /// after exhauting the `Above` partition.
     739              : /// So, we did not respect each tenant's min_resident_size.
     740              : ///
     741              : /// # Example with EvictionOrder::RelativeAccessed
     742              : ///
     743              : /// ```text
     744              : /// partition relative_age last_activity_ts tenant/layer
     745              : /// Above     0/4          18:30            A/c
     746              : /// Above     0/4          18:29            B/c
     747              : /// Above     1/4          19:00            A/b
     748              : /// Above     1/4          19:05            B/b
     749              : /// Above     2/4          20:00            B/a
     750              : /// Above     2/4          20:03            A/a
     751              : /// Below     3/4          20:30            A/d
     752              : /// Below     3/4          20:40            B/d
     753              : /// Below     4/4          20:45            B/e
     754              : /// Below     4/4          20:58            A/e
     755              : /// ```
     756              : ///
     757              : /// With tenants having the same number of layers the picture does not change much. The same with
     758              : /// A having many more layers **resident** (not all of them listed):
     759              : ///
     760              : /// ```text
     761              : /// Above       0/100      18:30            A/c
     762              : /// Above       0/4        18:29            B/c
     763              : /// Above       1/100      19:00            A/b
     764              : /// Above       2/100      20:03            A/a
     765              : /// Above       3/100      20:03            A/nth_3
     766              : /// Above       4/100      20:03            A/nth_4
     767              : ///             ...
     768              : /// Above       1/4        19:05            B/b
     769              : /// Above      25/100      20:04            A/nth_25
     770              : ///             ...
     771              : /// Above       2/4        20:00            B/a
     772              : /// Above      50/100      20:10            A/nth_50
     773              : ///             ...
     774              : /// Below       3/4        20:40            B/d
     775              : /// Below      99/100      20:30            A/nth_99
     776              : /// Below       4/4        20:45            B/e
     777              : /// Below     100/100      20:58            A/nth_100
     778              : /// ```
     779              : ///
     780              : /// Now it's easier to see that because A has grown fast it has more layers to get evicted. What is
     781              : /// difficult to see is what happens on the next round assuming the evicting 23 from the above list
     782              : /// relieves the pressure (22 A layers gone, 1 B layers gone) but a new fast growing tenant C has
     783              : /// appeared:
     784              : ///
     785              : /// ```text
     786              : /// Above       0/87       20:04            A/nth_23
     787              : /// Above       0/3        19:05            B/b
     788              : /// Above       0/50       20:59            C/nth_0
     789              : /// Above       1/87       20:04            A/nth_24
     790              : /// Above       1/50       21:00            C/nth_1
     791              : /// Above       2/87       20:04            A/nth_25
     792              : ///             ...
     793              : /// Above      16/50       21:02            C/nth_16
     794              : /// Above       1/3        20:00            B/a
     795              : /// Above      27/87       20:10            A/nth_50
     796              : ///             ...
     797              : /// Below       2/3        20:40            B/d
     798              : /// Below      49/50       21:05            C/nth_49
     799              : /// Below      86/87       20:30            A/nth_99
     800              : /// Below       3/3        20:45            B/e
     801              : /// Below      50/50       21:05            C/nth_50
     802              : /// Below      87/87       20:58            A/nth_100
     803              : /// ```
     804              : ///
     805              : /// Now relieving pressure with 23 layers would cost:
     806              : /// - tenant A 14 layers
     807              : /// - tenant B 1 layer
     808              : /// - tenant C 8 layers
     809            0 : async fn collect_eviction_candidates(
     810            0 :     tenant_manager: &Arc<TenantManager>,
     811            0 :     eviction_order: EvictionOrder,
     812            0 :     cancel: &CancellationToken,
     813            0 : ) -> anyhow::Result<EvictionCandidates> {
     814              :     const LOG_DURATION_THRESHOLD: std::time::Duration = std::time::Duration::from_secs(10);
     815              : 
     816              :     // get a snapshot of the list of tenants
     817            0 :     let tenants = tenant_manager
     818            0 :         .list_tenants()
     819            0 :         .context("get list of tenants")?;
     820              : 
     821              :     // TODO: avoid listing every layer in every tenant: this loop can block the executor,
     822              :     // and the resulting data structure can be huge.
     823              :     // (https://github.com/neondatabase/neon/issues/6224)
     824            0 :     let mut candidates = Vec::new();
     825              : 
     826            0 :     for (tenant_id, _state, _gen) in tenants {
     827            0 :         if cancel.is_cancelled() {
     828            0 :             return Ok(EvictionCandidates::Cancelled);
     829            0 :         }
     830            0 :         let tenant = match tenant_manager.get_attached_tenant_shard(tenant_id) {
     831            0 :             Ok(tenant) if tenant.is_active() => tenant,
     832              :             Ok(_) => {
     833            0 :                 debug!(tenant_id=%tenant_id.tenant_id, shard_id=%tenant_id.shard_slug(), "Tenant shard is not active");
     834            0 :                 continue;
     835              :             }
     836            0 :             Err(e) => {
     837            0 :                 // this can happen if tenant has lifecycle transition after we fetched it
     838            0 :                 debug!("failed to get tenant: {e:#}");
     839            0 :                 continue;
     840              :             }
     841              :         };
     842              : 
     843            0 :         if tenant.cancel.is_cancelled() {
     844            0 :             info!(%tenant_id, "Skipping tenant for eviction, it is shutting down");
     845            0 :             continue;
     846            0 :         }
     847            0 : 
     848            0 :         let started_at = std::time::Instant::now();
     849            0 : 
     850            0 :         // collect layers from all timelines in this tenant
     851            0 :         //
     852            0 :         // If one of the timelines becomes `!is_active()` during the iteration,
     853            0 :         // for example because we're shutting down, then `max_layer_size` can be too small.
     854            0 :         // That's OK. This code only runs under a disk pressure situation, and being
     855            0 :         // a little unfair to tenants during shutdown in such a situation is tolerable.
     856            0 :         let mut tenant_candidates = Vec::new();
     857            0 :         let mut max_layer_size = 0;
     858            0 :         for tl in tenant.list_timelines() {
     859            0 :             if !tl.is_active() {
     860            0 :                 continue;
     861            0 :             }
     862            0 :             let info = tl.get_local_layers_for_disk_usage_eviction().await;
     863            0 :             debug!(tenant_id=%tl.tenant_shard_id.tenant_id, shard_id=%tl.tenant_shard_id.shard_slug(), timeline_id=%tl.timeline_id, "timeline resident layers count: {}", info.resident_layers.len());
     864              : 
     865            0 :             tenant_candidates.extend(info.resident_layers.into_iter());
     866            0 :             max_layer_size = max_layer_size.max(info.max_layer_size.unwrap_or(0));
     867            0 : 
     868            0 :             if cancel.is_cancelled() {
     869            0 :                 return Ok(EvictionCandidates::Cancelled);
     870            0 :             }
     871              :         }
     872              : 
     873              :         // `min_resident_size` defaults to maximum layer file size of the tenant.
     874              :         // This ensures that each tenant can have at least one layer resident at a given time,
     875              :         // ensuring forward progress for a single Timeline::get in that tenant.
     876              :         // It's a questionable heuristic since, usually, there are many Timeline::get
     877              :         // requests going on for a tenant, and, at least in Neon prod, the median
     878              :         // layer file size is much smaller than the compaction target size.
     879              :         // We could be better here, e.g., sum of all L0 layers + most recent L1 layer.
     880              :         // That's what's typically used by the various background loops.
     881              :         //
     882              :         // The default can be overridden with a fixed value in the tenant conf.
     883              :         // A default override can be put in the default tenant conf in the pageserver.toml.
     884            0 :         let min_resident_size = if let Some(s) = tenant.get_min_resident_size_override() {
     885            0 :             debug!(
     886            0 :                 tenant_id=%tenant.tenant_shard_id().tenant_id,
     887            0 :                 shard_id=%tenant.tenant_shard_id().shard_slug(),
     888            0 :                 overridden_size=s,
     889            0 :                 "using overridden min resident size for tenant"
     890              :             );
     891            0 :             s
     892              :         } else {
     893            0 :             debug!(
     894            0 :                 tenant_id=%tenant.tenant_shard_id().tenant_id,
     895            0 :                 shard_id=%tenant.tenant_shard_id().shard_slug(),
     896            0 :                 max_layer_size,
     897            0 :                 "using max layer size as min_resident_size for tenant",
     898              :             );
     899            0 :             max_layer_size
     900              :         };
     901              : 
     902              :         // Sort layers most-recently-used first, then calculate [`EvictionPartition`] for each layer,
     903              :         // where the inputs are:
     904              :         //  - whether the layer is visible
     905              :         //  - whether the layer is above/below the min_resident_size cutline
     906            0 :         tenant_candidates
     907            0 :             .sort_unstable_by_key(|layer_info| std::cmp::Reverse(layer_info.last_activity_ts));
     908            0 :         let mut cumsum: i128 = 0;
     909            0 : 
     910            0 :         let total = tenant_candidates.len();
     911            0 : 
     912            0 :         let tenant_candidates =
     913            0 :             tenant_candidates
     914            0 :                 .into_iter()
     915            0 :                 .enumerate()
     916            0 :                 .map(|(i, mut candidate)| {
     917            0 :                     // as we iterate this reverse sorted list, the most recently accessed layer will always
     918            0 :                     // be 1.0; this is for us to evict it last.
     919            0 :                     candidate.relative_last_activity =
     920            0 :                         eviction_order.relative_last_activity(total, i);
     921              : 
     922            0 :                     let partition = match candidate.visibility {
     923              :                         LayerVisibilityHint::Covered => {
     924              :                             // Covered layers are evicted first
     925            0 :                             EvictionPartition::EvictNow
     926              :                         }
     927              :                         LayerVisibilityHint::Visible => {
     928            0 :                             cumsum += i128::from(candidate.layer.get_file_size());
     929            0 : 
     930            0 :                             if cumsum > min_resident_size as i128 {
     931            0 :                                 EvictionPartition::Above
     932              :                             } else {
     933              :                                 // The most recent layers below the min_resident_size threshold
     934              :                                 // are the last to be evicted.
     935            0 :                                 EvictionPartition::Below
     936              :                             }
     937              :                         }
     938              :                     };
     939              : 
     940            0 :                     (partition, candidate)
     941            0 :                 });
     942            0 : 
     943            0 :         METRICS
     944            0 :             .tenant_layer_count
     945            0 :             .observe(tenant_candidates.len() as f64);
     946            0 : 
     947            0 :         candidates.extend(tenant_candidates);
     948            0 : 
     949            0 :         let elapsed = started_at.elapsed();
     950            0 :         METRICS
     951            0 :             .tenant_collection_time
     952            0 :             .observe(elapsed.as_secs_f64());
     953            0 : 
     954            0 :         if elapsed > LOG_DURATION_THRESHOLD {
     955            0 :             tracing::info!(
     956            0 :                 tenant_id=%tenant.tenant_shard_id().tenant_id,
     957            0 :                 shard_id=%tenant.tenant_shard_id().shard_slug(),
     958            0 :                 elapsed_ms = elapsed.as_millis(),
     959            0 :                 "collection took longer than threshold"
     960              :             );
     961            0 :         }
     962              :     }
     963              : 
     964              :     // Note: the same tenant ID might be hit twice, if it transitions from attached to
     965              :     // secondary while we run.  That is okay: when we eventually try and run the eviction,
     966              :     // the `Gate` on the object will ensure that whichever one has already been shut down
     967              :     // will not delete anything.
     968              : 
     969            0 :     let mut secondary_tenants = Vec::new();
     970            0 :     tenant_manager.foreach_secondary_tenants(
     971            0 :         |_tenant_shard_id: &TenantShardId, state: &Arc<SecondaryTenant>| {
     972            0 :             secondary_tenants.push(state.clone());
     973            0 :         },
     974            0 :     );
     975              : 
     976            0 :     for tenant in secondary_tenants {
     977              :         // for secondary tenants we use a sum of on_disk layers and already evicted layers. this is
     978              :         // to prevent repeated disk usage based evictions from completely draining less often
     979              :         // updating secondaries.
     980            0 :         let (mut layer_info, total_layers) = tenant.get_layers_for_eviction();
     981            0 : 
     982            0 :         debug_assert!(
     983            0 :             total_layers >= layer_info.resident_layers.len(),
     984            0 :             "total_layers ({total_layers}) must be at least the resident_layers.len() ({})",
     985            0 :             layer_info.resident_layers.len()
     986              :         );
     987              : 
     988            0 :         let started_at = std::time::Instant::now();
     989            0 : 
     990            0 :         layer_info
     991            0 :             .resident_layers
     992            0 :             .sort_unstable_by_key(|layer_info| std::cmp::Reverse(layer_info.last_activity_ts));
     993            0 : 
     994            0 :         let tenant_candidates =
     995            0 :             layer_info
     996            0 :                 .resident_layers
     997            0 :                 .into_iter()
     998            0 :                 .enumerate()
     999            0 :                 .map(|(i, mut candidate)| {
    1000            0 :                     candidate.relative_last_activity =
    1001            0 :                         eviction_order.relative_last_activity(total_layers, i);
    1002            0 :                     (
    1003            0 :                         // Secondary locations' layers are always considered above the min resident size,
    1004            0 :                         // i.e. secondary locations are permitted to be trimmed to zero layers if all
    1005            0 :                         // the layers have sufficiently old access times.
    1006            0 :                         EvictionPartition::Above,
    1007            0 :                         candidate,
    1008            0 :                     )
    1009            0 :                 });
    1010            0 : 
    1011            0 :         METRICS
    1012            0 :             .tenant_layer_count
    1013            0 :             .observe(tenant_candidates.len() as f64);
    1014            0 :         candidates.extend(tenant_candidates);
    1015            0 : 
    1016            0 :         tokio::task::yield_now().await;
    1017              : 
    1018            0 :         let elapsed = started_at.elapsed();
    1019            0 : 
    1020            0 :         METRICS
    1021            0 :             .tenant_collection_time
    1022            0 :             .observe(elapsed.as_secs_f64());
    1023            0 : 
    1024            0 :         if elapsed > LOG_DURATION_THRESHOLD {
    1025            0 :             tracing::info!(
    1026            0 :                 tenant_id=%tenant.tenant_shard_id().tenant_id,
    1027            0 :                 shard_id=%tenant.tenant_shard_id().shard_slug(),
    1028            0 :                 elapsed_ms = elapsed.as_millis(),
    1029            0 :                 "collection took longer than threshold"
    1030              :             );
    1031            0 :         }
    1032              :     }
    1033              : 
    1034            0 :     debug_assert!(EvictionPartition::Above < EvictionPartition::Below,
    1035            0 :         "as explained in the function's doc comment, layers that aren't in the tenant's min_resident_size are evicted first");
    1036            0 :     debug_assert!(EvictionPartition::EvictNow < EvictionPartition::Above,
    1037            0 :         "as explained in the function's doc comment, layers that aren't in the tenant's min_resident_size are evicted first");
    1038              : 
    1039            0 :     eviction_order.sort(&mut candidates);
    1040            0 : 
    1041            0 :     Ok(EvictionCandidates::Finished(candidates))
    1042            0 : }
    1043              : 
    1044              : /// Given a pre-sorted vec of all layers in the system, select the first N which are enough to
    1045              : /// relieve pressure.
    1046              : ///
    1047              : /// Returns the amount of candidates selected, with the planned usage.
    1048            0 : fn select_victims<U: Usage>(
    1049            0 :     candidates: &[(EvictionPartition, EvictionCandidate)],
    1050            0 :     usage_pre: U,
    1051            0 : ) -> VictimSelection<U> {
    1052            0 :     let mut usage_when_switched = None;
    1053            0 :     let mut usage_planned = usage_pre;
    1054            0 :     let mut evicted_amount = 0;
    1055              : 
    1056            0 :     for (i, (partition, candidate)) in candidates.iter().enumerate() {
    1057            0 :         if !usage_planned.has_pressure() {
    1058            0 :             break;
    1059            0 :         }
    1060            0 : 
    1061            0 :         if partition == &EvictionPartition::Below && usage_when_switched.is_none() {
    1062            0 :             usage_when_switched = Some((usage_planned, i));
    1063            0 :         }
    1064              : 
    1065            0 :         usage_planned.add_available_bytes(candidate.layer.get_file_size());
    1066            0 :         evicted_amount += 1;
    1067              :     }
    1068              : 
    1069            0 :     VictimSelection {
    1070            0 :         amount: evicted_amount,
    1071            0 :         usage_pre,
    1072            0 :         usage_when_switched,
    1073            0 :         usage_planned,
    1074            0 :     }
    1075            0 : }
    1076              : 
    1077              : struct VictimSelection<U> {
    1078              :     amount: usize,
    1079              :     usage_pre: U,
    1080              :     usage_when_switched: Option<(U, usize)>,
    1081              :     usage_planned: U,
    1082              : }
    1083              : 
    1084              : impl<U: Usage> VictimSelection<U> {
    1085            0 :     fn into_amount_and_planned(self) -> (usize, PlannedUsage<U>) {
    1086            0 :         debug!(
    1087              :             evicted_amount=%self.amount,
    1088            0 :             "took enough candidates for pressure to be relieved"
    1089              :         );
    1090              : 
    1091            0 :         if let Some((usage_planned, candidate_no)) = self.usage_when_switched.as_ref() {
    1092            0 :             warn!(usage_pre=?self.usage_pre, ?usage_planned, candidate_no, "tenant_min_resident_size-respecting LRU would not relieve pressure, evicting more following global LRU policy");
    1093            0 :         }
    1094              : 
    1095            0 :         let planned = match self.usage_when_switched {
    1096            0 :             Some((respecting_tenant_min_resident_size, _)) => PlannedUsage {
    1097            0 :                 respecting_tenant_min_resident_size,
    1098            0 :                 fallback_to_global_lru: Some(self.usage_planned),
    1099            0 :             },
    1100            0 :             None => PlannedUsage {
    1101            0 :                 respecting_tenant_min_resident_size: self.usage_planned,
    1102            0 :                 fallback_to_global_lru: None,
    1103            0 :             },
    1104              :         };
    1105              : 
    1106            0 :         (self.amount, planned)
    1107            0 :     }
    1108              : }
    1109              : 
    1110              : /// A totally ordered f32 subset we can use with sorting functions.
    1111              : pub(crate) mod finite_f32 {
    1112              : 
    1113              :     /// A totally ordered f32 subset we can use with sorting functions.
    1114              :     #[derive(Clone, Copy, PartialEq)]
    1115              :     pub struct FiniteF32(f32);
    1116              : 
    1117              :     impl std::fmt::Debug for FiniteF32 {
    1118            0 :         fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    1119            0 :             std::fmt::Debug::fmt(&self.0, f)
    1120            0 :         }
    1121              :     }
    1122              : 
    1123              :     impl std::fmt::Display for FiniteF32 {
    1124            0 :         fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    1125            0 :             std::fmt::Display::fmt(&self.0, f)
    1126            0 :         }
    1127              :     }
    1128              : 
    1129              :     impl std::cmp::Eq for FiniteF32 {}
    1130              : 
    1131              :     impl std::cmp::PartialOrd for FiniteF32 {
    1132            0 :         fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
    1133            0 :             Some(self.cmp(other))
    1134            0 :         }
    1135              :     }
    1136              : 
    1137              :     impl std::cmp::Ord for FiniteF32 {
    1138            0 :         fn cmp(&self, other: &Self) -> std::cmp::Ordering {
    1139            0 :             self.0.total_cmp(&other.0)
    1140            0 :         }
    1141              :     }
    1142              : 
    1143              :     impl TryFrom<f32> for FiniteF32 {
    1144              :         type Error = f32;
    1145              : 
    1146            0 :         fn try_from(value: f32) -> Result<Self, Self::Error> {
    1147            0 :             if value.is_finite() {
    1148            0 :                 Ok(FiniteF32(value))
    1149              :             } else {
    1150            0 :                 Err(value)
    1151              :             }
    1152            0 :         }
    1153              :     }
    1154              : 
    1155              :     impl From<FiniteF32> for f32 {
    1156           40 :         fn from(value: FiniteF32) -> f32 {
    1157           40 :             value.0
    1158           40 :         }
    1159              :     }
    1160              : 
    1161              :     impl FiniteF32 {
    1162              :         pub const ZERO: FiniteF32 = FiniteF32(0.0);
    1163              : 
    1164           40 :         pub fn try_from_normalized(value: f32) -> Result<Self, f32> {
    1165           40 :             if (0.0..=1.0).contains(&value) {
    1166              :                 // -0.0 is within the range, make sure it is assumed 0.0..=1.0
    1167           40 :                 let value = value.abs();
    1168           40 :                 Ok(FiniteF32(value))
    1169              :             } else {
    1170            0 :                 Err(value)
    1171              :             }
    1172           40 :         }
    1173              : 
    1174           40 :         pub fn into_inner(self) -> f32 {
    1175           40 :             self.into()
    1176           40 :         }
    1177              :     }
    1178              : }
    1179              : 
    1180              : mod filesystem_level_usage {
    1181              :     use anyhow::Context;
    1182              :     use camino::Utf8Path;
    1183              : 
    1184              :     use crate::statvfs::Statvfs;
    1185              : 
    1186              :     use super::DiskUsageEvictionTaskConfig;
    1187              : 
    1188              :     #[derive(Debug, Clone, Copy)]
    1189              :     pub struct Usage<'a> {
    1190              :         config: &'a DiskUsageEvictionTaskConfig,
    1191              : 
    1192              :         /// Filesystem capacity
    1193              :         total_bytes: u64,
    1194              :         /// Free filesystem space
    1195              :         avail_bytes: u64,
    1196              :     }
    1197              : 
    1198              :     impl super::Usage for Usage<'_> {
    1199           14 :         fn has_pressure(&self) -> bool {
    1200           14 :             let usage_pct =
    1201           14 :                 (100.0 * (1.0 - ((self.avail_bytes as f64) / (self.total_bytes as f64)))) as u64;
    1202           14 : 
    1203           14 :             let pressures = [
    1204           14 :                 (
    1205           14 :                     "min_avail_bytes",
    1206           14 :                     self.avail_bytes < self.config.min_avail_bytes,
    1207           14 :                 ),
    1208           14 :                 (
    1209           14 :                     "max_usage_pct",
    1210           14 :                     usage_pct >= self.config.max_usage_pct.get() as u64,
    1211           14 :                 ),
    1212           14 :             ];
    1213           14 : 
    1214           28 :             pressures.into_iter().any(|(_, has_pressure)| has_pressure)
    1215           14 :         }
    1216              : 
    1217           12 :         fn add_available_bytes(&mut self, bytes: u64) {
    1218           12 :             self.avail_bytes += bytes;
    1219           12 :         }
    1220              :     }
    1221              : 
    1222            0 :     pub fn get<'a>(
    1223            0 :         tenants_dir: &Utf8Path,
    1224            0 :         config: &'a DiskUsageEvictionTaskConfig,
    1225            0 :     ) -> anyhow::Result<Usage<'a>> {
    1226            0 :         let mock_config = {
    1227            0 :             #[cfg(feature = "testing")]
    1228            0 :             {
    1229            0 :                 config.mock_statvfs.as_ref()
    1230              :             }
    1231              :             #[cfg(not(feature = "testing"))]
    1232              :             {
    1233              :                 None
    1234              :             }
    1235              :         };
    1236              : 
    1237            0 :         let stat = Statvfs::get(tenants_dir, mock_config)
    1238            0 :             .context("statvfs failed, presumably directory got unlinked")?;
    1239              : 
    1240              :         // https://unix.stackexchange.com/a/703650
    1241            0 :         let blocksize = if stat.fragment_size() > 0 {
    1242            0 :             stat.fragment_size()
    1243              :         } else {
    1244            0 :             stat.block_size()
    1245              :         };
    1246              : 
    1247              :         // use blocks_available (b_avail) since, pageserver runs as unprivileged user
    1248            0 :         let avail_bytes = stat.blocks_available() * blocksize;
    1249            0 :         let total_bytes = stat.blocks() * blocksize;
    1250            0 : 
    1251            0 :         Ok(Usage {
    1252            0 :             config,
    1253            0 :             total_bytes,
    1254            0 :             avail_bytes,
    1255            0 :         })
    1256            0 :     }
    1257              : 
    1258              :     #[test]
    1259            2 :     fn max_usage_pct_pressure() {
    1260            2 :         use super::EvictionOrder;
    1261            2 :         use super::Usage as _;
    1262            2 :         use std::time::Duration;
    1263            2 :         use utils::serde_percent::Percent;
    1264            2 : 
    1265            2 :         let mut usage = Usage {
    1266            2 :             config: &DiskUsageEvictionTaskConfig {
    1267            2 :                 max_usage_pct: Percent::new(85).unwrap(),
    1268            2 :                 min_avail_bytes: 0,
    1269            2 :                 period: Duration::MAX,
    1270            2 :                 #[cfg(feature = "testing")]
    1271            2 :                 mock_statvfs: None,
    1272            2 :                 eviction_order: EvictionOrder::default(),
    1273            2 :             },
    1274            2 :             total_bytes: 100_000,
    1275            2 :             avail_bytes: 0,
    1276            2 :         };
    1277            2 : 
    1278            2 :         assert!(usage.has_pressure(), "expected pressure at 100%");
    1279              : 
    1280            2 :         usage.add_available_bytes(14_000);
    1281            2 :         assert!(usage.has_pressure(), "expected pressure at 86%");
    1282              : 
    1283            2 :         usage.add_available_bytes(999);
    1284            2 :         assert!(usage.has_pressure(), "expected pressure at 85.001%");
    1285              : 
    1286            2 :         usage.add_available_bytes(1);
    1287            2 :         assert!(usage.has_pressure(), "expected pressure at precisely 85%");
    1288              : 
    1289            2 :         usage.add_available_bytes(1);
    1290            2 :         assert!(!usage.has_pressure(), "no pressure at 84.999%");
    1291              : 
    1292            2 :         usage.add_available_bytes(999);
    1293            2 :         assert!(!usage.has_pressure(), "no pressure at 84%");
    1294              : 
    1295            2 :         usage.add_available_bytes(16_000);
    1296            2 :         assert!(!usage.has_pressure());
    1297            2 :     }
    1298              : }
    1299              : 
    1300              : #[cfg(test)]
    1301              : mod tests {
    1302              :     use super::*;
    1303              : 
    1304              :     #[test]
    1305            2 :     fn relative_equal_bounds() {
    1306            2 :         let order = EvictionOrder::RelativeAccessed {
    1307            2 :             highest_layer_count_loses_first: false,
    1308            2 :         };
    1309            2 : 
    1310            2 :         let len = 10;
    1311            2 :         let v = (0..len)
    1312           20 :             .map(|i| order.relative_last_activity(len, i).into_inner())
    1313            2 :             .collect::<Vec<_>>();
    1314            2 : 
    1315            2 :         assert_eq!(v.first(), Some(&1.0));
    1316            2 :         assert_eq!(v.last(), Some(&0.0));
    1317           18 :         assert!(v.windows(2).all(|slice| slice[0] > slice[1]));
    1318            2 :     }
    1319              : 
    1320              :     #[test]
    1321            2 :     fn relative_spare_bounds() {
    1322            2 :         let order = EvictionOrder::RelativeAccessed {
    1323            2 :             highest_layer_count_loses_first: true,
    1324            2 :         };
    1325            2 : 
    1326            2 :         let len = 10;
    1327            2 :         let v = (0..len)
    1328           20 :             .map(|i| order.relative_last_activity(len, i).into_inner())
    1329            2 :             .collect::<Vec<_>>();
    1330            2 : 
    1331            2 :         assert_eq!(v.first(), Some(&1.0));
    1332            2 :         assert_eq!(v.last(), Some(&0.1));
    1333           18 :         assert!(v.windows(2).all(|slice| slice[0] > slice[1]));
    1334            2 :     }
    1335              : }
        

Generated by: LCOV version 2.1-beta