Line data Source code
1 : //! This module contains functions to serve per-tenant background processes,
2 : //! such as compaction and GC
3 :
4 : use std::ops::ControlFlow;
5 : use std::str::FromStr;
6 : use std::sync::Arc;
7 : use std::time::{Duration, Instant};
8 :
9 : use crate::context::{DownloadBehavior, RequestContext};
10 : use crate::metrics::TENANT_TASK_EVENTS;
11 : use crate::task_mgr;
12 : use crate::task_mgr::{TaskKind, BACKGROUND_RUNTIME};
13 : use crate::tenant::config::defaults::DEFAULT_COMPACTION_PERIOD;
14 : use crate::tenant::throttle::Stats;
15 : use crate::tenant::timeline::CompactionError;
16 : use crate::tenant::{Tenant, TenantState};
17 : use rand::Rng;
18 : use tokio_util::sync::CancellationToken;
19 : use tracing::*;
20 : use utils::{backoff, completion, pausable_failpoint};
21 :
22 : static CONCURRENT_BACKGROUND_TASKS: once_cell::sync::Lazy<tokio::sync::Semaphore> =
23 60 : once_cell::sync::Lazy::new(|| {
24 60 : let total_threads = task_mgr::TOKIO_WORKER_THREADS.get();
25 60 : let permits = usize::max(
26 60 : 1,
27 60 : // while a lot of the work is done on spawn_blocking, we still do
28 60 : // repartitioning in the async context. this should give leave us some workers
29 60 : // unblocked to be blocked on other work, hopefully easing any outside visible
30 60 : // effects of restarts.
31 60 : //
32 60 : // 6/8 is a guess; previously we ran with unlimited 8 and more from
33 60 : // spawn_blocking.
34 60 : (total_threads * 3).checked_div(4).unwrap_or(0),
35 60 : );
36 60 : assert_ne!(permits, 0, "we will not be adding in permits later");
37 60 : assert!(
38 60 : permits < total_threads,
39 0 : "need threads avail for shorter work"
40 : );
41 60 : tokio::sync::Semaphore::new(permits)
42 60 : });
43 :
44 1080 : #[derive(Debug, PartialEq, Eq, Clone, Copy, strum_macros::IntoStaticStr, enum_map::Enum)]
45 : #[strum(serialize_all = "snake_case")]
46 : pub(crate) enum BackgroundLoopKind {
47 : Compaction,
48 : Gc,
49 : Eviction,
50 : IngestHouseKeeping,
51 : ConsumptionMetricsCollectMetrics,
52 : ConsumptionMetricsSyntheticSizeWorker,
53 : InitialLogicalSizeCalculation,
54 : HeatmapUpload,
55 : SecondaryDownload,
56 : }
57 :
58 : impl BackgroundLoopKind {
59 0 : fn as_static_str(&self) -> &'static str {
60 0 : self.into()
61 0 : }
62 : }
63 :
64 : /// Cancellation safe.
65 1092 : pub(crate) async fn concurrent_background_tasks_rate_limit_permit(
66 1092 : loop_kind: BackgroundLoopKind,
67 1092 : _ctx: &RequestContext,
68 1092 : ) -> tokio::sync::SemaphorePermit<'static> {
69 1092 : let _guard = crate::metrics::BACKGROUND_LOOP_SEMAPHORE.measure_acquisition(loop_kind);
70 :
71 : pausable_failpoint!(
72 : "initial-size-calculation-permit-pause",
73 : loop_kind == BackgroundLoopKind::InitialLogicalSizeCalculation
74 : );
75 :
76 : // TODO: assert that we run on BACKGROUND_RUNTIME; requires tokio_unstable Handle::id();
77 1092 : match CONCURRENT_BACKGROUND_TASKS.acquire().await {
78 1092 : Ok(permit) => permit,
79 0 : Err(_closed) => unreachable!("we never close the semaphore"),
80 : }
81 1092 : }
82 :
83 : /// Start per tenant background loops: compaction and gc.
84 0 : pub fn start_background_loops(
85 0 : tenant: &Arc<Tenant>,
86 0 : background_jobs_can_start: Option<&completion::Barrier>,
87 0 : ) {
88 0 : let tenant_shard_id = tenant.tenant_shard_id;
89 0 : task_mgr::spawn(
90 0 : BACKGROUND_RUNTIME.handle(),
91 0 : TaskKind::Compaction,
92 0 : tenant_shard_id,
93 0 : None,
94 0 : &format!("compactor for tenant {tenant_shard_id}"),
95 0 : {
96 0 : let tenant = Arc::clone(tenant);
97 0 : let background_jobs_can_start = background_jobs_can_start.cloned();
98 0 : async move {
99 0 : let cancel = task_mgr::shutdown_token();
100 : tokio::select! {
101 : _ = cancel.cancelled() => { return Ok(()) },
102 : _ = completion::Barrier::maybe_wait(background_jobs_can_start) => {}
103 : };
104 0 : compaction_loop(tenant, cancel)
105 0 : // If you rename this span, change the RUST_LOG env variable in test_runner/performance/test_branch_creation.py
106 0 : .instrument(info_span!("compaction_loop", tenant_id = %tenant_shard_id.tenant_id, shard_id = %tenant_shard_id.shard_slug()))
107 0 : .await;
108 0 : Ok(())
109 0 : }
110 0 : },
111 0 : );
112 0 : task_mgr::spawn(
113 0 : BACKGROUND_RUNTIME.handle(),
114 0 : TaskKind::GarbageCollector,
115 0 : tenant_shard_id,
116 0 : None,
117 0 : &format!("garbage collector for tenant {tenant_shard_id}"),
118 0 : {
119 0 : let tenant = Arc::clone(tenant);
120 0 : let background_jobs_can_start = background_jobs_can_start.cloned();
121 0 : async move {
122 0 : let cancel = task_mgr::shutdown_token();
123 : tokio::select! {
124 : _ = cancel.cancelled() => { return Ok(()) },
125 : _ = completion::Barrier::maybe_wait(background_jobs_can_start) => {}
126 : };
127 0 : gc_loop(tenant, cancel)
128 0 : .instrument(info_span!("gc_loop", tenant_id = %tenant_shard_id.tenant_id, shard_id = %tenant_shard_id.shard_slug()))
129 0 : .await;
130 0 : Ok(())
131 0 : }
132 0 : },
133 0 : );
134 0 :
135 0 : task_mgr::spawn(
136 0 : BACKGROUND_RUNTIME.handle(),
137 0 : TaskKind::IngestHousekeeping,
138 0 : tenant_shard_id,
139 0 : None,
140 0 : &format!("ingest housekeeping for tenant {tenant_shard_id}"),
141 0 : {
142 0 : let tenant = Arc::clone(tenant);
143 0 : let background_jobs_can_start = background_jobs_can_start.cloned();
144 0 : async move {
145 0 : let cancel = task_mgr::shutdown_token();
146 : tokio::select! {
147 : _ = cancel.cancelled() => { return Ok(()) },
148 : _ = completion::Barrier::maybe_wait(background_jobs_can_start) => {}
149 : };
150 0 : ingest_housekeeping_loop(tenant, cancel)
151 0 : .instrument(info_span!("ingest_housekeeping_loop", tenant_id = %tenant_shard_id.tenant_id, shard_id = %tenant_shard_id.shard_slug()))
152 0 : .await;
153 0 : Ok(())
154 0 : }
155 0 : },
156 0 : );
157 0 : }
158 :
159 : ///
160 : /// Compaction task's main loop
161 : ///
162 0 : async fn compaction_loop(tenant: Arc<Tenant>, cancel: CancellationToken) {
163 0 : const MAX_BACKOFF_SECS: f64 = 300.0;
164 0 : // How many errors we have seen consequtively
165 0 : let mut error_run_count = 0;
166 0 :
167 0 : let mut last_throttle_flag_reset_at = Instant::now();
168 0 :
169 0 : TENANT_TASK_EVENTS.with_label_values(&["start"]).inc();
170 0 : async {
171 0 : let ctx = RequestContext::todo_child(TaskKind::Compaction, DownloadBehavior::Download);
172 0 : let mut first = true;
173 0 : loop {
174 0 : tokio::select! {
175 : _ = cancel.cancelled() => {
176 : return;
177 : },
178 : tenant_wait_result = wait_for_active_tenant(&tenant) => match tenant_wait_result {
179 : ControlFlow::Break(()) => return,
180 : ControlFlow::Continue(()) => (),
181 : },
182 : }
183 :
184 0 : let period = tenant.get_compaction_period();
185 0 :
186 0 : // TODO: we shouldn't need to await to find tenant and this could be moved outside of
187 0 : // loop, #3501. There are also additional "allowed_errors" in tests.
188 0 : if first {
189 0 : first = false;
190 0 : if random_init_delay(period, &cancel).await.is_err() {
191 0 : break;
192 0 : }
193 0 : }
194 :
195 0 : let started_at = Instant::now();
196 :
197 0 : let sleep_duration = if period == Duration::ZERO {
198 : #[cfg(not(feature = "testing"))]
199 : info!("automatic compaction is disabled");
200 : // check again in 10 seconds, in case it's been enabled again.
201 0 : Duration::from_secs(10)
202 : } else {
203 : // Run compaction
204 0 : match tenant.compaction_iteration(&cancel, &ctx).await {
205 0 : Ok(has_pending_task) => {
206 0 : error_run_count = 0;
207 0 : // schedule the next compaction immediately in case there is a pending compaction task
208 0 : if has_pending_task { Duration::ZERO } else { period }
209 : }
210 0 : Err(e) => {
211 0 : let wait_duration = backoff::exponential_backoff_duration_seconds(
212 0 : error_run_count + 1,
213 0 : 1.0,
214 0 : MAX_BACKOFF_SECS,
215 0 : );
216 0 : error_run_count += 1;
217 0 : let wait_duration = Duration::from_secs_f64(wait_duration);
218 0 : log_compaction_error(
219 0 : &e,
220 0 : error_run_count,
221 0 : &wait_duration,
222 0 : cancel.is_cancelled(),
223 0 : );
224 0 : wait_duration
225 : }
226 : }
227 : };
228 :
229 0 : let elapsed = started_at.elapsed();
230 0 : warn_when_period_overrun(elapsed, period, BackgroundLoopKind::Compaction);
231 0 :
232 0 : // the duration is recorded by performance tests by enabling debug in this function
233 0 : tracing::debug!(elapsed_ms=elapsed.as_millis(), "compaction iteration complete");
234 :
235 : // Perhaps we did no work and the walredo process has been idle for some time:
236 : // give it a chance to shut down to avoid leaving walredo process running indefinitely.
237 0 : if let Some(walredo_mgr) = &tenant.walredo_mgr {
238 0 : walredo_mgr.maybe_quiesce(period * 10);
239 0 : }
240 :
241 : // TODO: move this (and walredo quiesce) to a separate task that isn't affected by the back-off,
242 : // so we get some upper bound guarantee on when walredo quiesce / this throttling reporting here happens.
243 0 : info_span!(parent: None, "timeline_get_throttle", tenant_id=%tenant.tenant_shard_id, shard_id=%tenant.tenant_shard_id.shard_slug()).in_scope(|| {
244 0 : let now = Instant::now();
245 0 : let prev = std::mem::replace(&mut last_throttle_flag_reset_at, now);
246 0 : let Stats { count_accounted, count_throttled, sum_throttled_usecs } = tenant.timeline_get_throttle.reset_stats();
247 0 : if count_throttled == 0 {
248 0 : return;
249 0 : }
250 0 : let allowed_rps = tenant.timeline_get_throttle.steady_rps();
251 0 : let delta = now - prev;
252 0 : info!(
253 0 : n_seconds=%format_args!("{:.3}",
254 0 : delta.as_secs_f64()),
255 : count_accounted,
256 : count_throttled,
257 : sum_throttled_usecs,
258 0 : allowed_rps=%format_args!("{allowed_rps:.0}"),
259 0 : "shard was throttled in the last n_seconds"
260 : );
261 0 : });
262 0 :
263 0 : // Sleep
264 0 : if tokio::time::timeout(sleep_duration, cancel.cancelled())
265 0 : .await
266 0 : .is_ok()
267 : {
268 0 : break;
269 0 : }
270 : }
271 0 : }
272 0 : .await;
273 0 : TENANT_TASK_EVENTS.with_label_values(&["stop"]).inc();
274 0 : }
275 :
276 0 : fn log_compaction_error(
277 0 : e: &CompactionError,
278 0 : error_run_count: u32,
279 0 : sleep_duration: &std::time::Duration,
280 0 : task_cancelled: bool,
281 0 : ) {
282 : use crate::tenant::upload_queue::NotInitialized;
283 : use crate::tenant::PageReconstructError;
284 : use CompactionError::*;
285 :
286 : enum LooksLike {
287 : Info,
288 : Error,
289 : }
290 :
291 0 : let decision = match e {
292 0 : ShuttingDown => None,
293 0 : _ if task_cancelled => Some(LooksLike::Info),
294 0 : Other(e) => {
295 0 : let root_cause = e.root_cause();
296 :
297 0 : let is_stopping = {
298 0 : let upload_queue = root_cause
299 0 : .downcast_ref::<NotInitialized>()
300 0 : .is_some_and(|e| e.is_stopping());
301 0 :
302 0 : let timeline = root_cause
303 0 : .downcast_ref::<PageReconstructError>()
304 0 : .is_some_and(|e| e.is_stopping());
305 0 :
306 0 : upload_queue || timeline
307 : };
308 :
309 0 : if is_stopping {
310 0 : Some(LooksLike::Info)
311 : } else {
312 0 : Some(LooksLike::Error)
313 : }
314 : }
315 : };
316 :
317 0 : match decision {
318 0 : Some(LooksLike::Info) => info!(
319 0 : "Compaction failed {error_run_count} times, retrying in {sleep_duration:?}: {e:#}",
320 : ),
321 0 : Some(LooksLike::Error) => error!(
322 0 : "Compaction failed {error_run_count} times, retrying in {sleep_duration:?}: {e:?}",
323 : ),
324 0 : None => {}
325 : }
326 0 : }
327 :
328 : ///
329 : /// GC task's main loop
330 : ///
331 0 : async fn gc_loop(tenant: Arc<Tenant>, cancel: CancellationToken) {
332 0 : const MAX_BACKOFF_SECS: f64 = 300.0;
333 0 : // How many errors we have seen consequtively
334 0 : let mut error_run_count = 0;
335 0 :
336 0 : TENANT_TASK_EVENTS.with_label_values(&["start"]).inc();
337 0 : async {
338 0 : // GC might require downloading, to find the cutoff LSN that corresponds to the
339 0 : // cutoff specified as time.
340 0 : let ctx =
341 0 : RequestContext::todo_child(TaskKind::GarbageCollector, DownloadBehavior::Download);
342 0 :
343 0 : let mut first = true;
344 0 : loop {
345 0 : tokio::select! {
346 : _ = cancel.cancelled() => {
347 : return;
348 : },
349 : tenant_wait_result = wait_for_active_tenant(&tenant) => match tenant_wait_result {
350 : ControlFlow::Break(()) => return,
351 : ControlFlow::Continue(()) => (),
352 : },
353 : }
354 :
355 0 : let period = tenant.get_gc_period();
356 0 :
357 0 : if first {
358 0 : first = false;
359 0 :
360 0 : let delays = async {
361 0 : delay_by_lease_length(tenant.get_lsn_lease_length(), &cancel).await?;
362 0 : random_init_delay(period, &cancel).await?;
363 0 : Ok::<_, Cancelled>(())
364 0 : };
365 :
366 0 : if delays.await.is_err() {
367 0 : break;
368 0 : }
369 0 : }
370 :
371 0 : let started_at = Instant::now();
372 0 :
373 0 : let gc_horizon = tenant.get_gc_horizon();
374 0 : let sleep_duration = if period == Duration::ZERO || gc_horizon == 0 {
375 : #[cfg(not(feature = "testing"))]
376 : info!("automatic GC is disabled");
377 : // check again in 10 seconds, in case it's been enabled again.
378 0 : Duration::from_secs(10)
379 : } else {
380 : // Run gc
381 0 : let res = tenant
382 0 : .gc_iteration(None, gc_horizon, tenant.get_pitr_interval(), &cancel, &ctx)
383 0 : .await;
384 0 : match res {
385 : Ok(_) => {
386 0 : error_run_count = 0;
387 0 : period
388 : }
389 : Err(crate::tenant::GcError::TenantCancelled) => {
390 0 : return;
391 : }
392 0 : Err(e) => {
393 0 : let wait_duration = backoff::exponential_backoff_duration_seconds(
394 0 : error_run_count + 1,
395 0 : 1.0,
396 0 : MAX_BACKOFF_SECS,
397 0 : );
398 0 : error_run_count += 1;
399 0 : let wait_duration = Duration::from_secs_f64(wait_duration);
400 :
401 0 : if matches!(e, crate::tenant::GcError::TimelineCancelled) {
402 : // Timeline was cancelled during gc. We might either be in an event
403 : // that affects the entire tenant (tenant deletion, pageserver shutdown),
404 : // or in one that affects the timeline only (timeline deletion).
405 : // Therefore, don't exit the loop.
406 0 : info!("Gc failed {error_run_count} times, retrying in {wait_duration:?}: {e:?}");
407 : } else {
408 0 : error!("Gc failed {error_run_count} times, retrying in {wait_duration:?}: {e:?}");
409 : }
410 :
411 0 : wait_duration
412 : }
413 : }
414 : };
415 :
416 0 : warn_when_period_overrun(started_at.elapsed(), period, BackgroundLoopKind::Gc);
417 0 :
418 0 : if tokio::time::timeout(sleep_duration, cancel.cancelled())
419 0 : .await
420 0 : .is_ok()
421 : {
422 0 : break;
423 0 : }
424 : }
425 0 : }
426 0 : .await;
427 0 : TENANT_TASK_EVENTS.with_label_values(&["stop"]).inc();
428 0 : }
429 :
430 0 : async fn ingest_housekeeping_loop(tenant: Arc<Tenant>, cancel: CancellationToken) {
431 0 : TENANT_TASK_EVENTS.with_label_values(&["start"]).inc();
432 0 : async {
433 0 : loop {
434 0 : tokio::select! {
435 : _ = cancel.cancelled() => {
436 : return;
437 : },
438 : tenant_wait_result = wait_for_active_tenant(&tenant) => match tenant_wait_result {
439 : ControlFlow::Break(()) => return,
440 : ControlFlow::Continue(()) => (),
441 : },
442 : }
443 :
444 : // We run ingest housekeeping with the same frequency as compaction: it is not worth
445 : // having a distinct setting. But we don't run it in the same task, because compaction
446 : // blocks on acquiring the background job semaphore.
447 0 : let period = tenant.get_compaction_period();
448 :
449 : // If compaction period is set to zero (to disable it), then we will use a reasonable default
450 0 : let period = if period == Duration::ZERO {
451 0 : humantime::Duration::from_str(DEFAULT_COMPACTION_PERIOD)
452 0 : .unwrap()
453 0 : .into()
454 : } else {
455 0 : period
456 : };
457 :
458 : // Jitter the period by +/- 5%
459 0 : let period =
460 0 : rand::thread_rng().gen_range((period * (95)) / 100..(period * (105)) / 100);
461 0 :
462 0 : // Always sleep first: we do not need to do ingest housekeeping early in the lifetime of
463 0 : // a tenant, since it won't have started writing any ephemeral files yet.
464 0 : if tokio::time::timeout(period, cancel.cancelled())
465 0 : .await
466 0 : .is_ok()
467 : {
468 0 : break;
469 0 : }
470 0 :
471 0 : let started_at = Instant::now();
472 0 : tenant.ingest_housekeeping().await;
473 :
474 0 : warn_when_period_overrun(
475 0 : started_at.elapsed(),
476 0 : period,
477 0 : BackgroundLoopKind::IngestHouseKeeping,
478 0 : );
479 : }
480 0 : }
481 0 : .await;
482 0 : TENANT_TASK_EVENTS.with_label_values(&["stop"]).inc();
483 0 : }
484 :
485 0 : async fn wait_for_active_tenant(tenant: &Arc<Tenant>) -> ControlFlow<()> {
486 0 : // if the tenant has a proper status already, no need to wait for anything
487 0 : if tenant.current_state() == TenantState::Active {
488 0 : ControlFlow::Continue(())
489 : } else {
490 0 : let mut tenant_state_updates = tenant.subscribe_for_state_updates();
491 : loop {
492 0 : match tenant_state_updates.changed().await {
493 : Ok(()) => {
494 0 : let new_state = &*tenant_state_updates.borrow();
495 0 : match new_state {
496 : TenantState::Active => {
497 0 : debug!("Tenant state changed to active, continuing the task loop");
498 0 : return ControlFlow::Continue(());
499 : }
500 0 : state => {
501 0 : debug!("Not running the task loop, tenant is not active: {state:?}");
502 0 : continue;
503 : }
504 : }
505 : }
506 0 : Err(_sender_dropped_error) => {
507 0 : return ControlFlow::Break(());
508 : }
509 : }
510 : }
511 : }
512 0 : }
513 :
514 0 : #[derive(thiserror::Error, Debug)]
515 : #[error("cancelled")]
516 : pub(crate) struct Cancelled;
517 :
518 : /// Provide a random delay for background task initialization.
519 : ///
520 : /// This delay prevents a thundering herd of background tasks and will likely keep them running on
521 : /// different periods for more stable load.
522 0 : pub(crate) async fn random_init_delay(
523 0 : period: Duration,
524 0 : cancel: &CancellationToken,
525 0 : ) -> Result<(), Cancelled> {
526 0 : if period == Duration::ZERO {
527 0 : return Ok(());
528 0 : }
529 0 :
530 0 : let d = {
531 0 : let mut rng = rand::thread_rng();
532 0 : rng.gen_range(Duration::ZERO..=period)
533 0 : };
534 0 :
535 0 : match tokio::time::timeout(d, cancel.cancelled()).await {
536 0 : Ok(_) => Err(Cancelled),
537 0 : Err(_) => Ok(()),
538 : }
539 0 : }
540 :
541 : /// Delays GC by defaul lease length at restart.
542 : ///
543 : /// We do this as the leases mapping are not persisted to disk. By delaying GC by default
544 : /// length, we gurantees that all the leases we granted before the restart will expire
545 : /// when we run GC for the first time after the restart.
546 0 : pub(crate) async fn delay_by_lease_length(
547 0 : length: Duration,
548 0 : cancel: &CancellationToken,
549 0 : ) -> Result<(), Cancelled> {
550 0 : match tokio::time::timeout(length, cancel.cancelled()).await {
551 0 : Ok(_) => Err(Cancelled),
552 0 : Err(_) => Ok(()),
553 : }
554 0 : }
555 :
556 : /// Attention: the `task` and `period` beocme labels of a pageserver-wide prometheus metric.
557 0 : pub(crate) fn warn_when_period_overrun(
558 0 : elapsed: Duration,
559 0 : period: Duration,
560 0 : task: BackgroundLoopKind,
561 0 : ) {
562 0 : // Duration::ZERO will happen because it's the "disable [bgtask]" value.
563 0 : if elapsed >= period && period != Duration::ZERO {
564 : // humantime does no significant digits clamping whereas Duration's debug is a bit more
565 : // intelligent. however it makes sense to keep the "configuration format" for period, even
566 : // though there's no way to output the actual config value.
567 0 : info!(
568 : ?elapsed,
569 0 : period = %humantime::format_duration(period),
570 0 : ?task,
571 0 : "task iteration took longer than the configured period"
572 : );
573 0 : crate::metrics::BACKGROUND_LOOP_PERIOD_OVERRUN_COUNT
574 0 : .with_label_values(&[task.as_static_str(), &format!("{}", period.as_secs())])
575 0 : .inc();
576 0 : }
577 0 : }
|