Line data Source code
1 : //! This module implements Timeline lifecycle management and has all necessary code
2 : //! to glue together SafeKeeper and all other background services.
3 :
4 : use std::cmp::max;
5 : use std::ops::{Deref, DerefMut};
6 : use std::sync::Arc;
7 : use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
8 : use std::time::Duration;
9 :
10 : use anyhow::{Result, anyhow, bail};
11 : use camino::{Utf8Path, Utf8PathBuf};
12 : use http_utils::error::ApiError;
13 : use remote_storage::RemotePath;
14 : use safekeeper_api::Term;
15 : use safekeeper_api::membership::Configuration;
16 : use safekeeper_api::models::{
17 : PeerInfo, TimelineMembershipSwitchResponse, TimelineTermBumpResponse,
18 : };
19 : use storage_broker::proto::{SafekeeperTimelineInfo, TenantTimelineId as ProtoTenantTimelineId};
20 : use tokio::fs::{self};
21 : use tokio::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard, watch};
22 : use tokio::time::Instant;
23 : use tokio_util::sync::CancellationToken;
24 : use tracing::*;
25 : use utils::id::{NodeId, TenantId, TenantTimelineId};
26 : use utils::lsn::Lsn;
27 : use utils::sync::gate::Gate;
28 :
29 : use crate::metrics::{
30 : FullTimelineInfo, MISC_OPERATION_SECONDS, WAL_STORAGE_LIMIT_ERRORS, WalStorageMetrics,
31 : };
32 : use crate::rate_limit::RateLimiter;
33 : use crate::receive_wal::WalReceivers;
34 : use crate::safekeeper::{AcceptorProposerMessage, ProposerAcceptorMessage, SafeKeeper, TermLsn};
35 : use crate::send_wal::{WalSenders, WalSendersTimelineMetricValues};
36 : use crate::state::{EvictionState, TimelineMemState, TimelinePersistentState, TimelineState};
37 : use crate::timeline_guard::ResidenceGuard;
38 : use crate::timeline_manager::{AtomicStatus, ManagerCtl};
39 : use crate::timelines_set::TimelinesSet;
40 : use crate::wal_backup;
41 : use crate::wal_backup::{WalBackup, remote_timeline_path};
42 : use crate::wal_backup_partial::PartialRemoteSegment;
43 : use crate::wal_storage::{Storage as wal_storage_iface, WalReader};
44 : use crate::{SafeKeeperConf, control_file, debug_dump, timeline_manager, wal_storage};
45 :
46 0 : fn peer_info_from_sk_info(sk_info: &SafekeeperTimelineInfo, ts: Instant) -> PeerInfo {
47 0 : PeerInfo {
48 0 : sk_id: NodeId(sk_info.safekeeper_id),
49 0 : term: sk_info.term,
50 0 : last_log_term: sk_info.last_log_term,
51 0 : flush_lsn: Lsn(sk_info.flush_lsn),
52 0 : commit_lsn: Lsn(sk_info.commit_lsn),
53 0 : local_start_lsn: Lsn(sk_info.local_start_lsn),
54 0 : pg_connstr: sk_info.safekeeper_connstr.clone(),
55 0 : http_connstr: sk_info.http_connstr.clone(),
56 0 : https_connstr: sk_info.https_connstr.clone(),
57 0 : ts,
58 0 : }
59 0 : }
60 :
61 : // vector-based node id -> peer state map with very limited functionality we
62 : // need.
63 : #[derive(Debug, Clone, Default)]
64 : pub struct PeersInfo(pub Vec<PeerInfo>);
65 :
66 : impl PeersInfo {
67 0 : fn get(&mut self, id: NodeId) -> Option<&mut PeerInfo> {
68 0 : self.0.iter_mut().find(|p| p.sk_id == id)
69 0 : }
70 :
71 0 : fn upsert(&mut self, p: &PeerInfo) {
72 0 : match self.get(p.sk_id) {
73 0 : Some(rp) => *rp = p.clone(),
74 0 : None => self.0.push(p.clone()),
75 : }
76 0 : }
77 : }
78 :
79 : pub type ReadGuardSharedState<'a> = RwLockReadGuard<'a, SharedState>;
80 :
81 : /// WriteGuardSharedState is a wrapper around `RwLockWriteGuard<SharedState>` that
82 : /// automatically updates `watch::Sender` channels with state on drop.
83 : pub struct WriteGuardSharedState<'a> {
84 : tli: Arc<Timeline>,
85 : guard: RwLockWriteGuard<'a, SharedState>,
86 : }
87 :
88 : impl<'a> WriteGuardSharedState<'a> {
89 1270 : fn new(tli: Arc<Timeline>, guard: RwLockWriteGuard<'a, SharedState>) -> Self {
90 1270 : WriteGuardSharedState { tli, guard }
91 1270 : }
92 : }
93 :
94 : impl Deref for WriteGuardSharedState<'_> {
95 : type Target = SharedState;
96 :
97 0 : fn deref(&self) -> &Self::Target {
98 0 : &self.guard
99 0 : }
100 : }
101 :
102 : impl DerefMut for WriteGuardSharedState<'_> {
103 1265 : fn deref_mut(&mut self) -> &mut Self::Target {
104 1265 : &mut self.guard
105 1265 : }
106 : }
107 :
108 : impl Drop for WriteGuardSharedState<'_> {
109 1270 : fn drop(&mut self) {
110 1270 : let term_flush_lsn =
111 1270 : TermLsn::from((self.guard.sk.last_log_term(), self.guard.sk.flush_lsn()));
112 1270 : let commit_lsn = self.guard.sk.state().inmem.commit_lsn;
113 :
114 1270 : let _ = self.tli.term_flush_lsn_watch_tx.send_if_modified(|old| {
115 1270 : if *old != term_flush_lsn {
116 620 : *old = term_flush_lsn;
117 620 : true
118 : } else {
119 650 : false
120 : }
121 1270 : });
122 :
123 1270 : let _ = self.tli.commit_lsn_watch_tx.send_if_modified(|old| {
124 1270 : if *old != commit_lsn {
125 615 : *old = commit_lsn;
126 615 : true
127 : } else {
128 655 : false
129 : }
130 1270 : });
131 :
132 : // send notification about shared state update
133 1270 : self.tli.shared_state_version_tx.send_modify(|old| {
134 1270 : *old += 1;
135 1270 : });
136 1270 : }
137 : }
138 :
139 : /// This structure is stored in shared state and represents the state of the timeline.
140 : ///
141 : /// Usually it holds SafeKeeper, but it also supports offloaded timeline state. In this
142 : /// case, SafeKeeper is not available (because WAL is not present on disk) and all
143 : /// operations can be done only with control file.
144 : #[allow(clippy::large_enum_variant, reason = "TODO")]
145 : pub enum StateSK {
146 : Loaded(SafeKeeper<control_file::FileStorage, wal_storage::PhysicalStorage>),
147 : Offloaded(Box<TimelineState<control_file::FileStorage>>),
148 : // Not used, required for moving between states.
149 : Empty,
150 : }
151 :
152 : impl StateSK {
153 2666 : pub fn flush_lsn(&self) -> Lsn {
154 2666 : match self {
155 2666 : StateSK::Loaded(sk) => sk.wal_store.flush_lsn(),
156 0 : StateSK::Offloaded(state) => match state.eviction_state {
157 0 : EvictionState::Offloaded(flush_lsn) => flush_lsn,
158 0 : _ => panic!("StateSK::Offloaded mismatches with eviction_state from control_file"),
159 : },
160 0 : StateSK::Empty => unreachable!(),
161 : }
162 2666 : }
163 :
164 : /// Get a reference to the control file's timeline state.
165 2699 : pub fn state(&self) -> &TimelineState<control_file::FileStorage> {
166 2699 : match self {
167 2699 : StateSK::Loaded(sk) => &sk.state,
168 0 : StateSK::Offloaded(s) => s,
169 0 : StateSK::Empty => unreachable!(),
170 : }
171 2699 : }
172 :
173 25 : pub fn state_mut(&mut self) -> &mut TimelineState<control_file::FileStorage> {
174 25 : match self {
175 25 : StateSK::Loaded(sk) => &mut sk.state,
176 0 : StateSK::Offloaded(s) => s,
177 0 : StateSK::Empty => unreachable!(),
178 : }
179 25 : }
180 :
181 1333 : pub fn last_log_term(&self) -> Term {
182 1333 : self.state()
183 1333 : .acceptor_state
184 1333 : .get_last_log_term(self.flush_lsn())
185 1333 : }
186 :
187 0 : pub async fn term_bump(&mut self, to: Option<Term>) -> Result<TimelineTermBumpResponse> {
188 0 : self.state_mut().term_bump(to).await
189 0 : }
190 :
191 0 : pub async fn membership_switch(
192 0 : &mut self,
193 0 : to: Configuration,
194 0 : ) -> Result<TimelineMembershipSwitchResponse> {
195 0 : let result = self.state_mut().membership_switch(to).await?;
196 :
197 0 : Ok(TimelineMembershipSwitchResponse {
198 0 : previous_conf: result.previous_conf,
199 0 : current_conf: result.current_conf,
200 0 : last_log_term: self.state().acceptor_state.term,
201 0 : flush_lsn: self.flush_lsn(),
202 0 : })
203 0 : }
204 :
205 : /// Close open WAL files to release FDs.
206 0 : fn close_wal_store(&mut self) {
207 0 : if let StateSK::Loaded(sk) = self {
208 0 : sk.wal_store.close();
209 0 : }
210 0 : }
211 :
212 : /// Update timeline state with peer safekeeper data.
213 0 : pub async fn record_safekeeper_info(&mut self, sk_info: &SafekeeperTimelineInfo) -> Result<()> {
214 : // update commit_lsn if safekeeper is loaded
215 0 : match self {
216 0 : StateSK::Loaded(sk) => sk.record_safekeeper_info(sk_info).await?,
217 0 : StateSK::Offloaded(_) => {}
218 0 : StateSK::Empty => unreachable!(),
219 : }
220 :
221 : // update everything else, including remote_consistent_lsn and backup_lsn
222 0 : let mut sync_control_file = false;
223 0 : let state = self.state_mut();
224 0 : let wal_seg_size = state.server.wal_seg_size as u64;
225 :
226 0 : state.inmem.backup_lsn = max(Lsn(sk_info.backup_lsn), state.inmem.backup_lsn);
227 0 : sync_control_file |= state.backup_lsn + wal_seg_size < state.inmem.backup_lsn;
228 :
229 0 : state.inmem.remote_consistent_lsn = max(
230 0 : Lsn(sk_info.remote_consistent_lsn),
231 0 : state.inmem.remote_consistent_lsn,
232 0 : );
233 0 : sync_control_file |=
234 0 : state.remote_consistent_lsn + wal_seg_size < state.inmem.remote_consistent_lsn;
235 :
236 0 : state.inmem.peer_horizon_lsn =
237 0 : max(Lsn(sk_info.peer_horizon_lsn), state.inmem.peer_horizon_lsn);
238 0 : sync_control_file |= state.peer_horizon_lsn + wal_seg_size < state.inmem.peer_horizon_lsn;
239 :
240 0 : if sync_control_file {
241 0 : state.flush().await?;
242 0 : }
243 0 : Ok(())
244 0 : }
245 :
246 : /// Previously known as epoch_start_lsn. Needed only for reference in some APIs.
247 0 : pub fn term_start_lsn(&self) -> Lsn {
248 0 : match self {
249 0 : StateSK::Loaded(sk) => sk.term_start_lsn,
250 0 : StateSK::Offloaded(_) => Lsn(0),
251 0 : StateSK::Empty => unreachable!(),
252 : }
253 0 : }
254 :
255 : /// Used for metrics only.
256 0 : pub fn wal_storage_metrics(&self) -> WalStorageMetrics {
257 0 : match self {
258 0 : StateSK::Loaded(sk) => sk.wal_store.get_metrics(),
259 0 : StateSK::Offloaded(_) => WalStorageMetrics::default(),
260 0 : StateSK::Empty => unreachable!(),
261 : }
262 0 : }
263 :
264 : /// Returns WAL storage internal LSNs for debug dump.
265 0 : pub fn wal_storage_internal_state(&self) -> (Lsn, Lsn, Lsn, bool) {
266 0 : match self {
267 0 : StateSK::Loaded(sk) => sk.wal_store.internal_state(),
268 : StateSK::Offloaded(_) => {
269 0 : let flush_lsn = self.flush_lsn();
270 0 : (flush_lsn, flush_lsn, flush_lsn, false)
271 : }
272 0 : StateSK::Empty => unreachable!(),
273 : }
274 0 : }
275 :
276 : /// Access to SafeKeeper object. Panics if offloaded, should be good to use from WalResidentTimeline.
277 1240 : pub fn safekeeper(
278 1240 : &mut self,
279 1240 : ) -> &mut SafeKeeper<control_file::FileStorage, wal_storage::PhysicalStorage> {
280 1240 : match self {
281 1240 : StateSK::Loaded(sk) => sk,
282 : StateSK::Offloaded(_) => {
283 0 : panic!("safekeeper is offloaded, cannot be used")
284 : }
285 0 : StateSK::Empty => unreachable!(),
286 : }
287 1240 : }
288 :
289 : /// Moves control file's state structure out of the enum. Used to switch states.
290 0 : fn take_state(self) -> TimelineState<control_file::FileStorage> {
291 0 : match self {
292 0 : StateSK::Loaded(sk) => sk.state,
293 0 : StateSK::Offloaded(state) => *state,
294 0 : StateSK::Empty => unreachable!(),
295 : }
296 0 : }
297 : }
298 :
299 : /// Shared state associated with database instance
300 : pub struct SharedState {
301 : /// Safekeeper object
302 : pub(crate) sk: StateSK,
303 : /// In memory list containing state of peers sent in latest messages from them.
304 : pub(crate) peers_info: PeersInfo,
305 : // True value hinders old WAL removal; this is used by snapshotting. We
306 : // could make it a counter, but there is no need to.
307 : pub(crate) wal_removal_on_hold: bool,
308 : }
309 :
310 : impl SharedState {
311 : /// Creates a new SharedState.
312 5 : pub fn new(sk: StateSK) -> Self {
313 5 : Self {
314 5 : sk,
315 5 : peers_info: PeersInfo(vec![]),
316 5 : wal_removal_on_hold: false,
317 5 : }
318 5 : }
319 :
320 : /// Restore SharedState from control file. If file doesn't exist, bails out.
321 0 : pub fn restore(conf: &SafeKeeperConf, ttid: &TenantTimelineId) -> Result<Self> {
322 0 : let timeline_dir = get_timeline_dir(conf, ttid);
323 0 : let control_store = control_file::FileStorage::restore_new(&timeline_dir, conf.no_sync)?;
324 0 : if control_store.server.wal_seg_size == 0 {
325 0 : bail!(TimelineError::UninitializedWalSegSize(*ttid));
326 0 : }
327 :
328 0 : let sk = match control_store.eviction_state {
329 : EvictionState::Present => {
330 0 : let wal_store = wal_storage::PhysicalStorage::new(
331 0 : ttid,
332 0 : &timeline_dir,
333 0 : &control_store,
334 0 : conf.no_sync,
335 0 : )?;
336 0 : StateSK::Loaded(SafeKeeper::new(
337 0 : TimelineState::new(control_store),
338 0 : wal_store,
339 0 : conf.my_id,
340 0 : )?)
341 : }
342 : EvictionState::Offloaded(_) => {
343 0 : StateSK::Offloaded(Box::new(TimelineState::new(control_store)))
344 : }
345 : };
346 :
347 0 : Ok(Self::new(sk))
348 0 : }
349 :
350 5 : pub(crate) fn get_wal_seg_size(&self) -> usize {
351 5 : self.sk.state().server.wal_seg_size as usize
352 5 : }
353 :
354 0 : fn get_safekeeper_info(
355 0 : &self,
356 0 : ttid: &TenantTimelineId,
357 0 : conf: &SafeKeeperConf,
358 0 : standby_apply_lsn: Lsn,
359 0 : ) -> SafekeeperTimelineInfo {
360 0 : SafekeeperTimelineInfo {
361 0 : safekeeper_id: conf.my_id.0,
362 0 : tenant_timeline_id: Some(ProtoTenantTimelineId {
363 0 : tenant_id: ttid.tenant_id.as_ref().to_owned(),
364 0 : timeline_id: ttid.timeline_id.as_ref().to_owned(),
365 0 : }),
366 0 : term: self.sk.state().acceptor_state.term,
367 0 : last_log_term: self.sk.last_log_term(),
368 0 : flush_lsn: self.sk.flush_lsn().0,
369 0 : // note: this value is not flushed to control file yet and can be lost
370 0 : commit_lsn: self.sk.state().inmem.commit_lsn.0,
371 0 : remote_consistent_lsn: self.sk.state().inmem.remote_consistent_lsn.0,
372 0 : peer_horizon_lsn: self.sk.state().inmem.peer_horizon_lsn.0,
373 0 : safekeeper_connstr: conf
374 0 : .advertise_pg_addr
375 0 : .to_owned()
376 0 : .unwrap_or(conf.listen_pg_addr.clone()),
377 0 : http_connstr: conf.listen_http_addr.to_owned(),
378 0 : https_connstr: conf.listen_https_addr.to_owned(),
379 0 : backup_lsn: self.sk.state().inmem.backup_lsn.0,
380 0 : local_start_lsn: self.sk.state().local_start_lsn.0,
381 0 : availability_zone: conf.availability_zone.clone(),
382 0 : standby_horizon: standby_apply_lsn.0,
383 0 : }
384 0 : }
385 :
386 : /// Get our latest view of alive peers status on the timeline.
387 : /// We pass our own info through the broker as well, so when we don't have connection
388 : /// to the broker returned vec is empty.
389 58 : pub(crate) fn get_peers(&self, heartbeat_timeout: Duration) -> Vec<PeerInfo> {
390 58 : let now = Instant::now();
391 58 : self.peers_info
392 58 : .0
393 58 : .iter()
394 : // Regard peer as absent if we haven't heard from it within heartbeat_timeout.
395 58 : .filter(|p| now.duration_since(p.ts) <= heartbeat_timeout)
396 58 : .cloned()
397 58 : .collect()
398 58 : }
399 : }
400 :
401 : #[derive(Debug, thiserror::Error)]
402 : pub enum TimelineError {
403 : #[error("Timeline {0} was cancelled and cannot be used anymore")]
404 : Cancelled(TenantTimelineId),
405 : #[error("Timeline {0} was not found in global map")]
406 : NotFound(TenantTimelineId),
407 : #[error("Timeline {0} has been deleted")]
408 : Deleted(TenantTimelineId),
409 : #[error("Timeline {0} creation is in progress")]
410 : CreationInProgress(TenantTimelineId),
411 : #[error("Timeline {0} exists on disk, but wasn't loaded on startup")]
412 : Invalid(TenantTimelineId),
413 : #[error("Timeline {0} is already exists")]
414 : AlreadyExists(TenantTimelineId),
415 : #[error("Timeline {0} is not initialized, wal_seg_size is zero")]
416 : UninitializedWalSegSize(TenantTimelineId),
417 : #[error("Timeline {0} is not initialized, pg_version is unknown")]
418 : UninitialinzedPgVersion(TenantTimelineId),
419 : }
420 :
421 : // Convert to HTTP API error.
422 : impl From<TimelineError> for ApiError {
423 0 : fn from(te: TimelineError) -> ApiError {
424 0 : match te {
425 0 : TimelineError::NotFound(ttid) => {
426 0 : ApiError::NotFound(anyhow!("timeline {} not found", ttid).into())
427 : }
428 0 : _ => ApiError::InternalServerError(anyhow!("{}", te)),
429 : }
430 0 : }
431 : }
432 :
433 : /// We run remote deletion in a background task, this is how it sends its results back.
434 : type RemoteDeletionReceiver = tokio::sync::watch::Receiver<Option<anyhow::Result<()>>>;
435 :
436 : /// Timeline struct manages lifecycle (creation, deletion, restore) of a safekeeper timeline.
437 : /// It also holds SharedState and provides mutually exclusive access to it.
438 : pub struct Timeline {
439 : pub ttid: TenantTimelineId,
440 : pub remote_path: RemotePath,
441 :
442 : /// Used to broadcast commit_lsn updates to all background jobs.
443 : commit_lsn_watch_tx: watch::Sender<Lsn>,
444 : commit_lsn_watch_rx: watch::Receiver<Lsn>,
445 :
446 : /// Broadcasts (current term, flush_lsn) updates, walsender is interested in
447 : /// them when sending in recovery mode (to walproposer or peers). Note: this
448 : /// is just a notification, WAL reading should always done with lock held as
449 : /// term can change otherwise.
450 : term_flush_lsn_watch_tx: watch::Sender<TermLsn>,
451 : term_flush_lsn_watch_rx: watch::Receiver<TermLsn>,
452 :
453 : /// Broadcasts shared state updates.
454 : shared_state_version_tx: watch::Sender<usize>,
455 : shared_state_version_rx: watch::Receiver<usize>,
456 :
457 : /// Safekeeper and other state, that should remain consistent and
458 : /// synchronized with the disk. This is tokio mutex as we write WAL to disk
459 : /// while holding it, ensuring that consensus checks are in order.
460 : mutex: RwLock<SharedState>,
461 : walsenders: Arc<WalSenders>,
462 : walreceivers: Arc<WalReceivers>,
463 : timeline_dir: Utf8PathBuf,
464 : manager_ctl: ManagerCtl,
465 : conf: Arc<SafeKeeperConf>,
466 :
467 : pub(crate) wal_backup: Arc<WalBackup>,
468 :
469 : remote_deletion: std::sync::Mutex<Option<RemoteDeletionReceiver>>,
470 :
471 : /// Hold this gate from code that depends on the Timeline's non-shut-down state. While holding
472 : /// this gate, you must respect [`Timeline::cancel`]
473 : pub(crate) gate: Gate,
474 :
475 : /// Delete/cancel will trigger this, background tasks should drop out as soon as it fires
476 : pub(crate) cancel: CancellationToken,
477 :
478 : // timeline_manager controlled state
479 : pub(crate) broker_active: AtomicBool,
480 : pub(crate) wal_backup_active: AtomicBool,
481 : pub(crate) last_removed_segno: AtomicU64,
482 : pub(crate) mgr_status: AtomicStatus,
483 : }
484 :
485 : impl Timeline {
486 : /// Constructs a new timeline.
487 5 : pub fn new(
488 5 : ttid: TenantTimelineId,
489 5 : timeline_dir: &Utf8Path,
490 5 : remote_path: &RemotePath,
491 5 : shared_state: SharedState,
492 5 : conf: Arc<SafeKeeperConf>,
493 5 : wal_backup: Arc<WalBackup>,
494 5 : ) -> Arc<Self> {
495 5 : let (commit_lsn_watch_tx, commit_lsn_watch_rx) =
496 5 : watch::channel(shared_state.sk.state().commit_lsn);
497 5 : let (term_flush_lsn_watch_tx, term_flush_lsn_watch_rx) = watch::channel(TermLsn::from((
498 5 : shared_state.sk.last_log_term(),
499 5 : shared_state.sk.flush_lsn(),
500 5 : )));
501 5 : let (shared_state_version_tx, shared_state_version_rx) = watch::channel(0);
502 :
503 5 : let walreceivers = WalReceivers::new();
504 :
505 5 : Arc::new(Self {
506 5 : ttid,
507 5 : remote_path: remote_path.to_owned(),
508 5 : timeline_dir: timeline_dir.to_owned(),
509 5 : commit_lsn_watch_tx,
510 5 : commit_lsn_watch_rx,
511 5 : term_flush_lsn_watch_tx,
512 5 : term_flush_lsn_watch_rx,
513 5 : shared_state_version_tx,
514 5 : shared_state_version_rx,
515 5 : mutex: RwLock::new(shared_state),
516 5 : walsenders: WalSenders::new(walreceivers.clone()),
517 5 : walreceivers,
518 5 : gate: Default::default(),
519 5 : cancel: CancellationToken::default(),
520 5 : remote_deletion: std::sync::Mutex::new(None),
521 5 : manager_ctl: ManagerCtl::new(),
522 5 : conf,
523 5 : broker_active: AtomicBool::new(false),
524 5 : wal_backup_active: AtomicBool::new(false),
525 5 : last_removed_segno: AtomicU64::new(0),
526 5 : mgr_status: AtomicStatus::new(),
527 5 : wal_backup,
528 5 : })
529 5 : }
530 :
531 : /// Load existing timeline from disk.
532 0 : pub fn load_timeline(
533 0 : conf: Arc<SafeKeeperConf>,
534 0 : ttid: TenantTimelineId,
535 0 : wal_backup: Arc<WalBackup>,
536 0 : ) -> Result<Arc<Timeline>> {
537 0 : let _enter = info_span!("load_timeline", timeline = %ttid.timeline_id).entered();
538 :
539 0 : let shared_state = SharedState::restore(conf.as_ref(), &ttid)?;
540 0 : let timeline_dir = get_timeline_dir(conf.as_ref(), &ttid);
541 0 : let remote_path = remote_timeline_path(&ttid)?;
542 :
543 0 : Ok(Timeline::new(
544 0 : ttid,
545 0 : &timeline_dir,
546 0 : &remote_path,
547 0 : shared_state,
548 0 : conf,
549 0 : wal_backup,
550 0 : ))
551 0 : }
552 :
553 : /// Bootstrap new or existing timeline starting background tasks.
554 5 : pub fn bootstrap(
555 5 : self: &Arc<Timeline>,
556 5 : _shared_state: &mut WriteGuardSharedState<'_>,
557 5 : conf: &SafeKeeperConf,
558 5 : broker_active_set: Arc<TimelinesSet>,
559 5 : partial_backup_rate_limiter: RateLimiter,
560 5 : wal_backup: Arc<WalBackup>,
561 5 : ) {
562 5 : let (tx, rx) = self.manager_ctl.bootstrap_manager();
563 :
564 5 : let Ok(gate_guard) = self.gate.enter() else {
565 : // Init raced with shutdown
566 0 : return;
567 : };
568 :
569 : // Start manager task which will monitor timeline state and update
570 : // background tasks.
571 5 : tokio::spawn({
572 5 : let this = self.clone();
573 5 : let conf = conf.clone();
574 5 : async move {
575 5 : let _gate_guard = gate_guard;
576 5 : timeline_manager::main_task(
577 5 : ManagerTimeline { tli: this },
578 5 : conf,
579 5 : broker_active_set,
580 5 : tx,
581 5 : rx,
582 5 : partial_backup_rate_limiter,
583 5 : wal_backup,
584 5 : )
585 5 : .await
586 0 : }
587 : });
588 5 : }
589 :
590 : /// Cancel the timeline, requesting background activity to stop. Closing
591 : /// the `self.gate` waits for that.
592 0 : pub async fn cancel(&self) {
593 0 : info!("timeline {} shutting down", self.ttid);
594 0 : self.cancel.cancel();
595 0 : }
596 :
597 : /// Background timeline activities (which hold Timeline::gate) will no
598 : /// longer run once this function completes. `Self::cancel` must have been
599 : /// already called.
600 0 : pub async fn close(&self) {
601 0 : assert!(self.cancel.is_cancelled());
602 :
603 : // Wait for any concurrent tasks to stop using this timeline, to avoid e.g. attempts
604 : // to read deleted files.
605 0 : self.gate.close().await;
606 0 : }
607 :
608 : /// Delete timeline from disk completely, by removing timeline directory.
609 : ///
610 : /// Also deletes WAL in s3. Might fail if e.g. s3 is unavailable, but
611 : /// deletion API endpoint is retriable.
612 : ///
613 : /// Timeline must be in shut-down state (i.e. call [`Self::close`] first)
614 0 : pub async fn delete(
615 0 : &self,
616 0 : shared_state: &mut WriteGuardSharedState<'_>,
617 0 : only_local: bool,
618 0 : ) -> Result<bool> {
619 : // Assert that [`Self::close`] was already called
620 0 : assert!(self.cancel.is_cancelled());
621 0 : assert!(self.gate.close_complete());
622 :
623 0 : info!("deleting timeline {} from disk", self.ttid);
624 :
625 : // Close associated FDs. Nobody will be able to touch timeline data once
626 : // it is cancelled, so WAL storage won't be opened again.
627 0 : shared_state.sk.close_wal_store();
628 :
629 0 : if !only_local {
630 0 : self.remote_delete().await?;
631 0 : }
632 :
633 0 : let dir_existed = delete_dir(&self.timeline_dir).await?;
634 0 : Ok(dir_existed)
635 0 : }
636 :
637 : /// Delete timeline content from remote storage. If the returned future is dropped,
638 : /// deletion will continue in the background.
639 : ///
640 : /// This function ordinarily spawns a task and stashes a result receiver into [`Self::remote_deletion`]. If
641 : /// deletion is already happening, it may simply wait for an existing task's result.
642 : ///
643 : /// Note: we concurrently delete remote storage data from multiple
644 : /// safekeepers. That's ok, s3 replies 200 if object doesn't exist and we
645 : /// do some retries anyway.
646 0 : async fn remote_delete(&self) -> Result<()> {
647 : // We will start a background task to do the deletion, so that it proceeds even if our
648 : // API request is dropped. Future requests will see the existing deletion task and wait
649 : // for it to complete.
650 0 : let mut result_rx = {
651 0 : let mut remote_deletion_state = self.remote_deletion.lock().unwrap();
652 0 : let result_rx = if let Some(result_rx) = remote_deletion_state.as_ref() {
653 0 : if let Some(result) = result_rx.borrow().as_ref() {
654 0 : if let Err(e) = result {
655 : // A previous remote deletion failed: we will start a new one
656 0 : tracing::error!("remote deletion failed, will retry ({e})");
657 0 : None
658 : } else {
659 : // A previous remote deletion call already succeeded
660 0 : return Ok(());
661 : }
662 : } else {
663 : // Remote deletion is still in flight
664 0 : Some(result_rx.clone())
665 : }
666 : } else {
667 : // Remote deletion was not attempted yet, start it now.
668 0 : None
669 : };
670 :
671 0 : match result_rx {
672 0 : Some(result_rx) => result_rx,
673 0 : None => self.start_remote_delete(&mut remote_deletion_state),
674 : }
675 : };
676 :
677 : // Wait for a result
678 0 : let Ok(result) = result_rx.wait_for(|v| v.is_some()).await else {
679 : // Unexpected: sender should always send a result before dropping the channel, even if it has an error
680 0 : return Err(anyhow::anyhow!(
681 0 : "remote deletion task future was dropped without sending a result"
682 0 : ));
683 : };
684 :
685 0 : result
686 0 : .as_ref()
687 0 : .expect("We did a wait_for on this being Some above")
688 0 : .as_ref()
689 0 : .map(|_| ())
690 0 : .map_err(|e| anyhow::anyhow!("remote deletion failed: {e}"))
691 0 : }
692 :
693 : /// Spawn background task to do remote deletion, return a receiver for its outcome
694 0 : fn start_remote_delete(
695 0 : &self,
696 0 : guard: &mut std::sync::MutexGuard<Option<RemoteDeletionReceiver>>,
697 0 : ) -> RemoteDeletionReceiver {
698 0 : tracing::info!("starting remote deletion");
699 0 : let storage = self.wal_backup.get_storage().clone();
700 0 : let (result_tx, result_rx) = tokio::sync::watch::channel(None);
701 0 : let ttid = self.ttid;
702 0 : tokio::task::spawn(
703 0 : async move {
704 0 : let r = if let Some(storage) = storage {
705 0 : wal_backup::delete_timeline(&storage, &ttid).await
706 : } else {
707 0 : tracing::info!(
708 0 : "skipping remote deletion because no remote storage is configured; this effectively leaks the objects in remote storage"
709 : );
710 0 : Ok(())
711 : };
712 :
713 0 : if let Err(e) = &r {
714 : // Log error here in case nobody ever listens for our result (e.g. dropped API request)
715 0 : tracing::error!("remote deletion failed: {e}");
716 0 : }
717 :
718 : // Ignore send results: it's legal for the Timeline to give up waiting for us.
719 0 : let _ = result_tx.send(Some(r));
720 0 : }
721 0 : .instrument(info_span!("remote_delete", timeline = %self.ttid)),
722 : );
723 :
724 0 : **guard = Some(result_rx.clone());
725 :
726 0 : result_rx
727 0 : }
728 :
729 : /// Returns if timeline is cancelled.
730 2505 : pub fn is_cancelled(&self) -> bool {
731 2505 : self.cancel.is_cancelled()
732 2505 : }
733 :
734 : /// Take a writing mutual exclusive lock on timeline shared_state.
735 1270 : pub async fn write_shared_state(self: &Arc<Self>) -> WriteGuardSharedState<'_> {
736 1270 : WriteGuardSharedState::new(self.clone(), self.mutex.write().await)
737 1270 : }
738 :
739 77 : pub async fn read_shared_state(&self) -> ReadGuardSharedState {
740 77 : self.mutex.read().await
741 77 : }
742 :
743 : /// Returns commit_lsn watch channel.
744 5 : pub fn get_commit_lsn_watch_rx(&self) -> watch::Receiver<Lsn> {
745 5 : self.commit_lsn_watch_rx.clone()
746 5 : }
747 :
748 : /// Returns term_flush_lsn watch channel.
749 0 : pub fn get_term_flush_lsn_watch_rx(&self) -> watch::Receiver<TermLsn> {
750 0 : self.term_flush_lsn_watch_rx.clone()
751 0 : }
752 :
753 : /// Returns watch channel for SharedState update version.
754 5 : pub fn get_state_version_rx(&self) -> watch::Receiver<usize> {
755 5 : self.shared_state_version_rx.clone()
756 5 : }
757 :
758 : /// Returns wal_seg_size.
759 5 : pub async fn get_wal_seg_size(&self) -> usize {
760 5 : self.read_shared_state().await.get_wal_seg_size()
761 5 : }
762 :
763 : /// Returns state of the timeline.
764 9 : pub async fn get_state(&self) -> (TimelineMemState, TimelinePersistentState) {
765 9 : let state = self.read_shared_state().await;
766 9 : (
767 9 : state.sk.state().inmem.clone(),
768 9 : TimelinePersistentState::clone(state.sk.state()),
769 9 : )
770 9 : }
771 :
772 : /// Returns latest backup_lsn.
773 0 : pub async fn get_wal_backup_lsn(&self) -> Lsn {
774 0 : self.read_shared_state().await.sk.state().inmem.backup_lsn
775 0 : }
776 :
777 : /// Sets backup_lsn to the given value.
778 0 : pub async fn set_wal_backup_lsn(self: &Arc<Self>, backup_lsn: Lsn) -> Result<()> {
779 0 : if self.is_cancelled() {
780 0 : bail!(TimelineError::Cancelled(self.ttid));
781 0 : }
782 :
783 0 : let mut state = self.write_shared_state().await;
784 0 : state.sk.state_mut().inmem.backup_lsn = max(state.sk.state().inmem.backup_lsn, backup_lsn);
785 : // we should check whether to shut down offloader, but this will be done
786 : // soon by peer communication anyway.
787 0 : Ok(())
788 0 : }
789 :
790 : /// Get safekeeper info for broadcasting to broker and other peers.
791 0 : pub async fn get_safekeeper_info(&self, conf: &SafeKeeperConf) -> SafekeeperTimelineInfo {
792 0 : let standby_apply_lsn = self.walsenders.get_hotstandby().reply.apply_lsn;
793 0 : let shared_state = self.read_shared_state().await;
794 0 : shared_state.get_safekeeper_info(&self.ttid, conf, standby_apply_lsn)
795 0 : }
796 :
797 : /// Update timeline state with peer safekeeper data.
798 0 : pub async fn record_safekeeper_info(
799 0 : self: &Arc<Self>,
800 0 : sk_info: SafekeeperTimelineInfo,
801 0 : ) -> Result<()> {
802 : {
803 0 : let mut shared_state = self.write_shared_state().await;
804 0 : shared_state.sk.record_safekeeper_info(&sk_info).await?;
805 0 : let peer_info = peer_info_from_sk_info(&sk_info, Instant::now());
806 0 : shared_state.peers_info.upsert(&peer_info);
807 : }
808 0 : Ok(())
809 0 : }
810 :
811 0 : pub async fn get_peers(&self, conf: &SafeKeeperConf) -> Vec<PeerInfo> {
812 0 : let shared_state = self.read_shared_state().await;
813 0 : shared_state.get_peers(conf.heartbeat_timeout)
814 0 : }
815 :
816 5 : pub fn get_walsenders(&self) -> &Arc<WalSenders> {
817 5 : &self.walsenders
818 5 : }
819 :
820 18 : pub fn get_walreceivers(&self) -> &Arc<WalReceivers> {
821 18 : &self.walreceivers
822 18 : }
823 :
824 : /// Returns flush_lsn.
825 0 : pub async fn get_flush_lsn(&self) -> Lsn {
826 0 : self.read_shared_state().await.sk.flush_lsn()
827 0 : }
828 :
829 : /// Gather timeline data for metrics.
830 0 : pub async fn info_for_metrics(&self) -> Option<FullTimelineInfo> {
831 0 : if self.is_cancelled() {
832 0 : return None;
833 0 : }
834 :
835 : let WalSendersTimelineMetricValues {
836 0 : ps_feedback_counter,
837 0 : last_ps_feedback,
838 0 : interpreted_wal_reader_tasks,
839 0 : } = self.walsenders.info_for_metrics();
840 :
841 0 : let state = self.read_shared_state().await;
842 0 : Some(FullTimelineInfo {
843 0 : ttid: self.ttid,
844 0 : ps_feedback_count: ps_feedback_counter,
845 0 : last_ps_feedback,
846 0 : wal_backup_active: self.wal_backup_active.load(Ordering::Relaxed),
847 0 : timeline_is_active: self.broker_active.load(Ordering::Relaxed),
848 0 : num_computes: self.walreceivers.get_num() as u32,
849 0 : last_removed_segno: self.last_removed_segno.load(Ordering::Relaxed),
850 0 : interpreted_wal_reader_tasks,
851 0 : epoch_start_lsn: state.sk.term_start_lsn(),
852 0 : mem_state: state.sk.state().inmem.clone(),
853 0 : persisted_state: TimelinePersistentState::clone(state.sk.state()),
854 0 : flush_lsn: state.sk.flush_lsn(),
855 0 : wal_storage: state.sk.wal_storage_metrics(),
856 0 : })
857 0 : }
858 :
859 : /// Returns in-memory timeline state to build a full debug dump.
860 0 : pub async fn memory_dump(&self) -> debug_dump::Memory {
861 0 : let state = self.read_shared_state().await;
862 :
863 0 : let (write_lsn, write_record_lsn, flush_lsn, file_open) =
864 0 : state.sk.wal_storage_internal_state();
865 :
866 0 : debug_dump::Memory {
867 0 : is_cancelled: self.is_cancelled(),
868 0 : peers_info_len: state.peers_info.0.len(),
869 0 : walsenders: self.walsenders.get_all_public(),
870 0 : wal_backup_active: self.wal_backup_active.load(Ordering::Relaxed),
871 0 : active: self.broker_active.load(Ordering::Relaxed),
872 0 : num_computes: self.walreceivers.get_num() as u32,
873 0 : last_removed_segno: self.last_removed_segno.load(Ordering::Relaxed),
874 0 : epoch_start_lsn: state.sk.term_start_lsn(),
875 0 : mem_state: state.sk.state().inmem.clone(),
876 0 : mgr_status: self.mgr_status.get(),
877 0 : write_lsn,
878 0 : write_record_lsn,
879 0 : flush_lsn,
880 0 : file_open,
881 0 : }
882 0 : }
883 :
884 : /// Apply a function to the control file state and persist it.
885 0 : pub async fn map_control_file<T>(
886 0 : self: &Arc<Self>,
887 0 : f: impl FnOnce(&mut TimelinePersistentState) -> Result<T>,
888 0 : ) -> Result<T> {
889 0 : let mut state = self.write_shared_state().await;
890 0 : let mut persistent_state = state.sk.state_mut().start_change();
891 : // If f returns error, we abort the change and don't persist anything.
892 0 : let res = f(&mut persistent_state)?;
893 : // If persisting fails, we abort the change and return error.
894 0 : state
895 0 : .sk
896 0 : .state_mut()
897 0 : .finish_change(&persistent_state)
898 0 : .await?;
899 0 : Ok(res)
900 0 : }
901 :
902 0 : pub async fn term_bump(self: &Arc<Self>, to: Option<Term>) -> Result<TimelineTermBumpResponse> {
903 0 : let mut state = self.write_shared_state().await;
904 0 : state.sk.term_bump(to).await
905 0 : }
906 :
907 0 : pub async fn membership_switch(
908 0 : self: &Arc<Self>,
909 0 : to: Configuration,
910 0 : ) -> Result<TimelineMembershipSwitchResponse> {
911 0 : let mut state = self.write_shared_state().await;
912 0 : state.sk.membership_switch(to).await
913 0 : }
914 :
915 : /// Guts of [`Self::wal_residence_guard`] and [`Self::try_wal_residence_guard`]
916 10 : async fn do_wal_residence_guard(
917 10 : self: &Arc<Self>,
918 10 : block: bool,
919 10 : ) -> Result<Option<WalResidentTimeline>> {
920 10 : let op_label = if block {
921 10 : "wal_residence_guard"
922 : } else {
923 0 : "try_wal_residence_guard"
924 : };
925 :
926 10 : if self.is_cancelled() {
927 0 : bail!(TimelineError::Cancelled(self.ttid));
928 10 : }
929 :
930 10 : debug!("requesting WalResidentTimeline guard");
931 10 : let started_at = Instant::now();
932 10 : let status_before = self.mgr_status.get();
933 :
934 : // Wait 30 seconds for the guard to be acquired. It can time out if someone is
935 : // holding the lock (e.g. during `SafeKeeper::process_msg()`) or manager task
936 : // is stuck.
937 10 : let res = tokio::time::timeout_at(started_at + Duration::from_secs(30), async {
938 10 : if block {
939 10 : self.manager_ctl.wal_residence_guard().await.map(Some)
940 : } else {
941 0 : self.manager_ctl.try_wal_residence_guard().await
942 : }
943 10 : })
944 10 : .await;
945 :
946 10 : let guard = match res {
947 10 : Ok(Ok(guard)) => {
948 10 : let finished_at = Instant::now();
949 10 : let elapsed = finished_at - started_at;
950 10 : MISC_OPERATION_SECONDS
951 10 : .with_label_values(&[op_label])
952 10 : .observe(elapsed.as_secs_f64());
953 :
954 10 : guard
955 : }
956 0 : Ok(Err(e)) => {
957 0 : warn!(
958 0 : "error acquiring in {op_label}, statuses {:?} => {:?}",
959 : status_before,
960 0 : self.mgr_status.get()
961 : );
962 0 : return Err(e);
963 : }
964 : Err(_) => {
965 0 : warn!(
966 0 : "timeout acquiring in {op_label} guard, statuses {:?} => {:?}",
967 : status_before,
968 0 : self.mgr_status.get()
969 : );
970 0 : anyhow::bail!("timeout while acquiring WalResidentTimeline guard");
971 : }
972 : };
973 :
974 10 : Ok(guard.map(|g| WalResidentTimeline::new(self.clone(), g)))
975 10 : }
976 :
977 : /// Get the timeline guard for reading/writing WAL files.
978 : /// If WAL files are not present on disk (evicted), they will be automatically
979 : /// downloaded from remote storage. This is done in the manager task, which is
980 : /// responsible for issuing all guards.
981 : ///
982 : /// NB: don't use this function from timeline_manager, it will deadlock.
983 : /// NB: don't use this function while holding shared_state lock.
984 10 : pub async fn wal_residence_guard(self: &Arc<Self>) -> Result<WalResidentTimeline> {
985 10 : self.do_wal_residence_guard(true)
986 10 : .await
987 10 : .map(|m| m.expect("Always get Some in block=true mode"))
988 10 : }
989 :
990 : /// Get the timeline guard for reading/writing WAL files if the timeline is resident,
991 : /// else return None
992 0 : pub(crate) async fn try_wal_residence_guard(
993 0 : self: &Arc<Self>,
994 0 : ) -> Result<Option<WalResidentTimeline>> {
995 0 : self.do_wal_residence_guard(false).await
996 0 : }
997 :
998 0 : pub async fn backup_partial_reset(self: &Arc<Self>) -> Result<Vec<String>> {
999 0 : self.manager_ctl.backup_partial_reset().await
1000 0 : }
1001 : }
1002 :
1003 : /// This is a guard that allows to read/write disk timeline state.
1004 : /// All tasks that are trying to read/write WAL from disk should use this guard.
1005 : pub struct WalResidentTimeline {
1006 : pub tli: Arc<Timeline>,
1007 : _guard: ResidenceGuard,
1008 : }
1009 :
1010 : impl WalResidentTimeline {
1011 15 : pub fn new(tli: Arc<Timeline>, _guard: ResidenceGuard) -> Self {
1012 15 : WalResidentTimeline { tli, _guard }
1013 15 : }
1014 : }
1015 :
1016 : impl Deref for WalResidentTimeline {
1017 : type Target = Arc<Timeline>;
1018 :
1019 6917 : fn deref(&self) -> &Self::Target {
1020 6917 : &self.tli
1021 6917 : }
1022 : }
1023 :
1024 : impl WalResidentTimeline {
1025 : /// Returns true if walsender should stop sending WAL to pageserver. We
1026 : /// terminate it if remote_consistent_lsn reached commit_lsn and there is no
1027 : /// computes. While there might be nothing to stream already, we learn about
1028 : /// remote_consistent_lsn update through replication feedback, and we want
1029 : /// to stop pushing to the broker if pageserver is fully caughtup.
1030 0 : pub async fn should_walsender_stop(&self, reported_remote_consistent_lsn: Lsn) -> bool {
1031 0 : if self.is_cancelled() {
1032 0 : return true;
1033 0 : }
1034 0 : let shared_state = self.read_shared_state().await;
1035 0 : if self.walreceivers.get_num() == 0 {
1036 0 : return shared_state.sk.state().inmem.commit_lsn == Lsn(0) || // no data at all yet
1037 0 : reported_remote_consistent_lsn >= shared_state.sk.state().inmem.commit_lsn;
1038 0 : }
1039 0 : false
1040 0 : }
1041 :
1042 : /// Ensure that current term is t, erroring otherwise, and lock the state.
1043 0 : pub async fn acquire_term(&self, t: Term) -> Result<ReadGuardSharedState> {
1044 0 : let ss = self.read_shared_state().await;
1045 0 : if ss.sk.state().acceptor_state.term != t {
1046 0 : bail!(
1047 0 : "failed to acquire term {}, current term {}",
1048 : t,
1049 0 : ss.sk.state().acceptor_state.term
1050 : );
1051 0 : }
1052 0 : Ok(ss)
1053 0 : }
1054 :
1055 : // BEGIN HADRON
1056 : // Check if disk usage by WAL segment files for this timeline exceeds the configured limit.
1057 1240 : fn hadron_check_disk_usage(
1058 1240 : &self,
1059 1240 : shared_state_locked: &mut WriteGuardSharedState<'_>,
1060 1240 : ) -> Result<()> {
1061 : // The disk usage is calculated based on the number of segments between `last_removed_segno`
1062 : // and the current flush LSN segment number. `last_removed_segno` is advanced after
1063 : // unneeded WAL files are physically removed from disk (see `update_wal_removal_end()`
1064 : // in `timeline_manager.rs`).
1065 1240 : let max_timeline_disk_usage_bytes = self.conf.max_timeline_disk_usage_bytes;
1066 1240 : if max_timeline_disk_usage_bytes > 0 {
1067 0 : let last_removed_segno = self.last_removed_segno.load(Ordering::Relaxed);
1068 0 : let flush_lsn = shared_state_locked.sk.flush_lsn();
1069 0 : let wal_seg_size = shared_state_locked.sk.state().server.wal_seg_size as u64;
1070 0 : let current_segno = flush_lsn.segment_number(wal_seg_size as usize);
1071 :
1072 0 : let segno_count = current_segno - last_removed_segno;
1073 0 : let disk_usage_bytes = segno_count * wal_seg_size;
1074 :
1075 0 : if disk_usage_bytes > max_timeline_disk_usage_bytes {
1076 0 : WAL_STORAGE_LIMIT_ERRORS.inc();
1077 0 : bail!(
1078 0 : "WAL storage utilization exceeds configured limit of {} bytes: current disk usage: {} bytes",
1079 : max_timeline_disk_usage_bytes,
1080 : disk_usage_bytes
1081 : );
1082 0 : }
1083 1240 : }
1084 1240 : Ok(())
1085 1240 : }
1086 : // END HADRON
1087 :
1088 : /// Pass arrived message to the safekeeper.
1089 1240 : pub async fn process_msg(
1090 1240 : &self,
1091 1240 : msg: &ProposerAcceptorMessage,
1092 1240 : ) -> Result<Option<AcceptorProposerMessage>> {
1093 1240 : if self.is_cancelled() {
1094 0 : bail!(TimelineError::Cancelled(self.ttid));
1095 1240 : }
1096 :
1097 : let mut rmsg: Option<AcceptorProposerMessage>;
1098 : {
1099 1240 : let mut shared_state = self.write_shared_state().await;
1100 : // BEGIN HADRON
1101 : // Errors from the `hadron_check_disk_usage()` function fail the process_msg() function, which
1102 : // gets propagated upward and terminates the entire WalAcceptor. This will cause postgres to
1103 : // disconnect from the safekeeper and reestablish another connection. Postgres will keep retrying
1104 : // safekeeper connections every second until it can successfully propose WAL to the SK again.
1105 1240 : self.hadron_check_disk_usage(&mut shared_state)?;
1106 : // END HADRON
1107 1240 : rmsg = shared_state.sk.safekeeper().process_msg(msg).await?;
1108 :
1109 : // if this is AppendResponse, fill in proper hot standby feedback.
1110 620 : if let Some(AcceptorProposerMessage::AppendResponse(ref mut resp)) = rmsg {
1111 620 : resp.hs_feedback = self.walsenders.get_hotstandby().hs_feedback;
1112 620 : }
1113 : }
1114 1240 : Ok(rmsg)
1115 1240 : }
1116 :
1117 9 : pub async fn get_walreader(&self, start_lsn: Lsn) -> Result<WalReader> {
1118 9 : let (_, persisted_state) = self.get_state().await;
1119 :
1120 9 : WalReader::new(
1121 9 : &self.ttid,
1122 9 : self.timeline_dir.clone(),
1123 9 : &persisted_state,
1124 9 : start_lsn,
1125 9 : self.wal_backup.clone(),
1126 : )
1127 9 : }
1128 :
1129 0 : pub fn get_timeline_dir(&self) -> Utf8PathBuf {
1130 0 : self.timeline_dir.clone()
1131 0 : }
1132 :
1133 : /// Update in memory remote consistent lsn.
1134 0 : pub async fn update_remote_consistent_lsn(&self, candidate: Lsn) {
1135 0 : let mut shared_state = self.write_shared_state().await;
1136 0 : shared_state.sk.state_mut().inmem.remote_consistent_lsn = max(
1137 0 : shared_state.sk.state().inmem.remote_consistent_lsn,
1138 0 : candidate,
1139 0 : );
1140 0 : }
1141 : }
1142 :
1143 : /// This struct contains methods that are used by timeline manager task.
1144 : pub(crate) struct ManagerTimeline {
1145 : pub(crate) tli: Arc<Timeline>,
1146 : }
1147 :
1148 : impl Deref for ManagerTimeline {
1149 : type Target = Arc<Timeline>;
1150 :
1151 597 : fn deref(&self) -> &Self::Target {
1152 597 : &self.tli
1153 597 : }
1154 : }
1155 :
1156 : impl ManagerTimeline {
1157 0 : pub(crate) fn timeline_dir(&self) -> &Utf8PathBuf {
1158 0 : &self.tli.timeline_dir
1159 0 : }
1160 :
1161 : /// Manager requests this state on startup.
1162 5 : pub(crate) async fn bootstrap_mgr(&self) -> (bool, Option<PartialRemoteSegment>) {
1163 5 : let shared_state = self.read_shared_state().await;
1164 5 : let is_offloaded = matches!(
1165 5 : shared_state.sk.state().eviction_state,
1166 : EvictionState::Offloaded(_)
1167 : );
1168 5 : let partial_backup_uploaded = shared_state.sk.state().partial_backup.uploaded_segment();
1169 :
1170 5 : (is_offloaded, partial_backup_uploaded)
1171 5 : }
1172 :
1173 : /// Try to switch state Present->Offloaded.
1174 0 : pub(crate) async fn switch_to_offloaded(
1175 0 : &self,
1176 0 : partial: &PartialRemoteSegment,
1177 0 : ) -> anyhow::Result<()> {
1178 0 : let mut shared = self.write_shared_state().await;
1179 :
1180 : // updating control file
1181 0 : let mut pstate = shared.sk.state_mut().start_change();
1182 :
1183 0 : if !matches!(pstate.eviction_state, EvictionState::Present) {
1184 0 : bail!(
1185 0 : "cannot switch to offloaded state, current state is {:?}",
1186 : pstate.eviction_state
1187 : );
1188 0 : }
1189 :
1190 0 : if partial.flush_lsn != shared.sk.flush_lsn() {
1191 0 : bail!(
1192 0 : "flush_lsn mismatch in partial backup, expected {}, got {}",
1193 0 : shared.sk.flush_lsn(),
1194 : partial.flush_lsn
1195 : );
1196 0 : }
1197 :
1198 0 : if partial.commit_lsn != pstate.commit_lsn {
1199 0 : bail!(
1200 0 : "commit_lsn mismatch in partial backup, expected {}, got {}",
1201 : pstate.commit_lsn,
1202 : partial.commit_lsn
1203 : );
1204 0 : }
1205 :
1206 0 : if partial.term != shared.sk.last_log_term() {
1207 0 : bail!(
1208 0 : "term mismatch in partial backup, expected {}, got {}",
1209 0 : shared.sk.last_log_term(),
1210 : partial.term
1211 : );
1212 0 : }
1213 :
1214 0 : pstate.eviction_state = EvictionState::Offloaded(shared.sk.flush_lsn());
1215 0 : shared.sk.state_mut().finish_change(&pstate).await?;
1216 : // control file is now switched to Offloaded state
1217 :
1218 : // now we can switch shared.sk to Offloaded, shouldn't fail
1219 0 : let prev_sk = std::mem::replace(&mut shared.sk, StateSK::Empty);
1220 0 : let cfile_state = prev_sk.take_state();
1221 0 : shared.sk = StateSK::Offloaded(Box::new(cfile_state));
1222 :
1223 0 : Ok(())
1224 0 : }
1225 :
1226 : /// Try to switch state Offloaded->Present.
1227 0 : pub(crate) async fn switch_to_present(&self) -> anyhow::Result<()> {
1228 0 : let mut shared = self.write_shared_state().await;
1229 :
1230 : // trying to restore WAL storage
1231 0 : let wal_store = wal_storage::PhysicalStorage::new(
1232 0 : &self.ttid,
1233 0 : &self.timeline_dir,
1234 0 : shared.sk.state(),
1235 0 : self.conf.no_sync,
1236 0 : )?;
1237 :
1238 : // updating control file
1239 0 : let mut pstate = shared.sk.state_mut().start_change();
1240 :
1241 0 : if !matches!(pstate.eviction_state, EvictionState::Offloaded(_)) {
1242 0 : bail!(
1243 0 : "cannot switch to present state, current state is {:?}",
1244 : pstate.eviction_state
1245 : );
1246 0 : }
1247 :
1248 0 : if wal_store.flush_lsn() != shared.sk.flush_lsn() {
1249 0 : bail!(
1250 0 : "flush_lsn mismatch in restored WAL, expected {}, got {}",
1251 0 : shared.sk.flush_lsn(),
1252 0 : wal_store.flush_lsn()
1253 : );
1254 0 : }
1255 :
1256 0 : pstate.eviction_state = EvictionState::Present;
1257 0 : shared.sk.state_mut().finish_change(&pstate).await?;
1258 :
1259 : // now we can switch shared.sk to Present, shouldn't fail
1260 0 : let prev_sk = std::mem::replace(&mut shared.sk, StateSK::Empty);
1261 0 : let cfile_state = prev_sk.take_state();
1262 0 : shared.sk = StateSK::Loaded(SafeKeeper::new(cfile_state, wal_store, self.conf.my_id)?);
1263 :
1264 0 : Ok(())
1265 0 : }
1266 :
1267 : /// Update current manager state, useful for debugging manager deadlocks.
1268 318 : pub(crate) fn set_status(&self, status: timeline_manager::Status) {
1269 318 : self.mgr_status.store(status, Ordering::Relaxed);
1270 318 : }
1271 : }
1272 :
1273 : /// Deletes directory and it's contents. Returns false if directory does not exist.
1274 0 : pub async fn delete_dir(path: &Utf8PathBuf) -> Result<bool> {
1275 0 : match fs::remove_dir_all(path).await {
1276 0 : Ok(_) => Ok(true),
1277 0 : Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),
1278 0 : Err(e) => Err(e.into()),
1279 : }
1280 0 : }
1281 :
1282 : /// Get a path to the tenant directory. If you just need to get a timeline directory,
1283 : /// use WalResidentTimeline::get_timeline_dir instead.
1284 10 : pub fn get_tenant_dir(conf: &SafeKeeperConf, tenant_id: &TenantId) -> Utf8PathBuf {
1285 10 : conf.workdir.join(tenant_id.to_string())
1286 10 : }
1287 :
1288 : /// Get a path to the timeline directory. If you need to read WAL files from disk,
1289 : /// use WalResidentTimeline::get_timeline_dir instead. This function does not check
1290 : /// timeline eviction status and WAL files might not be present on disk.
1291 10 : pub fn get_timeline_dir(conf: &SafeKeeperConf, ttid: &TenantTimelineId) -> Utf8PathBuf {
1292 10 : get_tenant_dir(conf, &ttid.tenant_id).join(ttid.timeline_id.to_string())
1293 10 : }
|