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 anyhow::{anyhow, bail, Result};
5 : use camino::Utf8PathBuf;
6 : use postgres_ffi::XLogSegNo;
7 : use serde::{Deserialize, Serialize};
8 : use tokio::fs;
9 :
10 : use std::cmp::max;
11 : use std::sync::Arc;
12 : use std::time::Duration;
13 : use tokio::sync::{Mutex, MutexGuard};
14 : use tokio::{
15 : sync::{mpsc::Sender, watch},
16 : time::Instant,
17 : };
18 : use tracing::*;
19 : use utils::http::error::ApiError;
20 : use utils::{
21 : id::{NodeId, TenantTimelineId},
22 : lsn::Lsn,
23 : };
24 :
25 : use storage_broker::proto::SafekeeperTimelineInfo;
26 : use storage_broker::proto::TenantTimelineId as ProtoTenantTimelineId;
27 :
28 : use crate::receive_wal::WalReceivers;
29 : use crate::recovery::{recovery_main, Donor, RecoveryNeededInfo};
30 : use crate::safekeeper::{
31 : AcceptorProposerMessage, ProposerAcceptorMessage, SafeKeeper, ServerInfo, Term, TermLsn,
32 : INVALID_TERM,
33 : };
34 : use crate::send_wal::WalSenders;
35 : use crate::state::{TimelineMemState, TimelinePersistentState};
36 : use crate::wal_backup::{self};
37 : use crate::{control_file, safekeeper::UNKNOWN_SERVER_VERSION};
38 :
39 : use crate::metrics::FullTimelineInfo;
40 : use crate::wal_storage::Storage as wal_storage_iface;
41 : use crate::{debug_dump, wal_storage};
42 : use crate::{GlobalTimelines, SafeKeeperConf};
43 :
44 : /// Things safekeeper should know about timeline state on peers.
45 12361 : #[derive(Debug, Clone, Serialize, Deserialize)]
46 : pub struct PeerInfo {
47 : pub sk_id: NodeId,
48 : pub term: Term,
49 : /// Term of the last entry.
50 : pub last_log_term: Term,
51 : /// LSN of the last record.
52 : pub flush_lsn: Lsn,
53 : pub commit_lsn: Lsn,
54 : /// Since which LSN safekeeper has WAL. TODO: remove this once we fill new
55 : /// sk since backup_lsn.
56 : pub local_start_lsn: Lsn,
57 : /// When info was received. Serde annotations are not very useful but make
58 : /// the code compile -- we don't rely on this field externally.
59 : #[serde(skip)]
60 : #[serde(default = "Instant::now")]
61 : ts: Instant,
62 : pub pg_connstr: String,
63 : pub http_connstr: String,
64 : }
65 :
66 : impl PeerInfo {
67 11104 : fn from_sk_info(sk_info: &SafekeeperTimelineInfo, ts: Instant) -> PeerInfo {
68 11104 : PeerInfo {
69 11104 : sk_id: NodeId(sk_info.safekeeper_id),
70 11104 : term: sk_info.term,
71 11104 : last_log_term: sk_info.last_log_term,
72 11104 : flush_lsn: Lsn(sk_info.flush_lsn),
73 11104 : commit_lsn: Lsn(sk_info.commit_lsn),
74 11104 : local_start_lsn: Lsn(sk_info.local_start_lsn),
75 11104 : pg_connstr: sk_info.safekeeper_connstr.clone(),
76 11104 : http_connstr: sk_info.http_connstr.clone(),
77 11104 : ts,
78 11104 : }
79 11104 : }
80 : }
81 :
82 : // vector-based node id -> peer state map with very limited functionality we
83 : // need.
84 0 : #[derive(Debug, Clone, Default)]
85 : pub struct PeersInfo(pub Vec<PeerInfo>);
86 :
87 : impl PeersInfo {
88 11104 : fn get(&mut self, id: NodeId) -> Option<&mut PeerInfo> {
89 15189 : self.0.iter_mut().find(|p| p.sk_id == id)
90 11104 : }
91 :
92 11104 : fn upsert(&mut self, p: &PeerInfo) {
93 11104 : match self.get(p.sk_id) {
94 10261 : Some(rp) => *rp = p.clone(),
95 843 : None => self.0.push(p.clone()),
96 : }
97 11104 : }
98 : }
99 :
100 : /// Shared state associated with database instance
101 : pub struct SharedState {
102 : /// Safekeeper object
103 : sk: SafeKeeper<control_file::FileStorage, wal_storage::PhysicalStorage>,
104 : /// In memory list containing state of peers sent in latest messages from them.
105 : peers_info: PeersInfo,
106 : /// True when WAL backup launcher oversees the timeline, making sure WAL is
107 : /// offloaded, allows to bother launcher less.
108 : wal_backup_active: bool,
109 : /// True whenever there is at least some pending activity on timeline: live
110 : /// compute connection, pageserver is not caughtup (it must have latest WAL
111 : /// for new compute start) or WAL backuping is not finished. Practically it
112 : /// means safekeepers broadcast info to peers about the timeline, old WAL is
113 : /// trimmed.
114 : ///
115 : /// TODO: it might be better to remove tli completely from GlobalTimelines
116 : /// when tli is inactive instead of having this flag.
117 : active: bool,
118 : last_removed_segno: XLogSegNo,
119 : }
120 :
121 : impl SharedState {
122 : /// Initialize fresh timeline state without persisting anything to disk.
123 479 : fn create_new(
124 479 : conf: &SafeKeeperConf,
125 479 : ttid: &TenantTimelineId,
126 479 : state: TimelinePersistentState,
127 479 : ) -> Result<Self> {
128 479 : if state.server.wal_seg_size == 0 {
129 0 : bail!(TimelineError::UninitializedWalSegSize(*ttid));
130 479 : }
131 479 :
132 479 : if state.server.pg_version == UNKNOWN_SERVER_VERSION {
133 0 : bail!(TimelineError::UninitialinzedPgVersion(*ttid));
134 479 : }
135 479 :
136 479 : if state.commit_lsn < state.local_start_lsn {
137 0 : bail!(
138 0 : "commit_lsn {} is higher than local_start_lsn {}",
139 0 : state.commit_lsn,
140 0 : state.local_start_lsn
141 0 : );
142 479 : }
143 479 :
144 479 : // We don't want to write anything to disk, because we may have existing timeline there.
145 479 : // These functions should not change anything on disk.
146 479 : let timeline_dir = conf.timeline_dir(ttid);
147 479 : let control_store = control_file::FileStorage::create_new(timeline_dir, conf, state)?;
148 479 : let wal_store =
149 479 : wal_storage::PhysicalStorage::new(ttid, conf.timeline_dir(ttid), conf, &control_store)?;
150 479 : let sk = SafeKeeper::new(control_store, wal_store, conf.my_id)?;
151 :
152 479 : Ok(Self {
153 479 : sk,
154 479 : peers_info: PeersInfo(vec![]),
155 479 : wal_backup_active: false,
156 479 : active: false,
157 479 : last_removed_segno: 0,
158 479 : })
159 479 : }
160 :
161 : /// Restore SharedState from control file. If file doesn't exist, bails out.
162 133 : fn restore(conf: &SafeKeeperConf, ttid: &TenantTimelineId) -> Result<Self> {
163 133 : let control_store = control_file::FileStorage::restore_new(ttid, conf)?;
164 133 : if control_store.server.wal_seg_size == 0 {
165 0 : bail!(TimelineError::UninitializedWalSegSize(*ttid));
166 133 : }
167 :
168 133 : let wal_store =
169 133 : wal_storage::PhysicalStorage::new(ttid, conf.timeline_dir(ttid), conf, &control_store)?;
170 :
171 : Ok(Self {
172 133 : sk: SafeKeeper::new(control_store, wal_store, conf.my_id)?,
173 133 : peers_info: PeersInfo(vec![]),
174 : wal_backup_active: false,
175 : active: false,
176 : last_removed_segno: 0,
177 : })
178 133 : }
179 :
180 15293 : fn is_active(&self, num_computes: usize) -> bool {
181 15293 : self.is_wal_backup_required(num_computes)
182 : // FIXME: add tracking of relevant pageservers and check them here individually,
183 : // otherwise migration won't work (we suspend too early).
184 2327 : || self.sk.state.inmem.remote_consistent_lsn < self.sk.state.inmem.commit_lsn
185 15293 : }
186 :
187 : /// Mark timeline active/inactive and return whether s3 offloading requires
188 : /// start/stop action. If timeline is deactivated, control file is persisted
189 : /// as maintenance task does that only for active timelines.
190 15293 : async fn update_status(&mut self, num_computes: usize, ttid: TenantTimelineId) -> bool {
191 15293 : let is_active = self.is_active(num_computes);
192 15293 : if self.active != is_active {
193 1537 : info!(
194 1537 : "timeline {} active={} now, remote_consistent_lsn={}, commit_lsn={}",
195 1537 : ttid,
196 1537 : is_active,
197 1537 : self.sk.state.inmem.remote_consistent_lsn,
198 1537 : self.sk.state.inmem.commit_lsn
199 1537 : );
200 1537 : if !is_active {
201 1484 : if let Err(e) = self.sk.state.flush().await {
202 0 : warn!("control file save in update_status failed: {:?}", e);
203 495 : }
204 1042 : }
205 13756 : }
206 15293 : self.active = is_active;
207 15293 : self.is_wal_backup_action_pending(num_computes)
208 15293 : }
209 :
210 : /// Should we run s3 offloading in current state?
211 43203 : fn is_wal_backup_required(&self, num_computes: usize) -> bool {
212 43203 : let seg_size = self.get_wal_seg_size();
213 43203 : num_computes > 0 ||
214 : // Currently only the whole segment is offloaded, so compare segment numbers.
215 11035 : (self.sk.state.inmem.commit_lsn.segment_number(seg_size) >
216 11035 : self.sk.state.inmem.backup_lsn.segment_number(seg_size))
217 43203 : }
218 :
219 : /// Is current state of s3 offloading is not what it ought to be?
220 15293 : fn is_wal_backup_action_pending(&self, num_computes: usize) -> bool {
221 15293 : let res = self.wal_backup_active != self.is_wal_backup_required(num_computes);
222 15293 : if res {
223 12466 : let action_pending = if self.is_wal_backup_required(num_computes) {
224 12403 : "start"
225 : } else {
226 63 : "stop"
227 : };
228 12466 : trace!(
229 0 : "timeline {} s3 offloading action {} pending: num_computes={}, commit_lsn={}, backup_lsn={}",
230 0 : self.sk.state.timeline_id, action_pending, num_computes, self.sk.state.inmem.commit_lsn, self.sk.state.inmem.backup_lsn
231 0 : );
232 2827 : }
233 15293 : res
234 15293 : }
235 :
236 : /// Returns whether s3 offloading is required and sets current status as
237 : /// matching.
238 151 : fn wal_backup_attend(&mut self, num_computes: usize) -> bool {
239 151 : self.wal_backup_active = self.is_wal_backup_required(num_computes);
240 151 : self.wal_backup_active
241 151 : }
242 :
243 43213 : fn get_wal_seg_size(&self) -> usize {
244 43213 : self.sk.state.server.wal_seg_size as usize
245 43213 : }
246 :
247 7862 : fn get_safekeeper_info(
248 7862 : &self,
249 7862 : ttid: &TenantTimelineId,
250 7862 : conf: &SafeKeeperConf,
251 7862 : ) -> SafekeeperTimelineInfo {
252 7862 : SafekeeperTimelineInfo {
253 7862 : safekeeper_id: conf.my_id.0,
254 7862 : tenant_timeline_id: Some(ProtoTenantTimelineId {
255 7862 : tenant_id: ttid.tenant_id.as_ref().to_owned(),
256 7862 : timeline_id: ttid.timeline_id.as_ref().to_owned(),
257 7862 : }),
258 7862 : term: self.sk.state.acceptor_state.term,
259 7862 : last_log_term: self.sk.get_epoch(),
260 7862 : flush_lsn: self.sk.flush_lsn().0,
261 7862 : // note: this value is not flushed to control file yet and can be lost
262 7862 : commit_lsn: self.sk.state.inmem.commit_lsn.0,
263 7862 : remote_consistent_lsn: self.sk.state.inmem.remote_consistent_lsn.0,
264 7862 : peer_horizon_lsn: self.sk.state.inmem.peer_horizon_lsn.0,
265 7862 : safekeeper_connstr: conf
266 7862 : .advertise_pg_addr
267 7862 : .to_owned()
268 7862 : .unwrap_or(conf.listen_pg_addr.clone()),
269 7862 : http_connstr: conf.listen_http_addr.to_owned(),
270 7862 : backup_lsn: self.sk.state.inmem.backup_lsn.0,
271 7862 : local_start_lsn: self.sk.state.local_start_lsn.0,
272 7862 : availability_zone: conf.availability_zone.clone(),
273 7862 : }
274 7862 : }
275 :
276 : /// Get our latest view of alive peers status on the timeline.
277 : /// We pass our own info through the broker as well, so when we don't have connection
278 : /// to the broker returned vec is empty.
279 511 : fn get_peers(&self, heartbeat_timeout: Duration) -> Vec<PeerInfo> {
280 511 : let now = Instant::now();
281 511 : self.peers_info
282 511 : .0
283 511 : .iter()
284 511 : // Regard peer as absent if we haven't heard from it within heartbeat_timeout.
285 1287 : .filter(|p| now.duration_since(p.ts) <= heartbeat_timeout)
286 511 : .cloned()
287 511 : .collect()
288 511 : }
289 : }
290 :
291 1 : #[derive(Debug, thiserror::Error)]
292 : pub enum TimelineError {
293 : #[error("Timeline {0} was cancelled and cannot be used anymore")]
294 : Cancelled(TenantTimelineId),
295 : #[error("Timeline {0} was not found in global map")]
296 : NotFound(TenantTimelineId),
297 : #[error("Timeline {0} exists on disk, but wasn't loaded on startup")]
298 : Invalid(TenantTimelineId),
299 : #[error("Timeline {0} is already exists")]
300 : AlreadyExists(TenantTimelineId),
301 : #[error("Timeline {0} is not initialized, wal_seg_size is zero")]
302 : UninitializedWalSegSize(TenantTimelineId),
303 : #[error("Timeline {0} is not initialized, pg_version is unknown")]
304 : UninitialinzedPgVersion(TenantTimelineId),
305 : }
306 :
307 : // Convert to HTTP API error.
308 : impl From<TimelineError> for ApiError {
309 0 : fn from(te: TimelineError) -> ApiError {
310 0 : match te {
311 0 : TimelineError::NotFound(ttid) => {
312 0 : ApiError::NotFound(anyhow!("timeline {} not found", ttid).into())
313 : }
314 0 : _ => ApiError::InternalServerError(anyhow!("{}", te)),
315 : }
316 0 : }
317 : }
318 :
319 : /// Timeline struct manages lifecycle (creation, deletion, restore) of a safekeeper timeline.
320 : /// It also holds SharedState and provides mutually exclusive access to it.
321 : pub struct Timeline {
322 : pub ttid: TenantTimelineId,
323 :
324 : /// Sending here asks for wal backup launcher attention (start/stop
325 : /// offloading). Sending ttid instead of concrete command allows to do
326 : /// sending without timeline lock.
327 : pub wal_backup_launcher_tx: Sender<TenantTimelineId>,
328 :
329 : /// Used to broadcast commit_lsn updates to all background jobs.
330 : commit_lsn_watch_tx: watch::Sender<Lsn>,
331 : commit_lsn_watch_rx: watch::Receiver<Lsn>,
332 :
333 : /// Broadcasts (current term, flush_lsn) updates, walsender is interested in
334 : /// them when sending in recovery mode (to walproposer or peers). Note: this
335 : /// is just a notification, WAL reading should always done with lock held as
336 : /// term can change otherwise.
337 : term_flush_lsn_watch_tx: watch::Sender<TermLsn>,
338 : term_flush_lsn_watch_rx: watch::Receiver<TermLsn>,
339 :
340 : /// Safekeeper and other state, that should remain consistent and
341 : /// synchronized with the disk. This is tokio mutex as we write WAL to disk
342 : /// while holding it, ensuring that consensus checks are in order.
343 : mutex: Mutex<SharedState>,
344 : walsenders: Arc<WalSenders>,
345 : walreceivers: Arc<WalReceivers>,
346 :
347 : /// Cancellation channel. Delete/cancel will send `true` here as a cancellation signal.
348 : cancellation_tx: watch::Sender<bool>,
349 :
350 : /// Timeline should not be used after cancellation. Background tasks should
351 : /// monitor this channel and stop eventually after receiving `true` from this channel.
352 : cancellation_rx: watch::Receiver<bool>,
353 :
354 : /// Directory where timeline state is stored.
355 : pub timeline_dir: Utf8PathBuf,
356 : }
357 :
358 : impl Timeline {
359 : /// Load existing timeline from disk.
360 133 : pub fn load_timeline(
361 133 : conf: &SafeKeeperConf,
362 133 : ttid: TenantTimelineId,
363 133 : wal_backup_launcher_tx: Sender<TenantTimelineId>,
364 133 : ) -> Result<Timeline> {
365 133 : let _enter = info_span!("load_timeline", timeline = %ttid.timeline_id).entered();
366 :
367 133 : let shared_state = SharedState::restore(conf, &ttid)?;
368 133 : let (commit_lsn_watch_tx, commit_lsn_watch_rx) =
369 133 : watch::channel(shared_state.sk.state.commit_lsn);
370 133 : let (term_flush_lsn_watch_tx, term_flush_lsn_watch_rx) = watch::channel(TermLsn::from((
371 133 : shared_state.sk.get_term(),
372 133 : shared_state.sk.flush_lsn(),
373 133 : )));
374 133 : let (cancellation_tx, cancellation_rx) = watch::channel(false);
375 133 :
376 133 : Ok(Timeline {
377 133 : ttid,
378 133 : wal_backup_launcher_tx,
379 133 : commit_lsn_watch_tx,
380 133 : commit_lsn_watch_rx,
381 133 : term_flush_lsn_watch_tx,
382 133 : term_flush_lsn_watch_rx,
383 133 : mutex: Mutex::new(shared_state),
384 133 : walsenders: WalSenders::new(),
385 133 : walreceivers: WalReceivers::new(),
386 133 : cancellation_rx,
387 133 : cancellation_tx,
388 133 : timeline_dir: conf.timeline_dir(&ttid),
389 133 : })
390 133 : }
391 :
392 : /// Create a new timeline, which is not yet persisted to disk.
393 479 : pub fn create_empty(
394 479 : conf: &SafeKeeperConf,
395 479 : ttid: TenantTimelineId,
396 479 : wal_backup_launcher_tx: Sender<TenantTimelineId>,
397 479 : server_info: ServerInfo,
398 479 : commit_lsn: Lsn,
399 479 : local_start_lsn: Lsn,
400 479 : ) -> Result<Timeline> {
401 479 : let (commit_lsn_watch_tx, commit_lsn_watch_rx) = watch::channel(Lsn::INVALID);
402 479 : let (term_flush_lsn_watch_tx, term_flush_lsn_watch_rx) =
403 479 : watch::channel(TermLsn::from((INVALID_TERM, Lsn::INVALID)));
404 479 : let (cancellation_tx, cancellation_rx) = watch::channel(false);
405 479 : let state =
406 479 : TimelinePersistentState::new(&ttid, server_info, vec![], commit_lsn, local_start_lsn);
407 479 :
408 479 : Ok(Timeline {
409 479 : ttid,
410 479 : wal_backup_launcher_tx,
411 479 : commit_lsn_watch_tx,
412 479 : commit_lsn_watch_rx,
413 479 : term_flush_lsn_watch_tx,
414 479 : term_flush_lsn_watch_rx,
415 479 : mutex: Mutex::new(SharedState::create_new(conf, &ttid, state)?),
416 479 : walsenders: WalSenders::new(),
417 479 : walreceivers: WalReceivers::new(),
418 479 : cancellation_rx,
419 479 : cancellation_tx,
420 479 : timeline_dir: conf.timeline_dir(&ttid),
421 : })
422 479 : }
423 :
424 : /// Initialize fresh timeline on disk and start background tasks. If init
425 : /// fails, timeline is cancelled and cannot be used anymore.
426 : ///
427 : /// Init is transactional, so if it fails, created files will be deleted,
428 : /// and state on disk should remain unchanged.
429 479 : pub async fn init_new(
430 479 : self: &Arc<Timeline>,
431 479 : shared_state: &mut MutexGuard<'_, SharedState>,
432 479 : conf: &SafeKeeperConf,
433 479 : ) -> Result<()> {
434 596 : match fs::metadata(&self.timeline_dir).await {
435 : Ok(_) => {
436 : // Timeline directory exists on disk, we should leave state unchanged
437 : // and return error.
438 0 : bail!(TimelineError::Invalid(self.ttid));
439 : }
440 479 : Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
441 0 : Err(e) => {
442 0 : return Err(e.into());
443 : }
444 : }
445 :
446 : // Create timeline directory.
447 510 : fs::create_dir_all(&self.timeline_dir).await?;
448 :
449 : // Write timeline to disk and start background tasks.
450 1557 : if let Err(e) = shared_state.sk.state.flush().await {
451 : // Bootstrap failed, cancel timeline and remove timeline directory.
452 0 : self.cancel(shared_state);
453 :
454 0 : if let Err(fs_err) = fs::remove_dir_all(&self.timeline_dir).await {
455 0 : warn!(
456 0 : "failed to remove timeline {} directory after bootstrap failure: {}",
457 0 : self.ttid, fs_err
458 0 : );
459 0 : }
460 :
461 0 : return Err(e);
462 479 : }
463 479 : self.bootstrap(conf);
464 479 : Ok(())
465 479 : }
466 :
467 : /// Bootstrap new or existing timeline starting background stasks.
468 612 : pub fn bootstrap(self: &Arc<Timeline>, conf: &SafeKeeperConf) {
469 612 : // Start recovery task which always runs on the timeline.
470 612 : if conf.peer_recovery_enabled {
471 1 : tokio::spawn(recovery_main(self.clone(), conf.clone()));
472 611 : }
473 612 : }
474 :
475 : /// Delete timeline from disk completely, by removing timeline directory.
476 : /// Background timeline activities will stop eventually.
477 : ///
478 : /// Also deletes WAL in s3. Might fail if e.g. s3 is unavailable, but
479 : /// deletion API endpoint is retriable.
480 28 : pub async fn delete(
481 28 : &self,
482 28 : shared_state: &mut MutexGuard<'_, SharedState>,
483 28 : only_local: bool,
484 28 : ) -> Result<(bool, bool)> {
485 28 : let was_active = shared_state.active;
486 28 : self.cancel(shared_state);
487 28 :
488 28 : // TODO: It's better to wait for s3 offloader termination before
489 28 : // removing data from s3. Though since s3 doesn't have transactions it
490 28 : // still wouldn't guarantee absense of data after removal.
491 28 : let conf = GlobalTimelines::get_global_config();
492 28 : if !only_local && conf.is_wal_backup_enabled() {
493 : // Note: we concurrently delete remote storage data from multiple
494 : // safekeepers. That's ok, s3 replies 200 if object doesn't exist and we
495 : // do some retries anyway.
496 31 : wal_backup::delete_timeline(&self.ttid).await?;
497 25 : }
498 28 : let dir_existed = delete_dir(&self.timeline_dir).await?;
499 28 : Ok((dir_existed, was_active))
500 28 : }
501 :
502 : /// Cancel timeline to prevent further usage. Background tasks will stop
503 : /// eventually after receiving cancellation signal.
504 : ///
505 : /// Note that we can't notify backup launcher here while holding
506 : /// shared_state lock, as this is a potential deadlock: caller is
507 : /// responsible for that. Generally we should probably make WAL backup tasks
508 : /// to shut down on their own, checking once in a while whether it is the
509 : /// time.
510 28 : fn cancel(&self, shared_state: &mut MutexGuard<'_, SharedState>) {
511 28 : info!("timeline {} is cancelled", self.ttid);
512 28 : let _ = self.cancellation_tx.send(true);
513 28 : // Close associated FDs. Nobody will be able to touch timeline data once
514 28 : // it is cancelled, so WAL storage won't be opened again.
515 28 : shared_state.sk.wal_store.close();
516 28 : }
517 :
518 : /// Returns if timeline is cancelled.
519 4380134 : pub fn is_cancelled(&self) -> bool {
520 4380134 : *self.cancellation_rx.borrow()
521 4380134 : }
522 :
523 : /// Returns watch channel which gets value when timeline is cancelled. It is
524 : /// guaranteed to have not cancelled value observed (errors otherwise).
525 1 : pub fn get_cancellation_rx(&self) -> Result<watch::Receiver<bool>> {
526 1 : let rx = self.cancellation_rx.clone();
527 1 : if *rx.borrow() {
528 0 : bail!(TimelineError::Cancelled(self.ttid));
529 1 : }
530 1 : Ok(rx)
531 1 : }
532 :
533 : /// Take a writing mutual exclusive lock on timeline shared_state.
534 5181514 : pub async fn write_shared_state(&self) -> MutexGuard<SharedState> {
535 5181514 : self.mutex.lock().await
536 5181513 : }
537 :
538 15293 : async fn update_status(&self, shared_state: &mut SharedState) -> bool {
539 15293 : shared_state
540 15293 : .update_status(self.walreceivers.get_num(), self.ttid)
541 1484 : .await
542 15293 : }
543 :
544 : /// Update timeline status and kick wal backup launcher to stop/start offloading if needed.
545 4189 : pub async fn update_status_notify(&self) -> Result<()> {
546 4189 : if self.is_cancelled() {
547 0 : bail!(TimelineError::Cancelled(self.ttid));
548 4189 : }
549 4189 : let is_wal_backup_action_pending: bool = {
550 4189 : let mut shared_state = self.write_shared_state().await;
551 4189 : self.update_status(&mut shared_state).await
552 : };
553 4189 : if is_wal_backup_action_pending {
554 : // Can fail only if channel to a static thread got closed, which is not normal at all.
555 2569 : self.wal_backup_launcher_tx.send(self.ttid).await?;
556 1620 : }
557 4189 : Ok(())
558 4189 : }
559 :
560 : /// Returns true if walsender should stop sending WAL to pageserver. We
561 : /// terminate it if remote_consistent_lsn reached commit_lsn and there is no
562 : /// computes. While there might be nothing to stream already, we learn about
563 : /// remote_consistent_lsn update through replication feedback, and we want
564 : /// to stop pushing to the broker if pageserver is fully caughtup.
565 3332 : pub async fn should_walsender_stop(&self, reported_remote_consistent_lsn: Lsn) -> bool {
566 3332 : if self.is_cancelled() {
567 0 : return true;
568 3332 : }
569 3332 : let shared_state = self.write_shared_state().await;
570 3332 : if self.walreceivers.get_num() == 0 {
571 868 : return shared_state.sk.state.inmem.commit_lsn == Lsn(0) || // no data at all yet
572 868 : reported_remote_consistent_lsn >= shared_state.sk.state.inmem.commit_lsn;
573 2464 : }
574 2464 : false
575 3332 : }
576 :
577 : /// Ensure taht current term is t, erroring otherwise, and lock the state.
578 2224 : pub async fn acquire_term(&self, t: Term) -> Result<MutexGuard<SharedState>> {
579 2224 : let ss = self.write_shared_state().await;
580 2224 : if ss.sk.state.acceptor_state.term != t {
581 1 : bail!(
582 1 : "failed to acquire term {}, current term {}",
583 1 : t,
584 1 : ss.sk.state.acceptor_state.term
585 1 : );
586 2223 : }
587 2223 : Ok(ss)
588 2224 : }
589 :
590 : /// Returns whether s3 offloading is required and sets current status as
591 : /// matching it.
592 151 : pub async fn wal_backup_attend(&self) -> bool {
593 151 : if self.is_cancelled() {
594 0 : return false;
595 151 : }
596 151 :
597 151 : self.write_shared_state()
598 37 : .await
599 151 : .wal_backup_attend(self.walreceivers.get_num())
600 151 : }
601 :
602 : /// Returns commit_lsn watch channel.
603 747 : pub fn get_commit_lsn_watch_rx(&self) -> watch::Receiver<Lsn> {
604 747 : self.commit_lsn_watch_rx.clone()
605 747 : }
606 :
607 : /// Returns term_flush_lsn watch channel.
608 19 : pub fn get_term_flush_lsn_watch_rx(&self) -> watch::Receiver<TermLsn> {
609 19 : self.term_flush_lsn_watch_rx.clone()
610 19 : }
611 :
612 : /// Pass arrived message to the safekeeper.
613 4337110 : pub async fn process_msg(
614 4337110 : &self,
615 4337110 : msg: &ProposerAcceptorMessage,
616 4337110 : ) -> Result<Option<AcceptorProposerMessage>> {
617 4337110 : if self.is_cancelled() {
618 0 : bail!(TimelineError::Cancelled(self.ttid));
619 4337110 : }
620 :
621 : let mut rmsg: Option<AcceptorProposerMessage>;
622 : let commit_lsn: Lsn;
623 : let term_flush_lsn: TermLsn;
624 : {
625 4337110 : let mut shared_state = self.write_shared_state().await;
626 4747097 : rmsg = shared_state.sk.process_msg(msg).await?;
627 :
628 : // if this is AppendResponse, fill in proper pageserver and hot
629 : // standby feedback.
630 4337108 : if let Some(AcceptorProposerMessage::AppendResponse(ref mut resp)) = rmsg {
631 1660289 : let (ps_feedback, hs_feedback) = self.walsenders.get_feedbacks();
632 1660289 : resp.hs_feedback = hs_feedback;
633 1660289 : resp.pageserver_feedback = ps_feedback;
634 2676819 : }
635 :
636 4337108 : commit_lsn = shared_state.sk.state.inmem.commit_lsn;
637 4337108 : term_flush_lsn =
638 4337108 : TermLsn::from((shared_state.sk.get_term(), shared_state.sk.flush_lsn()));
639 4337108 : }
640 4337108 : self.commit_lsn_watch_tx.send(commit_lsn)?;
641 4337108 : self.term_flush_lsn_watch_tx.send(term_flush_lsn)?;
642 4337108 : Ok(rmsg)
643 4337110 : }
644 :
645 : /// Returns wal_seg_size.
646 10 : pub async fn get_wal_seg_size(&self) -> usize {
647 10 : self.write_shared_state().await.get_wal_seg_size()
648 10 : }
649 :
650 : /// Returns true only if the timeline is loaded and active.
651 10054 : pub async fn is_active(&self) -> bool {
652 10054 : if self.is_cancelled() {
653 0 : return false;
654 10054 : }
655 10054 :
656 10054 : self.write_shared_state().await.active
657 10054 : }
658 :
659 : /// Returns state of the timeline.
660 2814 : pub async fn get_state(&self) -> (TimelineMemState, TimelinePersistentState) {
661 2814 : let state = self.write_shared_state().await;
662 2814 : (state.sk.state.inmem.clone(), state.sk.state.clone())
663 2814 : }
664 :
665 : /// Returns latest backup_lsn.
666 273 : pub async fn get_wal_backup_lsn(&self) -> Lsn {
667 273 : self.write_shared_state().await.sk.state.inmem.backup_lsn
668 273 : }
669 :
670 : /// Sets backup_lsn to the given value.
671 12 : pub async fn set_wal_backup_lsn(&self, backup_lsn: Lsn) -> Result<()> {
672 12 : if self.is_cancelled() {
673 0 : bail!(TimelineError::Cancelled(self.ttid));
674 12 : }
675 :
676 12 : let mut state = self.write_shared_state().await;
677 12 : state.sk.state.inmem.backup_lsn = max(state.sk.state.inmem.backup_lsn, backup_lsn);
678 12 : // we should check whether to shut down offloader, but this will be done
679 12 : // soon by peer communication anyway.
680 12 : Ok(())
681 12 : }
682 :
683 : /// Get safekeeper info for broadcasting to broker and other peers.
684 7862 : pub async fn get_safekeeper_info(&self, conf: &SafeKeeperConf) -> SafekeeperTimelineInfo {
685 7862 : let shared_state = self.write_shared_state().await;
686 7862 : shared_state.get_safekeeper_info(&self.ttid, conf)
687 7862 : }
688 :
689 : /// Update timeline state with peer safekeeper data.
690 11104 : pub async fn record_safekeeper_info(&self, sk_info: SafekeeperTimelineInfo) -> Result<()> {
691 : let is_wal_backup_action_pending: bool;
692 : let commit_lsn: Lsn;
693 : {
694 11104 : let mut shared_state = self.write_shared_state().await;
695 11104 : shared_state.sk.record_safekeeper_info(&sk_info).await?;
696 11104 : let peer_info = PeerInfo::from_sk_info(&sk_info, Instant::now());
697 11104 : shared_state.peers_info.upsert(&peer_info);
698 11104 : is_wal_backup_action_pending = self.update_status(&mut shared_state).await;
699 11104 : commit_lsn = shared_state.sk.state.inmem.commit_lsn;
700 11104 : }
701 11104 : self.commit_lsn_watch_tx.send(commit_lsn)?;
702 : // Wake up wal backup launcher, if it is time to stop the offloading.
703 11104 : if is_wal_backup_action_pending {
704 9897 : self.wal_backup_launcher_tx.send(self.ttid).await?;
705 1207 : }
706 11104 : Ok(())
707 11104 : }
708 :
709 : /// Update in memory remote consistent lsn.
710 797257 : pub async fn update_remote_consistent_lsn(&self, candidate: Lsn) {
711 797257 : let mut shared_state = self.write_shared_state().await;
712 797256 : shared_state.sk.state.inmem.remote_consistent_lsn =
713 797256 : max(shared_state.sk.state.inmem.remote_consistent_lsn, candidate);
714 797256 : }
715 :
716 508 : pub async fn get_peers(&self, conf: &SafeKeeperConf) -> Vec<PeerInfo> {
717 508 : let shared_state = self.write_shared_state().await;
718 508 : shared_state.get_peers(conf.heartbeat_timeout)
719 508 : }
720 :
721 : /// Should we start fetching WAL from a peer safekeeper, and if yes, from
722 : /// which? Answer is yes, i.e. .donors is not empty if 1) there is something
723 : /// to fetch, and we can do that without running elections; 2) there is no
724 : /// actively streaming compute, as we don't want to compete with it.
725 : ///
726 : /// If donor(s) are choosen, theirs last_log_term is guaranteed to be equal
727 : /// to its last_log_term so we are sure such a leader ever had been elected.
728 : ///
729 : /// All possible donors are returned so that we could keep connection to the
730 : /// current one if it is good even if it slightly lags behind.
731 : ///
732 : /// Note that term conditions above might be not met, but safekeepers are
733 : /// still not aligned on last flush_lsn. Generally in this case until
734 : /// elections are run it is not possible to say which safekeeper should
735 : /// recover from which one -- history which would be committed is different
736 : /// depending on assembled quorum (e.g. classic picture 8 from Raft paper).
737 : /// Thus we don't try to predict it here.
738 3 : pub async fn recovery_needed(&self, heartbeat_timeout: Duration) -> RecoveryNeededInfo {
739 3 : let ss = self.write_shared_state().await;
740 3 : let term = ss.sk.state.acceptor_state.term;
741 3 : let last_log_term = ss.sk.get_epoch();
742 3 : let flush_lsn = ss.sk.flush_lsn();
743 3 : // note that peers contain myself, but that's ok -- we are interested only in peers which are strictly ahead of us.
744 3 : let mut peers = ss.get_peers(heartbeat_timeout);
745 3 : // Sort by <last log term, lsn> pairs.
746 5 : peers.sort_by(|p1, p2| {
747 5 : let tl1 = TermLsn {
748 5 : term: p1.last_log_term,
749 5 : lsn: p1.flush_lsn,
750 5 : };
751 5 : let tl2 = TermLsn {
752 5 : term: p2.last_log_term,
753 5 : lsn: p2.flush_lsn,
754 5 : };
755 5 : tl2.cmp(&tl1) // desc
756 5 : });
757 3 : let num_streaming_computes = self.walreceivers.get_num_streaming();
758 3 : let donors = if num_streaming_computes > 0 {
759 0 : vec![] // If there is a streaming compute, don't try to recover to not intervene.
760 : } else {
761 3 : peers
762 3 : .iter()
763 6 : .filter_map(|candidate| {
764 6 : // Are we interested in this candidate?
765 6 : let candidate_tl = TermLsn {
766 6 : term: candidate.last_log_term,
767 6 : lsn: candidate.flush_lsn,
768 6 : };
769 6 : let my_tl = TermLsn {
770 6 : term: last_log_term,
771 6 : lsn: flush_lsn,
772 6 : };
773 6 : if my_tl < candidate_tl {
774 : // Yes, we are interested. Can we pull from it without
775 : // (re)running elections? It is possible if 1) his term
776 : // is equal to his last_log_term so we could act on
777 : // behalf of leader of this term (we must be sure he was
778 : // ever elected) and 2) our term is not higher, or we'll refuse data.
779 2 : if candidate.term == candidate.last_log_term && candidate.term >= term {
780 2 : Some(Donor::from(candidate))
781 : } else {
782 0 : None
783 : }
784 : } else {
785 4 : None
786 : }
787 6 : })
788 3 : .collect()
789 : };
790 3 : RecoveryNeededInfo {
791 3 : term,
792 3 : last_log_term,
793 3 : flush_lsn,
794 3 : peers,
795 3 : num_streaming_computes,
796 3 : donors,
797 3 : }
798 3 : }
799 :
800 1011 : pub fn get_walsenders(&self) -> &Arc<WalSenders> {
801 1011 : &self.walsenders
802 1011 : }
803 :
804 2104 : pub fn get_walreceivers(&self) -> &Arc<WalReceivers> {
805 2104 : &self.walreceivers
806 2104 : }
807 :
808 : /// Returns flush_lsn.
809 542 : pub async fn get_flush_lsn(&self) -> Lsn {
810 542 : self.write_shared_state().await.sk.wal_store.flush_lsn()
811 542 : }
812 :
813 : /// Delete WAL segments from disk that are no longer needed. This is determined
814 : /// based on pageserver's remote_consistent_lsn and local backup_lsn/peer_lsn.
815 1737 : pub async fn remove_old_wal(&self, wal_backup_enabled: bool) -> Result<()> {
816 1737 : if self.is_cancelled() {
817 0 : bail!(TimelineError::Cancelled(self.ttid));
818 1737 : }
819 :
820 : let horizon_segno: XLogSegNo;
821 31 : let remover = {
822 1737 : let shared_state = self.write_shared_state().await;
823 1737 : horizon_segno = shared_state.sk.get_horizon_segno(wal_backup_enabled);
824 1737 : if horizon_segno <= 1 || horizon_segno <= shared_state.last_removed_segno {
825 1706 : return Ok(()); // nothing to do
826 31 : }
827 31 :
828 31 : // release the lock before removing
829 31 : shared_state.sk.wal_store.remove_up_to(horizon_segno - 1)
830 31 : };
831 31 :
832 31 : // delete old WAL files
833 45 : remover.await?;
834 :
835 : // update last_removed_segno
836 31 : let mut shared_state = self.write_shared_state().await;
837 31 : shared_state.last_removed_segno = horizon_segno;
838 31 : Ok(())
839 1737 : }
840 :
841 : /// Persist control file if there is something to save and enough time
842 : /// passed after the last save. This helps to keep remote_consistent_lsn up
843 : /// to date so that storage nodes restart doesn't cause many pageserver ->
844 : /// safekeeper reconnections.
845 1737 : pub async fn maybe_persist_control_file(&self) -> Result<()> {
846 1737 : self.write_shared_state()
847 70 : .await
848 : .sk
849 1737 : .maybe_persist_inmem_control_file()
850 0 : .await
851 1737 : }
852 :
853 : /// Gather timeline data for metrics. If the timeline is not active, returns
854 : /// None, we do not collect these.
855 51 : pub async fn info_for_metrics(&self) -> Option<FullTimelineInfo> {
856 51 : if self.is_cancelled() {
857 0 : return None;
858 51 : }
859 51 :
860 51 : let ps_feedback = self.walsenders.get_ps_feedback();
861 51 : let state = self.write_shared_state().await;
862 51 : if state.active {
863 51 : Some(FullTimelineInfo {
864 51 : ttid: self.ttid,
865 51 : ps_feedback,
866 51 : wal_backup_active: state.wal_backup_active,
867 51 : timeline_is_active: state.active,
868 51 : num_computes: self.walreceivers.get_num() as u32,
869 51 : last_removed_segno: state.last_removed_segno,
870 51 : epoch_start_lsn: state.sk.epoch_start_lsn,
871 51 : mem_state: state.sk.state.inmem.clone(),
872 51 : persisted_state: state.sk.state.clone(),
873 51 : flush_lsn: state.sk.wal_store.flush_lsn(),
874 51 : wal_storage: state.sk.wal_store.get_metrics(),
875 51 : })
876 : } else {
877 0 : None
878 : }
879 51 : }
880 :
881 : /// Returns in-memory timeline state to build a full debug dump.
882 5 : pub async fn memory_dump(&self) -> debug_dump::Memory {
883 5 : let state = self.write_shared_state().await;
884 :
885 5 : let (write_lsn, write_record_lsn, flush_lsn, file_open) =
886 5 : state.sk.wal_store.internal_state();
887 5 :
888 5 : debug_dump::Memory {
889 5 : is_cancelled: self.is_cancelled(),
890 5 : peers_info_len: state.peers_info.0.len(),
891 5 : walsenders: self.walsenders.get_all(),
892 5 : wal_backup_active: state.wal_backup_active,
893 5 : active: state.active,
894 5 : num_computes: self.walreceivers.get_num() as u32,
895 5 : last_removed_segno: state.last_removed_segno,
896 5 : epoch_start_lsn: state.sk.epoch_start_lsn,
897 5 : mem_state: state.sk.state.inmem.clone(),
898 5 : write_lsn,
899 5 : write_record_lsn,
900 5 : flush_lsn,
901 5 : file_open,
902 5 : }
903 5 : }
904 :
905 : /// Apply a function to the control file state and persist it.
906 1 : pub async fn map_control_file<T>(
907 1 : &self,
908 1 : f: impl FnOnce(&mut TimelinePersistentState) -> Result<T>,
909 1 : ) -> Result<T> {
910 1 : let mut state = self.write_shared_state().await;
911 1 : let mut persistent_state = state.sk.state.start_change();
912 : // If f returns error, we abort the change and don't persist anything.
913 1 : let res = f(&mut persistent_state)?;
914 : // If persisting fails, we abort the change and return error.
915 3 : state.sk.state.finish_change(&persistent_state).await?;
916 1 : Ok(res)
917 1 : }
918 : }
919 :
920 : /// Deletes directory and it's contents. Returns false if directory does not exist.
921 28 : async fn delete_dir(path: &Utf8PathBuf) -> Result<bool> {
922 28 : match fs::remove_dir_all(path).await {
923 14 : Ok(_) => Ok(true),
924 14 : Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),
925 0 : Err(e) => Err(e.into()),
926 : }
927 28 : }
|