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