LCOV - code coverage report
Current view: top level - safekeeper/src - timeline_manager.rs (source / functions) Coverage Total Hit
Test: 8ff8efadb0253cf618c612650348666c0c564111.info Lines: 0.0 % 369 0
Test Date: 2024-11-20 17:53:50 Functions: 0.0 % 60 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              :         // Recovery task is only spawned if we can get a residence guard (i.e. timeline is not already shutting down)
     270              :         if let Ok(tli) = mgr.wal_resident_timeline() {
     271              :             mgr.recovery_task = Some(tokio::spawn(recovery_main(tli, mgr.conf.clone())));
     272              :         }
     273              :     }
     274              : 
     275              :     // If timeline is evicted, reflect that in the metric.
     276              :     if mgr.is_offloaded {
     277              :         NUM_EVICTED_TIMELINES.inc();
     278              :     }
     279              : 
     280              :     let last_state = 'outer: loop {
     281              :         MANAGER_ITERATIONS_TOTAL.inc();
     282              : 
     283              :         mgr.set_status(Status::StateSnapshot);
     284              :         let state_snapshot = mgr.state_snapshot().await;
     285              : 
     286              :         let mut next_event: Option<Instant> = None;
     287              :         if !mgr.is_offloaded {
     288              :             let num_computes = *mgr.num_computes_rx.borrow();
     289              : 
     290              :             mgr.set_status(Status::UpdateBackup);
     291              :             let is_wal_backup_required = mgr.update_backup(num_computes, &state_snapshot).await;
     292              :             mgr.update_is_active(is_wal_backup_required, num_computes, &state_snapshot);
     293              : 
     294              :             mgr.set_status(Status::UpdateControlFile);
     295              :             mgr.update_control_file_save(&state_snapshot, &mut next_event)
     296              :                 .await;
     297              : 
     298              :             mgr.set_status(Status::UpdateWalRemoval);
     299              :             mgr.update_wal_removal(&state_snapshot).await;
     300              : 
     301              :             mgr.set_status(Status::UpdatePartialBackup);
     302              :             mgr.update_partial_backup(&state_snapshot).await;
     303              : 
     304              :             let now = Instant::now();
     305              :             if mgr.evict_not_before > now {
     306              :                 // we should wait until evict_not_before
     307              :                 update_next_event(&mut next_event, mgr.evict_not_before);
     308              :             }
     309              : 
     310              :             if mgr.conf.enable_offload
     311              :                 && mgr.evict_not_before <= now
     312              :                 && mgr.ready_for_eviction(&next_event, &state_snapshot)
     313              :             {
     314              :                 // check rate limiter and evict timeline if possible
     315              :                 match mgr.global_rate_limiter.try_acquire_eviction() {
     316              :                     Some(_permit) => {
     317              :                         mgr.set_status(Status::EvictTimeline);
     318              :                         if !mgr.evict_timeline().await {
     319              :                             // eviction failed, try again later
     320              :                             mgr.evict_not_before =
     321              :                                 Instant::now() + rand_duration(&mgr.conf.eviction_min_resident);
     322              :                             update_next_event(&mut next_event, mgr.evict_not_before);
     323              :                         }
     324              :                     }
     325              :                     None => {
     326              :                         // we can't evict timeline now, will try again later
     327              :                         mgr.evict_not_before =
     328              :                             Instant::now() + rand_duration(&mgr.conf.eviction_min_resident);
     329              :                         update_next_event(&mut next_event, mgr.evict_not_before);
     330              :                     }
     331              :                 }
     332              :             }
     333              :         }
     334              : 
     335              :         mgr.set_status(Status::Wait);
     336              :         // wait until something changes. tx channels are stored under Arc, so they will not be
     337              :         // dropped until the manager task is finished.
     338              :         tokio::select! {
     339              :             _ = mgr.tli.cancel.cancelled() => {
     340              :                 // timeline was deleted
     341              :                 break 'outer state_snapshot;
     342              :             }
     343            0 :             _ = async {
     344            0 :                 // don't wake up on every state change, but at most every REFRESH_INTERVAL
     345            0 :                 tokio::time::sleep(REFRESH_INTERVAL).await;
     346            0 :                 let _ = mgr.state_version_rx.changed().await;
     347            0 :             } => {
     348              :                 // state was updated
     349              :             }
     350              :             _ = mgr.num_computes_rx.changed() => {
     351              :                 // number of connected computes was updated
     352              :             }
     353              :             _ = sleep_until(&next_event) => {
     354              :                 // we were waiting for some event (e.g. cfile save)
     355              :             }
     356              :             res = await_task_finish(mgr.wal_removal_task.as_mut()) => {
     357              :                 // WAL removal task finished
     358              :                 mgr.wal_removal_task = None;
     359              :                 mgr.update_wal_removal_end(res);
     360              :             }
     361            0 :             res = await_task_finish(mgr.partial_backup_task.as_mut().map(|(handle, _)| handle)) => {
     362              :                 // partial backup task finished
     363              :                 mgr.partial_backup_task = None;
     364              :                 mgr.update_partial_backup_end(res);
     365              :             }
     366              : 
     367              :             msg = manager_rx.recv() => {
     368              :                 mgr.set_status(Status::HandleMessage);
     369              :                 mgr.handle_message(msg).await;
     370              :             }
     371              :         }
     372              :     };
     373              :     mgr.set_status(Status::Exiting);
     374              : 
     375              :     // remove timeline from the broker active set sooner, before waiting for background tasks
     376              :     mgr.tli_broker_active.set(false);
     377              : 
     378              :     // shutdown background tasks
     379              :     if mgr.conf.is_wal_backup_enabled() {
     380              :         if let Some(backup_task) = mgr.backup_task.take() {
     381              :             // If we fell through here, then the timeline is shutting down. This is important
     382              :             // because otherwise joining on the wal_backup handle might hang.
     383              :             assert!(mgr.tli.cancel.is_cancelled());
     384              : 
     385              :             backup_task.join().await;
     386              :         }
     387              :         wal_backup::update_task(&mut mgr, false, &last_state).await;
     388              :     }
     389              : 
     390              :     if let Some(recovery_task) = &mut mgr.recovery_task {
     391              :         if let Err(e) = recovery_task.await {
     392              :             warn!("recovery task failed: {:?}", e);
     393              :         }
     394              :     }
     395              : 
     396              :     if let Some((handle, cancel)) = &mut mgr.partial_backup_task {
     397              :         cancel.cancel();
     398              :         if let Err(e) = handle.await {
     399              :             warn!("partial backup task failed: {:?}", e);
     400              :         }
     401              :     }
     402              : 
     403              :     if let Some(wal_removal_task) = &mut mgr.wal_removal_task {
     404              :         let res = wal_removal_task.await;
     405              :         mgr.update_wal_removal_end(res);
     406              :     }
     407              : 
     408              :     // If timeline is deleted while evicted decrement the gauge.
     409              :     if mgr.tli.is_cancelled() && mgr.is_offloaded {
     410              :         NUM_EVICTED_TIMELINES.dec();
     411              :     }
     412              : 
     413              :     mgr.set_status(Status::Finished);
     414              : }
     415              : 
     416              : impl Manager {
     417            0 :     async fn new(
     418            0 :         tli: ManagerTimeline,
     419            0 :         conf: SafeKeeperConf,
     420            0 :         broker_active_set: Arc<TimelinesSet>,
     421            0 :         manager_tx: tokio::sync::mpsc::UnboundedSender<ManagerCtlMessage>,
     422            0 :         global_rate_limiter: RateLimiter,
     423            0 :     ) -> Manager {
     424            0 :         let (is_offloaded, partial_backup_uploaded) = tli.bootstrap_mgr().await;
     425              :         Manager {
     426            0 :             wal_seg_size: tli.get_wal_seg_size().await,
     427            0 :             walsenders: tli.get_walsenders().clone(),
     428            0 :             state_version_rx: tli.get_state_version_rx(),
     429            0 :             num_computes_rx: tli.get_walreceivers().get_num_rx(),
     430            0 :             tli_broker_active: broker_active_set.guard(tli.clone()),
     431            0 :             last_removed_segno: 0,
     432            0 :             is_offloaded,
     433            0 :             backup_task: None,
     434            0 :             recovery_task: None,
     435            0 :             wal_removal_task: None,
     436            0 :             partial_backup_task: None,
     437            0 :             partial_backup_uploaded,
     438            0 :             access_service: AccessService::new(manager_tx),
     439            0 :             tli,
     440            0 :             global_rate_limiter,
     441            0 :             // to smooth out evictions spike after restart
     442            0 :             evict_not_before: Instant::now() + rand_duration(&conf.eviction_min_resident),
     443            0 :             conf,
     444            0 :         }
     445            0 :     }
     446              : 
     447            0 :     fn set_status(&self, status: Status) {
     448            0 :         self.tli.set_status(status);
     449            0 :     }
     450              : 
     451              :     /// Get a WalResidentTimeline.
     452              :     /// Manager code must use this function instead of one from `Timeline`
     453              :     /// directly, because it will deadlock.
     454              :     ///
     455              :     /// This function is fallible because the guard may not be created if the timeline is
     456              :     /// shutting down.
     457            0 :     pub(crate) fn wal_resident_timeline(&mut self) -> anyhow::Result<WalResidentTimeline> {
     458            0 :         assert!(!self.is_offloaded);
     459            0 :         let guard = self.access_service.create_guard(
     460            0 :             self.tli
     461            0 :                 .gate
     462            0 :                 .enter()
     463            0 :                 .map_err(|_| anyhow::anyhow!("Timeline shutting down"))?,
     464              :         );
     465            0 :         Ok(WalResidentTimeline::new(self.tli.clone(), guard))
     466            0 :     }
     467              : 
     468              :     /// Get a snapshot of the timeline state.
     469            0 :     async fn state_snapshot(&self) -> StateSnapshot {
     470            0 :         let _timer = MISC_OPERATION_SECONDS
     471            0 :             .with_label_values(&["state_snapshot"])
     472            0 :             .start_timer();
     473            0 : 
     474            0 :         StateSnapshot::new(
     475            0 :             self.tli.read_shared_state().await,
     476            0 :             self.conf.heartbeat_timeout,
     477            0 :         )
     478            0 :     }
     479              : 
     480              :     /// Spawns/kills backup task and returns true if backup is required.
     481            0 :     async fn update_backup(&mut self, num_computes: usize, state: &StateSnapshot) -> bool {
     482            0 :         let is_wal_backup_required =
     483            0 :             wal_backup::is_wal_backup_required(self.wal_seg_size, num_computes, state);
     484            0 : 
     485            0 :         if self.conf.is_wal_backup_enabled() {
     486            0 :             wal_backup::update_task(self, is_wal_backup_required, state).await;
     487            0 :         }
     488              : 
     489              :         // update the state in Arc<Timeline>
     490            0 :         self.tli.wal_backup_active.store(
     491            0 :             self.backup_task.is_some(),
     492            0 :             std::sync::atomic::Ordering::Relaxed,
     493            0 :         );
     494            0 :         is_wal_backup_required
     495            0 :     }
     496              : 
     497              :     /// Update is_active flag and returns its value.
     498            0 :     fn update_is_active(
     499            0 :         &mut self,
     500            0 :         is_wal_backup_required: bool,
     501            0 :         num_computes: usize,
     502            0 :         state: &StateSnapshot,
     503            0 :     ) {
     504            0 :         let is_active = is_wal_backup_required
     505            0 :             || num_computes > 0
     506            0 :             || state.remote_consistent_lsn < state.commit_lsn;
     507              : 
     508              :         // update the broker timeline set
     509            0 :         if self.tli_broker_active.set(is_active) {
     510              :             // write log if state has changed
     511            0 :             info!(
     512            0 :                 "timeline active={} now, remote_consistent_lsn={}, commit_lsn={}",
     513              :                 is_active, state.remote_consistent_lsn, state.commit_lsn,
     514              :             );
     515              : 
     516            0 :             MANAGER_ACTIVE_CHANGES.inc();
     517            0 :         }
     518              : 
     519              :         // update the state in Arc<Timeline>
     520            0 :         self.tli
     521            0 :             .broker_active
     522            0 :             .store(is_active, std::sync::atomic::Ordering::Relaxed);
     523            0 :     }
     524              : 
     525              :     /// Save control file if needed. Returns Instant if we should persist the control file in the future.
     526            0 :     async fn update_control_file_save(
     527            0 :         &self,
     528            0 :         state: &StateSnapshot,
     529            0 :         next_event: &mut Option<Instant>,
     530            0 :     ) {
     531            0 :         if !state.inmem_flush_pending {
     532            0 :             return;
     533            0 :         }
     534            0 : 
     535            0 :         if state.cfile_last_persist_at.elapsed() > self.conf.control_file_save_interval
     536              :             // If the control file's commit_lsn lags more than one segment behind the current
     537              :             // commit_lsn, flush immediately to limit recovery time in case of a crash. We don't do
     538              :             // this on the WAL ingest hot path since it incurs fsync latency.
     539            0 :             || state.commit_lsn.saturating_sub(state.cfile_commit_lsn).0 >= self.wal_seg_size as u64
     540              :         {
     541            0 :             let mut write_guard = self.tli.write_shared_state().await;
     542              :             // it should be done in the background because it blocks manager task, but flush() should
     543              :             // be fast enough not to be a problem now
     544            0 :             if let Err(e) = write_guard.sk.state_mut().flush().await {
     545            0 :                 warn!("failed to save control file: {:?}", e);
     546            0 :             }
     547            0 :         } else {
     548            0 :             // we should wait until some time passed until the next save
     549            0 :             update_next_event(
     550            0 :                 next_event,
     551            0 :                 (state.cfile_last_persist_at + self.conf.control_file_save_interval).into(),
     552            0 :             );
     553            0 :         }
     554            0 :     }
     555              : 
     556              :     /// Spawns WAL removal task if needed.
     557            0 :     async fn update_wal_removal(&mut self, state: &StateSnapshot) {
     558            0 :         if self.wal_removal_task.is_some() || state.wal_removal_on_hold {
     559              :             // WAL removal is already in progress or hold off
     560            0 :             return;
     561            0 :         }
     562              : 
     563              :         // If enabled, we use LSN of the most lagging walsender as a WAL removal horizon.
     564              :         // This allows to get better read speed for pageservers that are lagging behind,
     565              :         // at the cost of keeping more WAL on disk.
     566            0 :         let replication_horizon_lsn = if self.conf.walsenders_keep_horizon {
     567            0 :             self.walsenders.laggard_lsn()
     568              :         } else {
     569            0 :             None
     570              :         };
     571              : 
     572            0 :         let removal_horizon_lsn = calc_horizon_lsn(state, replication_horizon_lsn);
     573            0 :         let removal_horizon_segno = removal_horizon_lsn
     574            0 :             .segment_number(self.wal_seg_size)
     575            0 :             .saturating_sub(1);
     576            0 : 
     577            0 :         if removal_horizon_segno > self.last_removed_segno {
     578              :             // we need to remove WAL
     579            0 :             let Ok(timeline_gate_guard) = self.tli.gate.enter() else {
     580            0 :                 tracing::info!("Timeline shutdown, not spawning WAL removal task");
     581            0 :                 return;
     582              :             };
     583              : 
     584            0 :             let remover = match self.tli.read_shared_state().await.sk {
     585            0 :                 StateSK::Loaded(ref sk) => {
     586            0 :                     crate::wal_storage::Storage::remove_up_to(&sk.wal_store, removal_horizon_segno)
     587              :                 }
     588              :                 StateSK::Offloaded(_) => {
     589              :                     // we can't remove WAL if it's not loaded
     590            0 :                     warn!("unexpectedly trying to run WAL removal on offloaded timeline");
     591            0 :                     return;
     592              :                 }
     593            0 :                 StateSK::Empty => unreachable!(),
     594              :             };
     595              : 
     596            0 :             self.wal_removal_task = Some(tokio::spawn(
     597            0 :                 async move {
     598            0 :                     let _timeline_gate_guard = timeline_gate_guard;
     599            0 : 
     600            0 :                     remover.await?;
     601            0 :                     Ok(removal_horizon_segno)
     602            0 :                 }
     603            0 :                 .instrument(info_span!("WAL removal", ttid=%self.tli.ttid)),
     604              :             ));
     605            0 :         }
     606            0 :     }
     607              : 
     608              :     /// Update the state after WAL removal task finished.
     609            0 :     fn update_wal_removal_end(&mut self, res: Result<anyhow::Result<u64>, JoinError>) {
     610            0 :         let new_last_removed_segno = match res {
     611            0 :             Ok(Ok(segno)) => segno,
     612            0 :             Err(e) => {
     613            0 :                 warn!("WAL removal task failed: {:?}", e);
     614            0 :                 return;
     615              :             }
     616            0 :             Ok(Err(e)) => {
     617            0 :                 warn!("WAL removal task failed: {:?}", e);
     618            0 :                 return;
     619              :             }
     620              :         };
     621              : 
     622            0 :         self.last_removed_segno = new_last_removed_segno;
     623            0 :         // update the state in Arc<Timeline>
     624            0 :         self.tli
     625            0 :             .last_removed_segno
     626            0 :             .store(new_last_removed_segno, std::sync::atomic::Ordering::Relaxed);
     627            0 :     }
     628              : 
     629              :     /// Spawns partial WAL backup task if needed.
     630            0 :     async fn update_partial_backup(&mut self, state: &StateSnapshot) {
     631            0 :         // check if WAL backup is enabled and should be started
     632            0 :         if !self.conf.is_wal_backup_enabled() {
     633            0 :             return;
     634            0 :         }
     635            0 : 
     636            0 :         if self.partial_backup_task.is_some() {
     637              :             // partial backup is already running
     638            0 :             return;
     639            0 :         }
     640            0 : 
     641            0 :         if !wal_backup_partial::needs_uploading(state, &self.partial_backup_uploaded) {
     642              :             // nothing to upload
     643            0 :             return;
     644            0 :         }
     645              : 
     646            0 :         let Ok(resident) = self.wal_resident_timeline() else {
     647              :             // Shutting down
     648            0 :             return;
     649              :         };
     650              : 
     651              :         // Get WalResidentTimeline and start partial backup task.
     652            0 :         let cancel = CancellationToken::new();
     653            0 :         let handle = tokio::spawn(wal_backup_partial::main_task(
     654            0 :             resident,
     655            0 :             self.conf.clone(),
     656            0 :             self.global_rate_limiter.clone(),
     657            0 :             cancel.clone(),
     658            0 :         ));
     659            0 :         self.partial_backup_task = Some((handle, cancel));
     660            0 :     }
     661              : 
     662              :     /// Update the state after partial WAL backup task finished.
     663            0 :     fn update_partial_backup_end(&mut self, res: Result<Option<PartialRemoteSegment>, JoinError>) {
     664            0 :         match res {
     665            0 :             Ok(new_upload_state) => {
     666            0 :                 self.partial_backup_uploaded = new_upload_state;
     667            0 :             }
     668            0 :             Err(e) => {
     669            0 :                 warn!("partial backup task panicked: {:?}", e);
     670              :             }
     671              :         }
     672            0 :     }
     673              : 
     674              :     /// Reset partial backup state and remove its remote storage data. Since it
     675              :     /// might concurrently uploading something, cancel the task first.
     676            0 :     async fn backup_partial_reset(&mut self) -> anyhow::Result<Vec<String>> {
     677            0 :         info!("resetting partial backup state");
     678              :         // Force unevict timeline if it is evicted before erasing partial backup
     679              :         // state. The intended use of this function is to drop corrupted remote
     680              :         // state; we haven't enabled local files deletion yet anywhere,
     681              :         // so direct switch is safe.
     682            0 :         if self.is_offloaded {
     683            0 :             self.tli.switch_to_present().await?;
     684              :             // switch manager state as soon as possible
     685            0 :             self.is_offloaded = false;
     686            0 :         }
     687              : 
     688            0 :         if let Some((handle, cancel)) = &mut self.partial_backup_task {
     689            0 :             cancel.cancel();
     690            0 :             info!("cancelled partial backup task, awaiting it");
     691              :             // we're going to reset .partial_backup_uploaded to None anyway, so ignore the result
     692            0 :             handle.await.ok();
     693            0 :             self.partial_backup_task = None;
     694            0 :         }
     695              : 
     696            0 :         let tli = self.wal_resident_timeline()?;
     697            0 :         let mut partial_backup = PartialBackup::new(tli, self.conf.clone()).await;
     698              :         // Reset might fail e.g. when cfile is already reset but s3 removal
     699              :         // failed, so set manager state to None beforehand. In any case caller
     700              :         // is expected to retry until success.
     701            0 :         self.partial_backup_uploaded = None;
     702            0 :         let res = partial_backup.reset().await?;
     703            0 :         info!("reset is done");
     704            0 :         Ok(res)
     705            0 :     }
     706              : 
     707              :     /// Handle message arrived from ManagerCtl.
     708            0 :     async fn handle_message(&mut self, msg: Option<ManagerCtlMessage>) {
     709            0 :         debug!("received manager message: {:?}", msg);
     710            0 :         match msg {
     711            0 :             Some(ManagerCtlMessage::GuardRequest(tx)) => {
     712            0 :                 if self.is_offloaded {
     713              :                     // trying to unevict timeline, but without gurarantee that it will be successful
     714            0 :                     self.unevict_timeline().await;
     715            0 :                 }
     716              : 
     717            0 :                 let guard = if self.is_offloaded {
     718            0 :                     Err(anyhow::anyhow!("timeline is offloaded, can't get a guard"))
     719              :                 } else {
     720            0 :                     match self.tli.gate.enter() {
     721            0 :                         Ok(gate_guard) => Ok(self.access_service.create_guard(gate_guard)),
     722            0 :                         Err(_) => Err(anyhow::anyhow!(
     723            0 :                             "timeline is shutting down, can't get a guard"
     724            0 :                         )),
     725              :                     }
     726              :                 };
     727              : 
     728            0 :                 if tx.send(guard).is_err() {
     729            0 :                     warn!("failed to reply with a guard, receiver dropped");
     730            0 :                 }
     731              :             }
     732            0 :             Some(ManagerCtlMessage::TryGuardRequest(tx)) => {
     733            0 :                 let result = if self.is_offloaded {
     734            0 :                     None
     735              :                 } else {
     736            0 :                     match self.tli.gate.enter() {
     737            0 :                         Ok(gate_guard) => Some(self.access_service.create_guard(gate_guard)),
     738            0 :                         Err(_) => None,
     739              :                     }
     740              :                 };
     741              : 
     742            0 :                 if tx.send(result).is_err() {
     743            0 :                     warn!("failed to reply with a guard, receiver dropped");
     744            0 :                 }
     745              :             }
     746            0 :             Some(ManagerCtlMessage::GuardDrop(guard_id)) => {
     747            0 :                 self.access_service.drop_guard(guard_id);
     748            0 :             }
     749            0 :             Some(ManagerCtlMessage::BackupPartialReset(tx)) => {
     750            0 :                 info!("resetting uploaded partial backup state");
     751            0 :                 let res = self.backup_partial_reset().await;
     752            0 :                 if let Err(ref e) = res {
     753            0 :                     warn!("failed to reset partial backup state: {:?}", e);
     754            0 :                 }
     755            0 :                 if tx.send(res).is_err() {
     756            0 :                     warn!("failed to send partial backup reset result, receiver dropped");
     757            0 :                 }
     758              :             }
     759              :             None => {
     760              :                 // can't happen, we're holding the sender
     761            0 :                 unreachable!();
     762              :             }
     763              :         }
     764            0 :     }
     765              : }
     766              : 
     767              : // utility functions
     768            0 : async fn sleep_until(option: &Option<tokio::time::Instant>) {
     769            0 :     if let Some(timeout) = option {
     770            0 :         tokio::time::sleep_until(*timeout).await;
     771              :     } else {
     772            0 :         futures::future::pending::<()>().await;
     773              :     }
     774            0 : }
     775              : 
     776              : /// Future that resolves when the task is finished or never if the task is None.
     777              : ///
     778              : /// Note: it accepts Option<&mut> instead of &mut Option<> because mapping the
     779              : /// option to get the latter is hard.
     780            0 : async fn await_task_finish<T>(option: Option<&mut JoinHandle<T>>) -> Result<T, JoinError> {
     781            0 :     if let Some(task) = option {
     782            0 :         task.await
     783              :     } else {
     784            0 :         futures::future::pending().await
     785              :     }
     786            0 : }
     787              : 
     788              : /// Update next_event if candidate is earlier.
     789            0 : fn update_next_event(next_event: &mut Option<Instant>, candidate: Instant) {
     790            0 :     if let Some(next) = next_event {
     791            0 :         if candidate < *next {
     792            0 :             *next = candidate;
     793            0 :         }
     794            0 :     } else {
     795            0 :         *next_event = Some(candidate);
     796            0 :     }
     797            0 : }
     798              : 
     799              : #[repr(usize)]
     800            0 : #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
     801              : pub enum Status {
     802              :     NotStarted,
     803              :     Started,
     804              :     StateSnapshot,
     805              :     UpdateBackup,
     806              :     UpdateControlFile,
     807              :     UpdateWalRemoval,
     808              :     UpdatePartialBackup,
     809              :     EvictTimeline,
     810              :     Wait,
     811              :     HandleMessage,
     812              :     Exiting,
     813              :     Finished,
     814              : }
     815              : 
     816              : /// AtomicStatus is a wrapper around AtomicUsize adapted for the Status enum.
     817              : pub struct AtomicStatus {
     818              :     inner: AtomicUsize,
     819              : }
     820              : 
     821              : impl Default for AtomicStatus {
     822            0 :     fn default() -> Self {
     823            0 :         Self::new()
     824            0 :     }
     825              : }
     826              : 
     827              : impl AtomicStatus {
     828            0 :     pub fn new() -> Self {
     829            0 :         AtomicStatus {
     830            0 :             inner: AtomicUsize::new(Status::NotStarted as usize),
     831            0 :         }
     832            0 :     }
     833              : 
     834            0 :     pub fn load(&self, order: std::sync::atomic::Ordering) -> Status {
     835            0 :         // Safety: This line of code uses `std::mem::transmute` to reinterpret the loaded value as `Status`.
     836            0 :         // It is safe to use `transmute` in this context because `Status` is a repr(usize) enum,
     837            0 :         // which means it has the same memory layout as usize.
     838            0 :         // However, it is important to ensure that the loaded value is a valid variant of `Status`,
     839            0 :         // otherwise, the behavior will be undefined.
     840            0 :         unsafe { std::mem::transmute(self.inner.load(order)) }
     841            0 :     }
     842              : 
     843            0 :     pub fn get(&self) -> Status {
     844            0 :         self.load(std::sync::atomic::Ordering::Relaxed)
     845            0 :     }
     846              : 
     847            0 :     pub fn store(&self, val: Status, order: std::sync::atomic::Ordering) {
     848            0 :         self.inner.store(val as usize, order);
     849            0 :     }
     850              : }
        

Generated by: LCOV version 2.1-beta