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::sync::Arc;
6 : use std::time::{Duration, Instant};
7 :
8 : use crate::context::{DownloadBehavior, RequestContext};
9 : use crate::metrics::TENANT_TASK_EVENTS;
10 : use crate::task_mgr;
11 : use crate::task_mgr::{TaskKind, BACKGROUND_RUNTIME};
12 : use crate::tenant::throttle::Stats;
13 : use crate::tenant::timeline::CompactionError;
14 : use crate::tenant::{Tenant, TenantState};
15 : use tokio_util::sync::CancellationToken;
16 : use tracing::*;
17 : use utils::{backoff, completion};
18 :
19 : static CONCURRENT_BACKGROUND_TASKS: once_cell::sync::Lazy<tokio::sync::Semaphore> =
20 14 : once_cell::sync::Lazy::new(|| {
21 14 : let total_threads = *task_mgr::BACKGROUND_RUNTIME_WORKER_THREADS;
22 14 : let permits = usize::max(
23 14 : 1,
24 14 : // while a lot of the work is done on spawn_blocking, we still do
25 14 : // repartitioning in the async context. this should give leave us some workers
26 14 : // unblocked to be blocked on other work, hopefully easing any outside visible
27 14 : // effects of restarts.
28 14 : //
29 14 : // 6/8 is a guess; previously we ran with unlimited 8 and more from
30 14 : // spawn_blocking.
31 14 : (total_threads * 3).checked_div(4).unwrap_or(0),
32 14 : );
33 14 : assert_ne!(permits, 0, "we will not be adding in permits later");
34 14 : assert!(
35 14 : permits < total_threads,
36 0 : "need threads avail for shorter work"
37 : );
38 14 : tokio::sync::Semaphore::new(permits)
39 14 : });
40 :
41 510 : #[derive(Debug, PartialEq, Eq, Clone, Copy, strum_macros::IntoStaticStr)]
42 : #[strum(serialize_all = "snake_case")]
43 : pub(crate) enum BackgroundLoopKind {
44 : Compaction,
45 : Gc,
46 : Eviction,
47 : ConsumptionMetricsCollectMetrics,
48 : ConsumptionMetricsSyntheticSizeWorker,
49 : InitialLogicalSizeCalculation,
50 : HeatmapUpload,
51 : SecondaryDownload,
52 : }
53 :
54 : impl BackgroundLoopKind {
55 510 : fn as_static_str(&self) -> &'static str {
56 510 : let s: &'static str = self.into();
57 510 : s
58 510 : }
59 : }
60 :
61 : /// Cancellation safe.
62 510 : pub(crate) async fn concurrent_background_tasks_rate_limit_permit(
63 510 : loop_kind: BackgroundLoopKind,
64 510 : _ctx: &RequestContext,
65 510 : ) -> impl Drop {
66 510 : let _guard = crate::metrics::BACKGROUND_LOOP_SEMAPHORE_WAIT_GAUGE
67 510 : .with_label_values(&[loop_kind.as_static_str()])
68 510 : .guard();
69 :
70 0 : pausable_failpoint!(
71 0 : "initial-size-calculation-permit-pause",
72 0 : loop_kind == BackgroundLoopKind::InitialLogicalSizeCalculation
73 0 : );
74 :
75 510 : match CONCURRENT_BACKGROUND_TASKS.acquire().await {
76 510 : Ok(permit) => permit,
77 0 : Err(_closed) => unreachable!("we never close the semaphore"),
78 : }
79 510 : }
80 :
81 : /// Start per tenant background loops: compaction and gc.
82 0 : pub fn start_background_loops(
83 0 : tenant: &Arc<Tenant>,
84 0 : background_jobs_can_start: Option<&completion::Barrier>,
85 0 : ) {
86 0 : let tenant_shard_id = tenant.tenant_shard_id;
87 0 : task_mgr::spawn(
88 0 : BACKGROUND_RUNTIME.handle(),
89 0 : TaskKind::Compaction,
90 0 : Some(tenant_shard_id),
91 0 : None,
92 0 : &format!("compactor for tenant {tenant_shard_id}"),
93 0 : false,
94 0 : {
95 0 : let tenant = Arc::clone(tenant);
96 0 : let background_jobs_can_start = background_jobs_can_start.cloned();
97 0 : async move {
98 0 : let cancel = task_mgr::shutdown_token();
99 0 : tokio::select! {
100 0 : _ = cancel.cancelled() => { return Ok(()) },
101 0 : _ = completion::Barrier::maybe_wait(background_jobs_can_start) => {}
102 0 : };
103 0 : compaction_loop(tenant, cancel)
104 0 : // If you rename this span, change the RUST_LOG env variable in test_runner/performance/test_branch_creation.py
105 0 : .instrument(info_span!("compaction_loop", tenant_id = %tenant_shard_id.tenant_id, shard_id = %tenant_shard_id.shard_slug()))
106 0 : .await;
107 0 : Ok(())
108 0 : }
109 0 : },
110 0 : );
111 0 : task_mgr::spawn(
112 0 : BACKGROUND_RUNTIME.handle(),
113 0 : TaskKind::GarbageCollector,
114 0 : Some(tenant_shard_id),
115 0 : None,
116 0 : &format!("garbage collector for tenant {tenant_shard_id}"),
117 0 : false,
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 0 : tokio::select! {
124 0 : _ = cancel.cancelled() => { return Ok(()) },
125 0 : _ = completion::Barrier::maybe_wait(background_jobs_can_start) => {}
126 0 : };
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 :
136 : ///
137 : /// Compaction task's main loop
138 : ///
139 0 : async fn compaction_loop(tenant: Arc<Tenant>, cancel: CancellationToken) {
140 0 : const MAX_BACKOFF_SECS: f64 = 300.0;
141 0 : // How many errors we have seen consequtively
142 0 : let mut error_run_count = 0;
143 0 :
144 0 : let mut last_throttle_flag_reset_at = Instant::now();
145 0 :
146 0 : TENANT_TASK_EVENTS.with_label_values(&["start"]).inc();
147 0 : async {
148 0 : let ctx = RequestContext::todo_child(TaskKind::Compaction, DownloadBehavior::Download);
149 0 : let mut first = true;
150 0 : loop {
151 0 : tokio::select! {
152 : _ = cancel.cancelled() => {
153 : return;
154 : },
155 0 : tenant_wait_result = wait_for_active_tenant(&tenant) => match tenant_wait_result {
156 : ControlFlow::Break(()) => return,
157 : ControlFlow::Continue(()) => (),
158 : },
159 : }
160 :
161 0 : let period = tenant.get_compaction_period();
162 0 :
163 0 : // TODO: we shouldn't need to await to find tenant and this could be moved outside of
164 0 : // loop, #3501. There are also additional "allowed_errors" in tests.
165 0 : if first {
166 0 : first = false;
167 0 : if random_init_delay(period, &cancel).await.is_err() {
168 0 : break;
169 0 : }
170 0 : }
171 :
172 0 : let started_at = Instant::now();
173 :
174 0 : let sleep_duration = if period == Duration::ZERO {
175 : #[cfg(not(feature = "testing"))]
176 : info!("automatic compaction is disabled");
177 : // check again in 10 seconds, in case it's been enabled again.
178 0 : Duration::from_secs(10)
179 : } else {
180 : // Run compaction
181 0 : if let Err(e) = tenant.compaction_iteration(&cancel, &ctx).await {
182 0 : let wait_duration = backoff::exponential_backoff_duration_seconds(
183 0 : error_run_count + 1,
184 0 : 1.0,
185 0 : MAX_BACKOFF_SECS,
186 0 : );
187 0 : error_run_count += 1;
188 0 : let wait_duration = Duration::from_secs_f64(wait_duration);
189 0 : log_compaction_error(
190 0 : &e,
191 0 : error_run_count,
192 0 : &wait_duration,
193 0 : cancel.is_cancelled(),
194 0 : );
195 0 : wait_duration
196 : } else {
197 0 : error_run_count = 0;
198 0 : period
199 : }
200 : };
201 :
202 0 : let elapsed = started_at.elapsed();
203 0 : warn_when_period_overrun(elapsed, period, BackgroundLoopKind::Compaction);
204 0 :
205 0 : // the duration is recorded by performance tests by enabling debug in this function
206 0 : tracing::debug!(elapsed_ms=elapsed.as_millis(), "compaction iteration complete");
207 :
208 : // Perhaps we did no work and the walredo process has been idle for some time:
209 : // give it a chance to shut down to avoid leaving walredo process running indefinitely.
210 0 : if let Some(walredo_mgr) = &tenant.walredo_mgr {
211 0 : walredo_mgr.maybe_quiesce(period * 10);
212 0 : }
213 :
214 : // TODO: move this (and walredo quiesce) to a separate task that isn't affected by the back-off,
215 : // so we get some upper bound guarantee on when walredo quiesce / this throttling reporting here happens.
216 0 : info_span!(parent: None, "timeline_get_throttle", tenant_id=%tenant.tenant_shard_id, shard_id=%tenant.tenant_shard_id.shard_slug()).in_scope(|| {
217 0 : let now = Instant::now();
218 0 : let prev = std::mem::replace(&mut last_throttle_flag_reset_at, now);
219 0 : let Stats { count_accounted, count_throttled, sum_throttled_usecs } = tenant.timeline_get_throttle.reset_stats();
220 0 : if count_throttled == 0 {
221 0 : return;
222 0 : }
223 0 : let allowed_rps = tenant.timeline_get_throttle.steady_rps();
224 0 : let delta = now - prev;
225 0 : info!(
226 0 : n_seconds=%format_args!("{:.3}",
227 0 : delta.as_secs_f64()),
228 0 : count_accounted,
229 0 : count_throttled,
230 0 : sum_throttled_usecs,
231 0 : allowed_rps=%format_args!("{allowed_rps:.0}"),
232 0 : "shard was throttled in the last n_seconds")
233 0 : });
234 0 :
235 0 : // Sleep
236 0 : if tokio::time::timeout(sleep_duration, cancel.cancelled())
237 0 : .await
238 0 : .is_ok()
239 : {
240 0 : break;
241 0 : }
242 : }
243 0 : }
244 0 : .await;
245 0 : TENANT_TASK_EVENTS.with_label_values(&["stop"]).inc();
246 0 : }
247 :
248 0 : fn log_compaction_error(
249 0 : e: &CompactionError,
250 0 : error_run_count: u32,
251 0 : sleep_duration: &std::time::Duration,
252 0 : task_cancelled: bool,
253 0 : ) {
254 : use crate::tenant::upload_queue::NotInitialized;
255 : use crate::tenant::PageReconstructError;
256 : use CompactionError::*;
257 :
258 : enum LooksLike {
259 : Info,
260 : Error,
261 : }
262 :
263 0 : let decision = match e {
264 0 : ShuttingDown => None,
265 0 : _ if task_cancelled => Some(LooksLike::Info),
266 0 : Other(e) => {
267 0 : let root_cause = e.root_cause();
268 :
269 0 : let is_stopping = {
270 0 : let upload_queue = root_cause
271 0 : .downcast_ref::<NotInitialized>()
272 0 : .is_some_and(|e| e.is_stopping());
273 0 :
274 0 : let timeline = root_cause
275 0 : .downcast_ref::<PageReconstructError>()
276 0 : .is_some_and(|e| e.is_stopping());
277 0 :
278 0 : upload_queue || timeline
279 : };
280 :
281 0 : if is_stopping {
282 0 : Some(LooksLike::Info)
283 : } else {
284 0 : Some(LooksLike::Error)
285 : }
286 : }
287 : };
288 :
289 0 : match decision {
290 0 : Some(LooksLike::Info) => info!(
291 0 : "Compaction failed {error_run_count} times, retrying in {sleep_duration:?}: {e:#}",
292 0 : ),
293 0 : Some(LooksLike::Error) => error!(
294 0 : "Compaction failed {error_run_count} times, retrying in {sleep_duration:?}: {e:?}",
295 0 : ),
296 0 : None => {}
297 : }
298 0 : }
299 :
300 : ///
301 : /// GC task's main loop
302 : ///
303 0 : async fn gc_loop(tenant: Arc<Tenant>, cancel: CancellationToken) {
304 0 : const MAX_BACKOFF_SECS: f64 = 300.0;
305 0 : // How many errors we have seen consequtively
306 0 : let mut error_run_count = 0;
307 0 :
308 0 : TENANT_TASK_EVENTS.with_label_values(&["start"]).inc();
309 0 : async {
310 0 : // GC might require downloading, to find the cutoff LSN that corresponds to the
311 0 : // cutoff specified as time.
312 0 : let ctx =
313 0 : RequestContext::todo_child(TaskKind::GarbageCollector, DownloadBehavior::Download);
314 0 : let mut first = true;
315 0 : loop {
316 0 : tokio::select! {
317 : _ = cancel.cancelled() => {
318 : return;
319 : },
320 0 : tenant_wait_result = wait_for_active_tenant(&tenant) => match tenant_wait_result {
321 : ControlFlow::Break(()) => return,
322 : ControlFlow::Continue(()) => (),
323 : },
324 : }
325 :
326 0 : let period = tenant.get_gc_period();
327 0 :
328 0 : if first {
329 0 : first = false;
330 0 : if random_init_delay(period, &cancel).await.is_err() {
331 0 : break;
332 0 : }
333 0 : }
334 :
335 0 : let started_at = Instant::now();
336 0 :
337 0 : let gc_horizon = tenant.get_gc_horizon();
338 0 : let sleep_duration = if period == Duration::ZERO || gc_horizon == 0 {
339 : #[cfg(not(feature = "testing"))]
340 : info!("automatic GC is disabled");
341 : // check again in 10 seconds, in case it's been enabled again.
342 0 : Duration::from_secs(10)
343 : } else {
344 : // Run gc
345 0 : let res = tenant
346 0 : .gc_iteration(None, gc_horizon, tenant.get_pitr_interval(), &cancel, &ctx)
347 0 : .await;
348 0 : if let Err(e) = res {
349 0 : let wait_duration = backoff::exponential_backoff_duration_seconds(
350 0 : error_run_count + 1,
351 0 : 1.0,
352 0 : MAX_BACKOFF_SECS,
353 0 : );
354 0 : error_run_count += 1;
355 0 : let wait_duration = Duration::from_secs_f64(wait_duration);
356 0 : error!(
357 0 : "Gc failed {error_run_count} times, retrying in {wait_duration:?}: {e:?}",
358 0 : );
359 0 : wait_duration
360 : } else {
361 0 : error_run_count = 0;
362 0 : period
363 : }
364 : };
365 :
366 0 : warn_when_period_overrun(started_at.elapsed(), period, BackgroundLoopKind::Gc);
367 0 :
368 0 : // Sleep
369 0 : if tokio::time::timeout(sleep_duration, cancel.cancelled())
370 0 : .await
371 0 : .is_ok()
372 : {
373 0 : break;
374 0 : }
375 : }
376 0 : }
377 0 : .await;
378 0 : TENANT_TASK_EVENTS.with_label_values(&["stop"]).inc();
379 0 : }
380 :
381 0 : async fn wait_for_active_tenant(tenant: &Arc<Tenant>) -> ControlFlow<()> {
382 0 : // if the tenant has a proper status already, no need to wait for anything
383 0 : if tenant.current_state() == TenantState::Active {
384 0 : ControlFlow::Continue(())
385 : } else {
386 0 : let mut tenant_state_updates = tenant.subscribe_for_state_updates();
387 : loop {
388 0 : match tenant_state_updates.changed().await {
389 : Ok(()) => {
390 0 : let new_state = &*tenant_state_updates.borrow();
391 0 : match new_state {
392 : TenantState::Active => {
393 0 : debug!("Tenant state changed to active, continuing the task loop");
394 0 : return ControlFlow::Continue(());
395 : }
396 0 : state => {
397 0 : debug!("Not running the task loop, tenant is not active: {state:?}");
398 0 : continue;
399 : }
400 : }
401 : }
402 0 : Err(_sender_dropped_error) => {
403 0 : return ControlFlow::Break(());
404 : }
405 : }
406 : }
407 : }
408 0 : }
409 :
410 0 : #[derive(thiserror::Error, Debug)]
411 : #[error("cancelled")]
412 : pub(crate) struct Cancelled;
413 :
414 : /// Provide a random delay for background task initialization.
415 : ///
416 : /// This delay prevents a thundering herd of background tasks and will likely keep them running on
417 : /// different periods for more stable load.
418 0 : pub(crate) async fn random_init_delay(
419 0 : period: Duration,
420 0 : cancel: &CancellationToken,
421 0 : ) -> Result<(), Cancelled> {
422 0 : use rand::Rng;
423 0 :
424 0 : if period == Duration::ZERO {
425 0 : return Ok(());
426 0 : }
427 0 :
428 0 : let d = {
429 0 : let mut rng = rand::thread_rng();
430 0 : rng.gen_range(Duration::ZERO..=period)
431 0 : };
432 0 :
433 0 : match tokio::time::timeout(d, cancel.cancelled()).await {
434 0 : Ok(_) => Err(Cancelled),
435 0 : Err(_) => Ok(()),
436 : }
437 0 : }
438 :
439 : /// Attention: the `task` and `period` beocme labels of a pageserver-wide prometheus metric.
440 0 : pub(crate) fn warn_when_period_overrun(
441 0 : elapsed: Duration,
442 0 : period: Duration,
443 0 : task: BackgroundLoopKind,
444 0 : ) {
445 0 : // Duration::ZERO will happen because it's the "disable [bgtask]" value.
446 0 : if elapsed >= period && period != Duration::ZERO {
447 : // humantime does no significant digits clamping whereas Duration's debug is a bit more
448 : // intelligent. however it makes sense to keep the "configuration format" for period, even
449 : // though there's no way to output the actual config value.
450 0 : info!(
451 0 : ?elapsed,
452 0 : period = %humantime::format_duration(period),
453 0 : ?task,
454 0 : "task iteration took longer than the configured period"
455 0 : );
456 0 : crate::metrics::BACKGROUND_LOOP_PERIOD_OVERRUN_COUNT
457 0 : .with_label_values(&[task.as_static_str(), &format!("{}", period.as_secs())])
458 0 : .inc();
459 0 : }
460 0 : }
|