LCOV - code coverage report
Current view: top level - safekeeper/src - timeline_manager.rs (source / functions) Coverage Total Hit
Test: b9d67f908f91f00e353a27440ba89f642a869959.info Lines: 0.0 % 354 0
Test Date: 2024-11-19 21:44:13 Functions: 0.0 % 59 0

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

Generated by: LCOV version 2.1-beta