Line data Source code
1 : //! The timeline manager task is responsible for managing the timeline's background tasks.
2 : //!
3 : //! It is spawned alongside each timeline and exits when the timeline is deleted.
4 : //! It watches for changes in the timeline state and decides when to spawn or kill background tasks.
5 : //! It also can manage some reactive state, like should the timeline be active for broker pushes or not.
6 : //!
7 : //! Be aware that you need to be extra careful with manager code, because it is not respawned on panic.
8 : //! Also, if it will stuck in some branch, it will prevent any further progress in the timeline.
9 :
10 : use std::{
11 : sync::{atomic::AtomicUsize, Arc},
12 : time::Duration,
13 : };
14 :
15 : use futures::channel::oneshot;
16 : use postgres_ffi::XLogSegNo;
17 : use serde::{Deserialize, Serialize};
18 : use tokio::{
19 : task::{JoinError, JoinHandle},
20 : time::Instant,
21 : };
22 : use tokio_util::sync::CancellationToken;
23 : use tracing::{debug, info, info_span, instrument, warn, Instrument};
24 : use utils::lsn::Lsn;
25 :
26 : use crate::{
27 : control_file::{FileStorage, Storage},
28 : metrics::{MANAGER_ACTIVE_CHANGES, MANAGER_ITERATIONS_TOTAL, MISC_OPERATION_SECONDS},
29 : rate_limit::{rand_duration, RateLimiter},
30 : recovery::recovery_main,
31 : remove_wal::calc_horizon_lsn,
32 : safekeeper::Term,
33 : send_wal::WalSenders,
34 : state::TimelineState,
35 : timeline::{ManagerTimeline, PeerInfo, ReadGuardSharedState, StateSK, WalResidentTimeline},
36 : timeline_guard::{AccessService, GuardId, ResidenceGuard},
37 : timelines_set::{TimelineSetGuard, TimelinesSet},
38 : wal_backup::{self, WalBackupTaskHandle},
39 : wal_backup_partial::{self, PartialBackup, PartialRemoteSegment},
40 : SafeKeeperConf,
41 : };
42 :
43 : pub(crate) struct StateSnapshot {
44 : // inmem values
45 : pub(crate) commit_lsn: Lsn,
46 : pub(crate) backup_lsn: Lsn,
47 : pub(crate) remote_consistent_lsn: Lsn,
48 :
49 : // persistent control file values
50 : pub(crate) cfile_peer_horizon_lsn: Lsn,
51 : pub(crate) cfile_remote_consistent_lsn: Lsn,
52 : pub(crate) cfile_backup_lsn: Lsn,
53 :
54 : // latest state
55 : pub(crate) flush_lsn: Lsn,
56 : pub(crate) last_log_term: Term,
57 :
58 : // misc
59 : pub(crate) cfile_last_persist_at: std::time::Instant,
60 : pub(crate) inmem_flush_pending: bool,
61 : pub(crate) wal_removal_on_hold: bool,
62 : pub(crate) peers: Vec<PeerInfo>,
63 : }
64 :
65 : impl StateSnapshot {
66 : /// Create a new snapshot of the timeline state.
67 0 : fn new(read_guard: ReadGuardSharedState, heartbeat_timeout: Duration) -> Self {
68 0 : let state = read_guard.sk.state();
69 0 : Self {
70 0 : commit_lsn: state.inmem.commit_lsn,
71 0 : backup_lsn: state.inmem.backup_lsn,
72 0 : remote_consistent_lsn: state.inmem.remote_consistent_lsn,
73 0 : cfile_peer_horizon_lsn: state.peer_horizon_lsn,
74 0 : cfile_remote_consistent_lsn: state.remote_consistent_lsn,
75 0 : cfile_backup_lsn: state.backup_lsn,
76 0 : flush_lsn: read_guard.sk.flush_lsn(),
77 0 : last_log_term: read_guard.sk.last_log_term(),
78 0 : cfile_last_persist_at: state.pers.last_persist_at(),
79 0 : inmem_flush_pending: Self::has_unflushed_inmem_state(state),
80 0 : wal_removal_on_hold: read_guard.wal_removal_on_hold,
81 0 : peers: read_guard.get_peers(heartbeat_timeout),
82 0 : }
83 0 : }
84 :
85 0 : fn has_unflushed_inmem_state(state: &TimelineState<FileStorage>) -> bool {
86 0 : state.inmem.commit_lsn > state.commit_lsn
87 0 : || state.inmem.backup_lsn > state.backup_lsn
88 0 : || state.inmem.peer_horizon_lsn > state.peer_horizon_lsn
89 0 : || state.inmem.remote_consistent_lsn > state.remote_consistent_lsn
90 0 : }
91 : }
92 :
93 : /// Control how often the manager task should wake up to check updates.
94 : /// There is no need to check for updates more often than this.
95 : const REFRESH_INTERVAL: Duration = Duration::from_millis(300);
96 :
97 : pub enum ManagerCtlMessage {
98 : /// Request to get a guard for WalResidentTimeline, with WAL files available locally.
99 : GuardRequest(tokio::sync::oneshot::Sender<anyhow::Result<ResidenceGuard>>),
100 : /// Request to drop the guard.
101 : GuardDrop(GuardId),
102 : /// Request to reset uploaded partial backup state.
103 : BackupPartialReset(oneshot::Sender<anyhow::Result<Vec<String>>>),
104 : }
105 :
106 : impl std::fmt::Debug for ManagerCtlMessage {
107 0 : fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
108 0 : match self {
109 0 : ManagerCtlMessage::GuardRequest(_) => write!(f, "GuardRequest"),
110 0 : ManagerCtlMessage::GuardDrop(id) => write!(f, "GuardDrop({:?})", id),
111 0 : ManagerCtlMessage::BackupPartialReset(_) => write!(f, "BackupPartialReset"),
112 : }
113 0 : }
114 : }
115 :
116 : pub struct ManagerCtl {
117 : manager_tx: tokio::sync::mpsc::UnboundedSender<ManagerCtlMessage>,
118 :
119 : // this is used to initialize manager, it will be moved out in bootstrap().
120 : init_manager_rx:
121 : std::sync::Mutex<Option<tokio::sync::mpsc::UnboundedReceiver<ManagerCtlMessage>>>,
122 : }
123 :
124 : impl Default for ManagerCtl {
125 0 : fn default() -> Self {
126 0 : Self::new()
127 0 : }
128 : }
129 :
130 : impl ManagerCtl {
131 0 : pub fn new() -> Self {
132 0 : let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
133 0 : Self {
134 0 : manager_tx: tx,
135 0 : init_manager_rx: std::sync::Mutex::new(Some(rx)),
136 0 : }
137 0 : }
138 :
139 : /// Issue a new guard and wait for manager to prepare the timeline.
140 : /// Sends a message to the manager and waits for the response.
141 : /// Can be blocked indefinitely if the manager is stuck.
142 0 : pub async fn wal_residence_guard(&self) -> anyhow::Result<ResidenceGuard> {
143 0 : let (tx, rx) = tokio::sync::oneshot::channel();
144 0 : self.manager_tx.send(ManagerCtlMessage::GuardRequest(tx))?;
145 :
146 : // wait for the manager to respond with the guard
147 0 : rx.await
148 0 : .map_err(|e| anyhow::anyhow!("response read fail: {:?}", e))
149 0 : .and_then(std::convert::identity)
150 0 : }
151 :
152 : /// Request timeline manager to reset uploaded partial segment state and
153 : /// wait for the result.
154 0 : pub async fn backup_partial_reset(&self) -> anyhow::Result<Vec<String>> {
155 0 : let (tx, rx) = oneshot::channel();
156 0 : self.manager_tx
157 0 : .send(ManagerCtlMessage::BackupPartialReset(tx))
158 0 : .expect("manager task is not running");
159 0 : match rx.await {
160 0 : Ok(res) => res,
161 0 : Err(_) => anyhow::bail!("timeline manager is gone"),
162 : }
163 0 : }
164 :
165 : /// Must be called exactly once to bootstrap the manager.
166 0 : pub fn bootstrap_manager(
167 0 : &self,
168 0 : ) -> (
169 0 : tokio::sync::mpsc::UnboundedSender<ManagerCtlMessage>,
170 0 : tokio::sync::mpsc::UnboundedReceiver<ManagerCtlMessage>,
171 0 : ) {
172 0 : let rx = self
173 0 : .init_manager_rx
174 0 : .lock()
175 0 : .expect("mutex init_manager_rx poisoned")
176 0 : .take()
177 0 : .expect("manager already bootstrapped");
178 0 :
179 0 : (self.manager_tx.clone(), rx)
180 0 : }
181 : }
182 :
183 : pub(crate) struct Manager {
184 : // configuration & dependencies
185 : pub(crate) tli: ManagerTimeline,
186 : pub(crate) conf: SafeKeeperConf,
187 : pub(crate) wal_seg_size: usize,
188 : pub(crate) walsenders: Arc<WalSenders>,
189 :
190 : // current state
191 : pub(crate) state_version_rx: tokio::sync::watch::Receiver<usize>,
192 : pub(crate) num_computes_rx: tokio::sync::watch::Receiver<usize>,
193 : pub(crate) tli_broker_active: TimelineSetGuard,
194 : pub(crate) last_removed_segno: XLogSegNo,
195 : pub(crate) is_offloaded: bool,
196 :
197 : // background tasks
198 : pub(crate) backup_task: Option<WalBackupTaskHandle>,
199 : pub(crate) recovery_task: Option<JoinHandle<()>>,
200 : pub(crate) wal_removal_task: Option<JoinHandle<anyhow::Result<u64>>>,
201 :
202 : // partial backup
203 : pub(crate) partial_backup_task:
204 : Option<(JoinHandle<Option<PartialRemoteSegment>>, CancellationToken)>,
205 : pub(crate) partial_backup_uploaded: Option<PartialRemoteSegment>,
206 :
207 : // misc
208 : pub(crate) access_service: AccessService,
209 : pub(crate) global_rate_limiter: RateLimiter,
210 :
211 : // Anti-flapping state: we evict timelines eagerly if they are inactive, but should not
212 : // evict them if they go inactive very soon after being restored.
213 : pub(crate) evict_not_before: Instant,
214 : }
215 :
216 : /// This task gets spawned alongside each timeline and is responsible for managing the timeline's
217 : /// background tasks.
218 : /// Be careful, this task is not respawned on panic, so it should not panic.
219 0 : #[instrument(name = "manager", skip_all, fields(ttid = %tli.ttid))]
220 : pub async fn main_task(
221 : tli: ManagerTimeline,
222 : conf: SafeKeeperConf,
223 : broker_active_set: Arc<TimelinesSet>,
224 : manager_tx: tokio::sync::mpsc::UnboundedSender<ManagerCtlMessage>,
225 : mut manager_rx: tokio::sync::mpsc::UnboundedReceiver<ManagerCtlMessage>,
226 : global_rate_limiter: RateLimiter,
227 : ) {
228 : tli.set_status(Status::Started);
229 :
230 : let defer_tli = tli.tli.clone();
231 : scopeguard::defer! {
232 : if defer_tli.is_cancelled() {
233 : info!("manager task finished");
234 : } else {
235 : warn!("manager task finished prematurely");
236 : }
237 : };
238 :
239 : let mut mgr = Manager::new(
240 : tli,
241 : conf,
242 : broker_active_set,
243 : manager_tx,
244 : global_rate_limiter,
245 : )
246 : .await;
247 :
248 : // Start recovery task which always runs on the timeline.
249 : if !mgr.is_offloaded && mgr.conf.peer_recovery_enabled {
250 : let tli = mgr.wal_resident_timeline();
251 : mgr.recovery_task = Some(tokio::spawn(recovery_main(tli, mgr.conf.clone())));
252 : }
253 :
254 : let last_state = 'outer: loop {
255 : MANAGER_ITERATIONS_TOTAL.inc();
256 :
257 : mgr.set_status(Status::StateSnapshot);
258 : let state_snapshot = mgr.state_snapshot().await;
259 :
260 : let mut next_event: Option<Instant> = None;
261 : if !mgr.is_offloaded {
262 : let num_computes = *mgr.num_computes_rx.borrow();
263 :
264 : mgr.set_status(Status::UpdateBackup);
265 : let is_wal_backup_required = mgr.update_backup(num_computes, &state_snapshot).await;
266 : mgr.update_is_active(is_wal_backup_required, num_computes, &state_snapshot);
267 :
268 : mgr.set_status(Status::UpdateControlFile);
269 : mgr.update_control_file_save(&state_snapshot, &mut next_event)
270 : .await;
271 :
272 : mgr.set_status(Status::UpdateWalRemoval);
273 : mgr.update_wal_removal(&state_snapshot).await;
274 :
275 : mgr.set_status(Status::UpdatePartialBackup);
276 : mgr.update_partial_backup(&state_snapshot).await;
277 :
278 : let now = Instant::now();
279 : if mgr.evict_not_before > now {
280 : // we should wait until evict_not_before
281 : update_next_event(&mut next_event, mgr.evict_not_before);
282 : }
283 :
284 : if mgr.conf.enable_offload
285 : && mgr.evict_not_before <= now
286 : && mgr.ready_for_eviction(&next_event, &state_snapshot)
287 : {
288 : // check rate limiter and evict timeline if possible
289 : match mgr.global_rate_limiter.try_acquire_eviction() {
290 : Some(_permit) => {
291 : mgr.set_status(Status::EvictTimeline);
292 : mgr.evict_timeline().await;
293 : }
294 : None => {
295 : // we can't evict timeline now, will try again later
296 : mgr.evict_not_before =
297 : Instant::now() + rand_duration(&mgr.conf.eviction_min_resident);
298 : update_next_event(&mut next_event, mgr.evict_not_before);
299 : }
300 : }
301 : }
302 : }
303 :
304 : mgr.set_status(Status::Wait);
305 : // wait until something changes. tx channels are stored under Arc, so they will not be
306 : // dropped until the manager task is finished.
307 : tokio::select! {
308 : _ = mgr.tli.cancel.cancelled() => {
309 : // timeline was deleted
310 : break 'outer state_snapshot;
311 : }
312 0 : _ = async {
313 0 : // don't wake up on every state change, but at most every REFRESH_INTERVAL
314 0 : tokio::time::sleep(REFRESH_INTERVAL).await;
315 0 : let _ = mgr.state_version_rx.changed().await;
316 0 : } => {
317 : // state was updated
318 : }
319 : _ = mgr.num_computes_rx.changed() => {
320 : // number of connected computes was updated
321 : }
322 : _ = sleep_until(&next_event) => {
323 : // we were waiting for some event (e.g. cfile save)
324 : }
325 : res = await_task_finish(mgr.wal_removal_task.as_mut()) => {
326 : // WAL removal task finished
327 : mgr.wal_removal_task = None;
328 : mgr.update_wal_removal_end(res);
329 : }
330 0 : res = await_task_finish(mgr.partial_backup_task.as_mut().map(|(handle, _)| handle)) => {
331 : // partial backup task finished
332 : mgr.partial_backup_task = None;
333 : mgr.update_partial_backup_end(res);
334 : }
335 :
336 : msg = manager_rx.recv() => {
337 : mgr.set_status(Status::HandleMessage);
338 : mgr.handle_message(msg).await;
339 : }
340 : }
341 : };
342 : mgr.set_status(Status::Exiting);
343 :
344 : // remove timeline from the broker active set sooner, before waiting for background tasks
345 : mgr.tli_broker_active.set(false);
346 :
347 : // shutdown background tasks
348 : if mgr.conf.is_wal_backup_enabled() {
349 : wal_backup::update_task(&mut mgr, false, &last_state).await;
350 : }
351 :
352 : if let Some(recovery_task) = &mut mgr.recovery_task {
353 : if let Err(e) = recovery_task.await {
354 : warn!("recovery task failed: {:?}", e);
355 : }
356 : }
357 :
358 : if let Some((handle, cancel)) = &mut mgr.partial_backup_task {
359 : cancel.cancel();
360 : if let Err(e) = handle.await {
361 : warn!("partial backup task failed: {:?}", e);
362 : }
363 : }
364 :
365 : if let Some(wal_removal_task) = &mut mgr.wal_removal_task {
366 : let res = wal_removal_task.await;
367 : mgr.update_wal_removal_end(res);
368 : }
369 :
370 : mgr.set_status(Status::Finished);
371 : }
372 :
373 : impl Manager {
374 0 : async fn new(
375 0 : tli: ManagerTimeline,
376 0 : conf: SafeKeeperConf,
377 0 : broker_active_set: Arc<TimelinesSet>,
378 0 : manager_tx: tokio::sync::mpsc::UnboundedSender<ManagerCtlMessage>,
379 0 : global_rate_limiter: RateLimiter,
380 0 : ) -> Manager {
381 0 : let (is_offloaded, partial_backup_uploaded) = tli.bootstrap_mgr().await;
382 : Manager {
383 0 : wal_seg_size: tli.get_wal_seg_size().await,
384 0 : walsenders: tli.get_walsenders().clone(),
385 0 : state_version_rx: tli.get_state_version_rx(),
386 0 : num_computes_rx: tli.get_walreceivers().get_num_rx(),
387 0 : tli_broker_active: broker_active_set.guard(tli.clone()),
388 0 : last_removed_segno: 0,
389 0 : is_offloaded,
390 0 : backup_task: None,
391 0 : recovery_task: None,
392 0 : wal_removal_task: None,
393 0 : partial_backup_task: None,
394 0 : partial_backup_uploaded,
395 0 : access_service: AccessService::new(manager_tx),
396 0 : tli,
397 0 : global_rate_limiter,
398 0 : // to smooth out evictions spike after restart
399 0 : evict_not_before: Instant::now() + rand_duration(&conf.eviction_min_resident),
400 0 : conf,
401 0 : }
402 0 : }
403 :
404 0 : fn set_status(&self, status: Status) {
405 0 : self.tli.set_status(status);
406 0 : }
407 :
408 : /// Get a WalResidentTimeline.
409 : /// Manager code must use this function instead of one from `Timeline`
410 : /// directly, because it will deadlock.
411 0 : pub(crate) fn wal_resident_timeline(&mut self) -> WalResidentTimeline {
412 0 : assert!(!self.is_offloaded);
413 0 : let guard = self.access_service.create_guard();
414 0 : WalResidentTimeline::new(self.tli.clone(), guard)
415 0 : }
416 :
417 : /// Get a snapshot of the timeline state.
418 0 : async fn state_snapshot(&self) -> StateSnapshot {
419 0 : let _timer = MISC_OPERATION_SECONDS
420 0 : .with_label_values(&["state_snapshot"])
421 0 : .start_timer();
422 0 :
423 0 : StateSnapshot::new(
424 0 : self.tli.read_shared_state().await,
425 0 : self.conf.heartbeat_timeout,
426 0 : )
427 0 : }
428 :
429 : /// Spawns/kills backup task and returns true if backup is required.
430 0 : async fn update_backup(&mut self, num_computes: usize, state: &StateSnapshot) -> bool {
431 0 : let is_wal_backup_required =
432 0 : wal_backup::is_wal_backup_required(self.wal_seg_size, num_computes, state);
433 0 :
434 0 : if self.conf.is_wal_backup_enabled() {
435 0 : wal_backup::update_task(self, is_wal_backup_required, state).await;
436 0 : }
437 :
438 : // update the state in Arc<Timeline>
439 0 : self.tli.wal_backup_active.store(
440 0 : self.backup_task.is_some(),
441 0 : std::sync::atomic::Ordering::Relaxed,
442 0 : );
443 0 : is_wal_backup_required
444 0 : }
445 :
446 : /// Update is_active flag and returns its value.
447 0 : fn update_is_active(
448 0 : &mut self,
449 0 : is_wal_backup_required: bool,
450 0 : num_computes: usize,
451 0 : state: &StateSnapshot,
452 0 : ) {
453 0 : let is_active = is_wal_backup_required
454 0 : || num_computes > 0
455 0 : || state.remote_consistent_lsn < state.commit_lsn;
456 :
457 : // update the broker timeline set
458 0 : if self.tli_broker_active.set(is_active) {
459 : // write log if state has changed
460 0 : info!(
461 0 : "timeline active={} now, remote_consistent_lsn={}, commit_lsn={}",
462 : is_active, state.remote_consistent_lsn, state.commit_lsn,
463 : );
464 :
465 0 : MANAGER_ACTIVE_CHANGES.inc();
466 0 : }
467 :
468 : // update the state in Arc<Timeline>
469 0 : self.tli
470 0 : .broker_active
471 0 : .store(is_active, std::sync::atomic::Ordering::Relaxed);
472 0 : }
473 :
474 : /// Save control file if needed. Returns Instant if we should persist the control file in the future.
475 0 : async fn update_control_file_save(
476 0 : &self,
477 0 : state: &StateSnapshot,
478 0 : next_event: &mut Option<Instant>,
479 0 : ) {
480 0 : if !state.inmem_flush_pending {
481 0 : return;
482 0 : }
483 0 :
484 0 : if state.cfile_last_persist_at.elapsed() > self.conf.control_file_save_interval {
485 0 : let mut write_guard = self.tli.write_shared_state().await;
486 : // it should be done in the background because it blocks manager task, but flush() should
487 : // be fast enough not to be a problem now
488 0 : if let Err(e) = write_guard.sk.state_mut().flush().await {
489 0 : warn!("failed to save control file: {:?}", e);
490 0 : }
491 0 : } else {
492 0 : // we should wait until some time passed until the next save
493 0 : update_next_event(
494 0 : next_event,
495 0 : (state.cfile_last_persist_at + self.conf.control_file_save_interval).into(),
496 0 : );
497 0 : }
498 0 : }
499 :
500 : /// Spawns WAL removal task if needed.
501 0 : async fn update_wal_removal(&mut self, state: &StateSnapshot) {
502 0 : if self.wal_removal_task.is_some() || state.wal_removal_on_hold {
503 : // WAL removal is already in progress or hold off
504 0 : return;
505 0 : }
506 :
507 : // If enabled, we use LSN of the most lagging walsender as a WAL removal horizon.
508 : // This allows to get better read speed for pageservers that are lagging behind,
509 : // at the cost of keeping more WAL on disk.
510 0 : let replication_horizon_lsn = if self.conf.walsenders_keep_horizon {
511 0 : self.walsenders.laggard_lsn()
512 : } else {
513 0 : None
514 : };
515 :
516 0 : let removal_horizon_lsn = calc_horizon_lsn(state, replication_horizon_lsn);
517 0 : let removal_horizon_segno = removal_horizon_lsn
518 0 : .segment_number(self.wal_seg_size)
519 0 : .saturating_sub(1);
520 0 :
521 0 : if removal_horizon_segno > self.last_removed_segno {
522 : // we need to remove WAL
523 0 : let remover = match self.tli.read_shared_state().await.sk {
524 0 : StateSK::Loaded(ref sk) => {
525 0 : crate::wal_storage::Storage::remove_up_to(&sk.wal_store, removal_horizon_segno)
526 : }
527 : StateSK::Offloaded(_) => {
528 : // we can't remove WAL if it's not loaded
529 0 : warn!("unexpectedly trying to run WAL removal on offloaded timeline");
530 0 : return;
531 : }
532 0 : StateSK::Empty => unreachable!(),
533 : };
534 :
535 0 : self.wal_removal_task = Some(tokio::spawn(
536 0 : async move {
537 0 : remover.await?;
538 0 : Ok(removal_horizon_segno)
539 0 : }
540 0 : .instrument(info_span!("WAL removal", ttid=%self.tli.ttid)),
541 : ));
542 0 : }
543 0 : }
544 :
545 : /// Update the state after WAL removal task finished.
546 0 : fn update_wal_removal_end(&mut self, res: Result<anyhow::Result<u64>, JoinError>) {
547 0 : let new_last_removed_segno = match res {
548 0 : Ok(Ok(segno)) => segno,
549 0 : Err(e) => {
550 0 : warn!("WAL removal task failed: {:?}", e);
551 0 : return;
552 : }
553 0 : Ok(Err(e)) => {
554 0 : warn!("WAL removal task failed: {:?}", e);
555 0 : return;
556 : }
557 : };
558 :
559 0 : self.last_removed_segno = new_last_removed_segno;
560 0 : // update the state in Arc<Timeline>
561 0 : self.tli
562 0 : .last_removed_segno
563 0 : .store(new_last_removed_segno, std::sync::atomic::Ordering::Relaxed);
564 0 : }
565 :
566 : /// Spawns partial WAL backup task if needed.
567 0 : async fn update_partial_backup(&mut self, state: &StateSnapshot) {
568 0 : // check if WAL backup is enabled and should be started
569 0 : if !self.conf.is_wal_backup_enabled() {
570 0 : return;
571 0 : }
572 0 :
573 0 : if self.partial_backup_task.is_some() {
574 : // partial backup is already running
575 0 : return;
576 0 : }
577 0 :
578 0 : if !wal_backup_partial::needs_uploading(state, &self.partial_backup_uploaded) {
579 : // nothing to upload
580 0 : return;
581 0 : }
582 0 :
583 0 : // Get WalResidentTimeline and start partial backup task.
584 0 : let cancel = CancellationToken::new();
585 0 : let handle = tokio::spawn(wal_backup_partial::main_task(
586 0 : self.wal_resident_timeline(),
587 0 : self.conf.clone(),
588 0 : self.global_rate_limiter.clone(),
589 0 : cancel.clone(),
590 0 : ));
591 0 : self.partial_backup_task = Some((handle, cancel));
592 0 : }
593 :
594 : /// Update the state after partial WAL backup task finished.
595 0 : fn update_partial_backup_end(&mut self, res: Result<Option<PartialRemoteSegment>, JoinError>) {
596 0 : match res {
597 0 : Ok(new_upload_state) => {
598 0 : self.partial_backup_uploaded = new_upload_state;
599 0 : }
600 0 : Err(e) => {
601 0 : warn!("partial backup task panicked: {:?}", e);
602 : }
603 : }
604 0 : }
605 :
606 : /// Reset partial backup state and remove its remote storage data. Since it
607 : /// might concurrently uploading something, cancel the task first.
608 0 : async fn backup_partial_reset(&mut self) -> anyhow::Result<Vec<String>> {
609 0 : info!("resetting partial backup state");
610 : // Force unevict timeline if it is evicted before erasing partial backup
611 : // state. The intended use of this function is to drop corrupted remote
612 : // state; we haven't enabled local files deletion yet anywhere,
613 : // so direct switch is safe.
614 0 : if self.is_offloaded {
615 0 : self.tli.switch_to_present().await?;
616 : // switch manager state as soon as possible
617 0 : self.is_offloaded = false;
618 0 : }
619 :
620 0 : if let Some((handle, cancel)) = &mut self.partial_backup_task {
621 0 : cancel.cancel();
622 0 : info!("cancelled partial backup task, awaiting it");
623 : // we're going to reset .partial_backup_uploaded to None anyway, so ignore the result
624 0 : handle.await.ok();
625 0 : self.partial_backup_task = None;
626 0 : }
627 :
628 0 : let tli = self.wal_resident_timeline();
629 0 : let mut partial_backup = PartialBackup::new(tli, self.conf.clone()).await;
630 : // Reset might fail e.g. when cfile is already reset but s3 removal
631 : // failed, so set manager state to None beforehand. In any case caller
632 : // is expected to retry until success.
633 0 : self.partial_backup_uploaded = None;
634 0 : let res = partial_backup.reset().await?;
635 0 : info!("reset is done");
636 0 : Ok(res)
637 0 : }
638 :
639 : /// Handle message arrived from ManagerCtl.
640 0 : async fn handle_message(&mut self, msg: Option<ManagerCtlMessage>) {
641 0 : debug!("received manager message: {:?}", msg);
642 0 : match msg {
643 0 : Some(ManagerCtlMessage::GuardRequest(tx)) => {
644 0 : if self.is_offloaded {
645 : // trying to unevict timeline, but without gurarantee that it will be successful
646 0 : self.unevict_timeline().await;
647 0 : }
648 :
649 0 : let guard = if self.is_offloaded {
650 0 : Err(anyhow::anyhow!("timeline is offloaded, can't get a guard"))
651 : } else {
652 0 : Ok(self.access_service.create_guard())
653 : };
654 :
655 0 : if tx.send(guard).is_err() {
656 0 : warn!("failed to reply with a guard, receiver dropped");
657 0 : }
658 : }
659 0 : Some(ManagerCtlMessage::GuardDrop(guard_id)) => {
660 0 : self.access_service.drop_guard(guard_id);
661 0 : }
662 0 : Some(ManagerCtlMessage::BackupPartialReset(tx)) => {
663 0 : info!("resetting uploaded partial backup state");
664 0 : let res = self.backup_partial_reset().await;
665 0 : if let Err(ref e) = res {
666 0 : warn!("failed to reset partial backup state: {:?}", e);
667 0 : }
668 0 : if tx.send(res).is_err() {
669 0 : warn!("failed to send partial backup reset result, receiver dropped");
670 0 : }
671 : }
672 : None => {
673 : // can't happen, we're holding the sender
674 0 : unreachable!();
675 : }
676 : }
677 0 : }
678 : }
679 :
680 : // utility functions
681 0 : async fn sleep_until(option: &Option<tokio::time::Instant>) {
682 0 : if let Some(timeout) = option {
683 0 : tokio::time::sleep_until(*timeout).await;
684 : } else {
685 0 : futures::future::pending::<()>().await;
686 : }
687 0 : }
688 :
689 : /// Future that resolves when the task is finished or never if the task is None.
690 : ///
691 : /// Note: it accepts Option<&mut> instead of &mut Option<> because mapping the
692 : /// option to get the latter is hard.
693 0 : async fn await_task_finish<T>(option: Option<&mut JoinHandle<T>>) -> Result<T, JoinError> {
694 0 : if let Some(task) = option {
695 0 : task.await
696 : } else {
697 0 : futures::future::pending().await
698 : }
699 0 : }
700 :
701 : /// Update next_event if candidate is earlier.
702 0 : fn update_next_event(next_event: &mut Option<Instant>, candidate: Instant) {
703 0 : if let Some(next) = next_event {
704 0 : if candidate < *next {
705 0 : *next = candidate;
706 0 : }
707 0 : } else {
708 0 : *next_event = Some(candidate);
709 0 : }
710 0 : }
711 :
712 : #[repr(usize)]
713 0 : #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
714 : pub enum Status {
715 : NotStarted,
716 : Started,
717 : StateSnapshot,
718 : UpdateBackup,
719 : UpdateControlFile,
720 : UpdateWalRemoval,
721 : UpdatePartialBackup,
722 : EvictTimeline,
723 : Wait,
724 : HandleMessage,
725 : Exiting,
726 : Finished,
727 : }
728 :
729 : /// AtomicStatus is a wrapper around AtomicUsize adapted for the Status enum.
730 : pub struct AtomicStatus {
731 : inner: AtomicUsize,
732 : }
733 :
734 : impl Default for AtomicStatus {
735 0 : fn default() -> Self {
736 0 : Self::new()
737 0 : }
738 : }
739 :
740 : impl AtomicStatus {
741 0 : pub fn new() -> Self {
742 0 : AtomicStatus {
743 0 : inner: AtomicUsize::new(Status::NotStarted as usize),
744 0 : }
745 0 : }
746 :
747 0 : pub fn load(&self, order: std::sync::atomic::Ordering) -> Status {
748 0 : // Safety: This line of code uses `std::mem::transmute` to reinterpret the loaded value as `Status`.
749 0 : // It is safe to use `transmute` in this context because `Status` is a repr(usize) enum,
750 0 : // which means it has the same memory layout as usize.
751 0 : // However, it is important to ensure that the loaded value is a valid variant of `Status`,
752 0 : // otherwise, the behavior will be undefined.
753 0 : unsafe { std::mem::transmute(self.inner.load(order)) }
754 0 : }
755 :
756 0 : pub fn get(&self) -> Status {
757 0 : self.load(std::sync::atomic::Ordering::Relaxed)
758 0 : }
759 :
760 0 : pub fn store(&self, val: Status, order: std::sync::atomic::Ordering) {
761 0 : self.inner.store(val as usize, order);
762 0 : }
763 : }
|