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