Line data Source code
1 : //! Acceptor part of proposer-acceptor consensus algorithm.
2 :
3 : use anyhow::{bail, Context, Result};
4 : use byteorder::{LittleEndian, ReadBytesExt};
5 : use bytes::{Buf, BufMut, Bytes, BytesMut};
6 :
7 : use postgres_ffi::{TimeLineID, MAX_SEND_SIZE};
8 : use serde::{Deserialize, Serialize};
9 : use std::cmp::max;
10 : use std::cmp::min;
11 : use std::fmt;
12 : use std::io::Read;
13 : use std::time::Duration;
14 : use storage_broker::proto::SafekeeperTimelineInfo;
15 :
16 : use tracing::*;
17 :
18 : use crate::control_file;
19 : use crate::send_wal::HotStandbyFeedback;
20 :
21 : use crate::state::TimelineState;
22 : use crate::wal_storage;
23 : use pq_proto::SystemId;
24 : use utils::pageserver_feedback::PageserverFeedback;
25 : use utils::{
26 : bin_ser::LeSer,
27 : id::{NodeId, TenantId, TimelineId},
28 : lsn::Lsn,
29 : };
30 :
31 : const SK_PROTOCOL_VERSION: u32 = 2;
32 : pub const UNKNOWN_SERVER_VERSION: u32 = 0;
33 :
34 : /// Consensus logical timestamp.
35 : pub type Term = u64;
36 : pub const INVALID_TERM: Term = 0;
37 :
38 8 : #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
39 : pub struct TermLsn {
40 : pub term: Term,
41 : pub lsn: Lsn,
42 : }
43 :
44 : // Creation from tuple provides less typing (e.g. for unit tests).
45 : impl From<(Term, Lsn)> for TermLsn {
46 36 : fn from(pair: (Term, Lsn)) -> TermLsn {
47 36 : TermLsn {
48 36 : term: pair.0,
49 36 : lsn: pair.1,
50 36 : }
51 36 : }
52 : }
53 :
54 12 : #[derive(Clone, Serialize, Deserialize, PartialEq)]
55 : pub struct TermHistory(pub Vec<TermLsn>);
56 :
57 : impl TermHistory {
58 11437 : pub fn empty() -> TermHistory {
59 11437 : TermHistory(Vec::new())
60 11437 : }
61 :
62 : // Parse TermHistory as n_entries followed by TermLsn pairs
63 6549 : pub fn from_bytes(bytes: &mut Bytes) -> Result<TermHistory> {
64 6549 : if bytes.remaining() < 4 {
65 0 : bail!("TermHistory misses len");
66 6549 : }
67 6549 : let n_entries = bytes.get_u32_le();
68 6549 : let mut res = Vec::with_capacity(n_entries as usize);
69 6549 : for _ in 0..n_entries {
70 50708 : if bytes.remaining() < 16 {
71 0 : bail!("TermHistory is incomplete");
72 50708 : }
73 50708 : res.push(TermLsn {
74 50708 : term: bytes.get_u64_le(),
75 50708 : lsn: bytes.get_u64_le().into(),
76 50708 : })
77 : }
78 6549 : Ok(TermHistory(res))
79 6549 : }
80 :
81 : /// Return copy of self with switches happening strictly after up_to
82 : /// truncated.
83 31300 : pub fn up_to(&self, up_to: Lsn) -> TermHistory {
84 31300 : let mut res = Vec::with_capacity(self.0.len());
85 158565 : for e in &self.0 {
86 127322 : if e.lsn > up_to {
87 57 : break;
88 127265 : }
89 127265 : res.push(*e);
90 : }
91 31300 : TermHistory(res)
92 31300 : }
93 :
94 : /// Find point of divergence between leader (walproposer) term history and
95 : /// safekeeper. Arguments are not symmetrics as proposer history ends at
96 : /// +infinity while safekeeper at flush_lsn.
97 : /// C version is at walproposer SendProposerElected.
98 8 : pub fn find_highest_common_point(
99 8 : prop_th: &TermHistory,
100 8 : sk_th: &TermHistory,
101 8 : sk_wal_end: Lsn,
102 8 : ) -> Option<TermLsn> {
103 8 : let (prop_th, sk_th) = (&prop_th.0, &sk_th.0); // avoid .0 below
104 :
105 8 : if let Some(sk_th_last) = sk_th.last() {
106 8 : assert!(
107 8 : sk_th_last.lsn <= sk_wal_end,
108 0 : "safekeeper term history end {:?} LSN is higher than WAL end {:?}",
109 : sk_th_last,
110 : sk_wal_end
111 : );
112 0 : }
113 :
114 : // find last common term, if any...
115 8 : let mut last_common_idx = None;
116 16 : for i in 0..min(sk_th.len(), prop_th.len()) {
117 16 : if prop_th[i].term != sk_th[i].term {
118 4 : break;
119 12 : }
120 12 : // If term is the same, LSN must be equal as well.
121 12 : assert!(
122 12 : prop_th[i].lsn == sk_th[i].lsn,
123 0 : "same term {} has different start LSNs: prop {}, sk {}",
124 0 : prop_th[i].term,
125 0 : prop_th[i].lsn,
126 0 : sk_th[i].lsn
127 : );
128 12 : last_common_idx = Some(i);
129 : }
130 8 : let last_common_idx = match last_common_idx {
131 2 : None => return None, // no common point
132 6 : Some(lci) => lci,
133 6 : };
134 6 : // Now find where it ends at both prop and sk and take min. End of
135 6 : // (common) term is the start of the next except it is the last one;
136 6 : // there it is flush_lsn in case of safekeeper or, in case of proposer
137 6 : // +infinity, so we just take flush_lsn then.
138 6 : if last_common_idx == prop_th.len() - 1 {
139 2 : Some(TermLsn {
140 2 : term: prop_th[last_common_idx].term,
141 2 : lsn: sk_wal_end,
142 2 : })
143 : } else {
144 4 : let prop_common_term_end = prop_th[last_common_idx + 1].lsn;
145 4 : let sk_common_term_end = if last_common_idx + 1 < sk_th.len() {
146 2 : sk_th[last_common_idx + 1].lsn
147 : } else {
148 2 : sk_wal_end
149 : };
150 4 : Some(TermLsn {
151 4 : term: prop_th[last_common_idx].term,
152 4 : lsn: min(prop_common_term_end, sk_common_term_end),
153 4 : })
154 : }
155 8 : }
156 : }
157 :
158 : /// Display only latest entries for Debug.
159 : impl fmt::Debug for TermHistory {
160 400 : fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
161 400 : let n_printed = 20;
162 400 : write!(
163 400 : fmt,
164 400 : "{}{:?}",
165 400 : if self.0.len() > n_printed { "... " } else { "" },
166 400 : self.0
167 400 : .iter()
168 400 : .rev()
169 400 : .take(n_printed)
170 2216 : .map(|&e| (e.term, e.lsn)) // omit TermSwitchEntry
171 400 : .collect::<Vec<_>>()
172 400 : )
173 400 : }
174 : }
175 :
176 : /// Unique id of proposer. Not needed for correctness, used for monitoring.
177 : pub type PgUuid = [u8; 16];
178 :
179 : /// Persistent consensus state of the acceptor.
180 12 : #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
181 : pub struct AcceptorState {
182 : /// acceptor's last term it voted for (advanced in 1 phase)
183 : pub term: Term,
184 : /// History of term switches for safekeeper's WAL.
185 : /// Actually it often goes *beyond* WAL contents as we adopt term history
186 : /// from the proposer before recovery.
187 : pub term_history: TermHistory,
188 : }
189 :
190 : impl AcceptorState {
191 : /// acceptor's epoch is the term of the highest entry in the log
192 6555 : pub fn get_epoch(&self, flush_lsn: Lsn) -> Term {
193 6555 : let th = self.term_history.up_to(flush_lsn);
194 6555 : match th.0.last() {
195 5455 : Some(e) => e.term,
196 1100 : None => 0,
197 : }
198 6555 : }
199 : }
200 :
201 : /// Information about Postgres. Safekeeper gets it once and then verifies
202 : /// all further connections from computes match.
203 8 : #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
204 : pub struct ServerInfo {
205 : /// Postgres server version
206 : pub pg_version: u32,
207 : pub system_id: SystemId,
208 : pub wal_seg_size: u32,
209 : }
210 :
211 4 : #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
212 : pub struct PersistedPeerInfo {
213 : /// LSN up to which safekeeper offloaded WAL to s3.
214 : pub backup_lsn: Lsn,
215 : /// Term of the last entry.
216 : pub term: Term,
217 : /// LSN of the last record.
218 : pub flush_lsn: Lsn,
219 : /// Up to which LSN safekeeper regards its WAL as committed.
220 : pub commit_lsn: Lsn,
221 : }
222 :
223 : impl PersistedPeerInfo {
224 0 : pub fn new() -> Self {
225 0 : Self {
226 0 : backup_lsn: Lsn::INVALID,
227 0 : term: INVALID_TERM,
228 0 : flush_lsn: Lsn(0),
229 0 : commit_lsn: Lsn(0),
230 0 : }
231 0 : }
232 : }
233 :
234 : // make clippy happy
235 : impl Default for PersistedPeerInfo {
236 0 : fn default() -> Self {
237 0 : Self::new()
238 0 : }
239 : }
240 :
241 : // protocol messages
242 :
243 : /// Initial Proposer -> Acceptor message
244 159121 : #[derive(Debug, Deserialize)]
245 : pub struct ProposerGreeting {
246 : /// proposer-acceptor protocol version
247 : pub protocol_version: u32,
248 : /// Postgres server version
249 : pub pg_version: u32,
250 : pub proposer_id: PgUuid,
251 : pub system_id: SystemId,
252 : pub timeline_id: TimelineId,
253 : pub tenant_id: TenantId,
254 : pub tli: TimeLineID,
255 : pub wal_seg_size: u32,
256 : }
257 :
258 : /// Acceptor -> Proposer initial response: the highest term known to me
259 : /// (acceptor voted for).
260 : #[derive(Debug, Serialize)]
261 : pub struct AcceptorGreeting {
262 : term: u64,
263 : node_id: NodeId,
264 : }
265 :
266 : /// Vote request sent from proposer to safekeepers
267 24741 : #[derive(Debug, Deserialize)]
268 : pub struct VoteRequest {
269 : pub term: Term,
270 : }
271 :
272 : /// Vote itself, sent from safekeeper to proposer
273 : #[derive(Debug, Serialize)]
274 : pub struct VoteResponse {
275 : pub term: Term, // safekeeper's current term; if it is higher than proposer's, the compute is out of date.
276 : vote_given: u64, // fixme u64 due to padding
277 : // Safekeeper flush_lsn (end of WAL) + history of term switches allow
278 : // proposer to choose the most advanced one.
279 : pub flush_lsn: Lsn,
280 : truncate_lsn: Lsn,
281 : pub term_history: TermHistory,
282 : timeline_start_lsn: Lsn,
283 : }
284 :
285 : /*
286 : * Proposer -> Acceptor message announcing proposer is elected and communicating
287 : * term history to it.
288 : */
289 : #[derive(Debug)]
290 : pub struct ProposerElected {
291 : pub term: Term,
292 : pub start_streaming_at: Lsn,
293 : pub term_history: TermHistory,
294 : pub timeline_start_lsn: Lsn,
295 : }
296 :
297 : /// Request with WAL message sent from proposer to safekeeper. Along the way it
298 : /// communicates commit_lsn.
299 : #[derive(Debug)]
300 : pub struct AppendRequest {
301 : pub h: AppendRequestHeader,
302 : pub wal_data: Bytes,
303 : }
304 21691 : #[derive(Debug, Clone, Deserialize)]
305 : pub struct AppendRequestHeader {
306 : // safekeeper's current term; if it is higher than proposer's, the compute is out of date.
307 : pub term: Term,
308 : // TODO: remove this field, it in unused -- LSN of term switch can be taken
309 : // from ProposerElected (as well as from term history).
310 : pub epoch_start_lsn: Lsn,
311 : /// start position of message in WAL
312 : pub begin_lsn: Lsn,
313 : /// end position of message in WAL
314 : pub end_lsn: Lsn,
315 : /// LSN committed by quorum of safekeepers
316 : pub commit_lsn: Lsn,
317 : /// minimal LSN which may be needed by proposer to perform recovery of some safekeeper
318 : pub truncate_lsn: Lsn,
319 : // only for logging/debugging
320 : pub proposer_uuid: PgUuid,
321 : }
322 :
323 : /// Report safekeeper state to proposer
324 : #[derive(Debug, Serialize, Clone)]
325 : pub struct AppendResponse {
326 : // Current term of the safekeeper; if it is higher than proposer's, the
327 : // compute is out of date.
328 : pub term: Term,
329 : // NOTE: this is physical end of wal on safekeeper; currently it doesn't
330 : // make much sense without taking epoch into account, as history can be
331 : // diverged.
332 : pub flush_lsn: Lsn,
333 : // We report back our awareness about which WAL is committed, as this is
334 : // a criterion for walproposer --sync mode exit
335 : pub commit_lsn: Lsn,
336 : pub hs_feedback: HotStandbyFeedback,
337 : pub pageserver_feedback: Option<PageserverFeedback>,
338 : }
339 :
340 : impl AppendResponse {
341 0 : fn term_only(term: Term) -> AppendResponse {
342 0 : AppendResponse {
343 0 : term,
344 0 : flush_lsn: Lsn(0),
345 0 : commit_lsn: Lsn(0),
346 0 : hs_feedback: HotStandbyFeedback::empty(),
347 0 : pageserver_feedback: None,
348 0 : }
349 0 : }
350 : }
351 :
352 : /// Proposer -> Acceptor messages
353 : #[derive(Debug)]
354 : pub enum ProposerAcceptorMessage {
355 : Greeting(ProposerGreeting),
356 : VoteRequest(VoteRequest),
357 : Elected(ProposerElected),
358 : AppendRequest(AppendRequest),
359 : NoFlushAppendRequest(AppendRequest),
360 : FlushWAL,
361 : }
362 :
363 : impl ProposerAcceptorMessage {
364 : /// Parse proposer message.
365 212102 : pub fn parse(msg_bytes: Bytes) -> Result<ProposerAcceptorMessage> {
366 212102 : // xxx using Reader is inefficient but easy to work with bincode
367 212102 : let mut stream = msg_bytes.reader();
368 : // u64 is here to avoid padding; it will be removed once we stop packing C structs into the wire as is
369 212102 : let tag = stream.read_u64::<LittleEndian>()? as u8 as char;
370 212102 : match tag {
371 : 'g' => {
372 159121 : let msg = ProposerGreeting::des_from(&mut stream)?;
373 159121 : Ok(ProposerAcceptorMessage::Greeting(msg))
374 : }
375 : 'v' => {
376 24741 : let msg = VoteRequest::des_from(&mut stream)?;
377 24741 : Ok(ProposerAcceptorMessage::VoteRequest(msg))
378 : }
379 : 'e' => {
380 6549 : let mut msg_bytes = stream.into_inner();
381 6549 : if msg_bytes.remaining() < 16 {
382 0 : bail!("ProposerElected message is not complete");
383 6549 : }
384 6549 : let term = msg_bytes.get_u64_le();
385 6549 : let start_streaming_at = msg_bytes.get_u64_le().into();
386 6549 : let term_history = TermHistory::from_bytes(&mut msg_bytes)?;
387 6549 : if msg_bytes.remaining() < 8 {
388 0 : bail!("ProposerElected message is not complete");
389 6549 : }
390 6549 : let timeline_start_lsn = msg_bytes.get_u64_le().into();
391 6549 : let msg = ProposerElected {
392 6549 : term,
393 6549 : start_streaming_at,
394 6549 : timeline_start_lsn,
395 6549 : term_history,
396 6549 : };
397 6549 : Ok(ProposerAcceptorMessage::Elected(msg))
398 : }
399 : 'a' => {
400 : // read header followed by wal data
401 21691 : let hdr = AppendRequestHeader::des_from(&mut stream)?;
402 21691 : let rec_size = hdr
403 21691 : .end_lsn
404 21691 : .checked_sub(hdr.begin_lsn)
405 21691 : .context("begin_lsn > end_lsn in AppendRequest")?
406 : .0 as usize;
407 21691 : if rec_size > MAX_SEND_SIZE {
408 0 : bail!(
409 0 : "AppendRequest is longer than MAX_SEND_SIZE ({})",
410 0 : MAX_SEND_SIZE
411 0 : );
412 21691 : }
413 21691 :
414 21691 : let mut wal_data_vec: Vec<u8> = vec![0; rec_size];
415 21691 : stream.read_exact(&mut wal_data_vec)?;
416 21691 : let wal_data = Bytes::from(wal_data_vec);
417 21691 : let msg = AppendRequest { h: hdr, wal_data };
418 21691 :
419 21691 : Ok(ProposerAcceptorMessage::AppendRequest(msg))
420 : }
421 0 : _ => bail!("unknown proposer-acceptor message tag: {}", tag),
422 : }
423 212102 : }
424 : }
425 :
426 : /// Acceptor -> Proposer messages
427 : #[derive(Debug)]
428 : pub enum AcceptorProposerMessage {
429 : Greeting(AcceptorGreeting),
430 : VoteResponse(VoteResponse),
431 : AppendResponse(AppendResponse),
432 : }
433 :
434 : impl AcceptorProposerMessage {
435 : /// Serialize acceptor -> proposer message.
436 201826 : pub fn serialize(&self, buf: &mut BytesMut) -> Result<()> {
437 201826 : match self {
438 159121 : AcceptorProposerMessage::Greeting(msg) => {
439 159121 : buf.put_u64_le('g' as u64);
440 159121 : buf.put_u64_le(msg.term);
441 159121 : buf.put_u64_le(msg.node_id.0);
442 159121 : }
443 24741 : AcceptorProposerMessage::VoteResponse(msg) => {
444 24741 : buf.put_u64_le('v' as u64);
445 24741 : buf.put_u64_le(msg.term);
446 24741 : buf.put_u64_le(msg.vote_given);
447 24741 : buf.put_u64_le(msg.flush_lsn.into());
448 24741 : buf.put_u64_le(msg.truncate_lsn.into());
449 24741 : buf.put_u32_le(msg.term_history.0.len() as u32);
450 108418 : for e in &msg.term_history.0 {
451 83677 : buf.put_u64_le(e.term);
452 83677 : buf.put_u64_le(e.lsn.into());
453 83677 : }
454 24741 : buf.put_u64_le(msg.timeline_start_lsn.into());
455 : }
456 17964 : AcceptorProposerMessage::AppendResponse(msg) => {
457 17964 : buf.put_u64_le('a' as u64);
458 17964 : buf.put_u64_le(msg.term);
459 17964 : buf.put_u64_le(msg.flush_lsn.into());
460 17964 : buf.put_u64_le(msg.commit_lsn.into());
461 17964 : buf.put_i64_le(msg.hs_feedback.ts);
462 17964 : buf.put_u64_le(msg.hs_feedback.xmin);
463 17964 : buf.put_u64_le(msg.hs_feedback.catalog_xmin);
464 :
465 : // AsyncReadMessage in walproposer.c will not try to decode pageserver_feedback
466 : // if it is not present.
467 17964 : if let Some(ref msg) = msg.pageserver_feedback {
468 0 : msg.serialize(buf);
469 17964 : }
470 : }
471 : }
472 :
473 201826 : Ok(())
474 201826 : }
475 : }
476 :
477 : /// Safekeeper implements consensus to reliably persist WAL across nodes.
478 : /// It controls all WAL disk writes and updates of control file.
479 : ///
480 : /// Currently safekeeper processes:
481 : /// - messages from compute (proposers) and provides replies
482 : /// - messages from broker peers
483 : pub struct SafeKeeper<CTRL: control_file::Storage, WAL: wal_storage::Storage> {
484 : /// LSN since the proposer safekeeper currently talking to appends WAL;
485 : /// determines epoch switch point.
486 : pub epoch_start_lsn: Lsn,
487 :
488 : pub state: TimelineState<CTRL>, // persistent state storage
489 : pub wal_store: WAL,
490 :
491 : node_id: NodeId, // safekeeper's node id
492 : }
493 :
494 : impl<CTRL, WAL> SafeKeeper<CTRL, WAL>
495 : where
496 : CTRL: control_file::Storage,
497 : WAL: wal_storage::Storage,
498 : {
499 : /// Accepts a control file storage containing the safekeeper state.
500 : /// State must be initialized, i.e. contain filled `tenant_id`, `timeline_id`
501 : /// and `server` (`wal_seg_size` inside it) fields.
502 70729 : pub fn new(state: CTRL, wal_store: WAL, node_id: NodeId) -> Result<SafeKeeper<CTRL, WAL>> {
503 70729 : if state.tenant_id == TenantId::from([0u8; 16])
504 70729 : || state.timeline_id == TimelineId::from([0u8; 16])
505 : {
506 0 : bail!(
507 0 : "Calling SafeKeeper::new with empty tenant_id ({}) or timeline_id ({})",
508 0 : state.tenant_id,
509 0 : state.timeline_id
510 0 : );
511 70729 : }
512 70729 :
513 70729 : Ok(SafeKeeper {
514 70729 : epoch_start_lsn: Lsn(0),
515 70729 : state: TimelineState::new(state),
516 70729 : wal_store,
517 70729 : node_id,
518 70729 : })
519 70729 : }
520 :
521 : /// Get history of term switches for the available WAL
522 24745 : fn get_term_history(&self) -> TermHistory {
523 24745 : self.state
524 24745 : .acceptor_state
525 24745 : .term_history
526 24745 : .up_to(self.flush_lsn())
527 24745 : }
528 :
529 : /// Get current term.
530 0 : pub fn get_term(&self) -> Term {
531 0 : self.state.acceptor_state.term
532 0 : }
533 :
534 6555 : pub fn get_epoch(&self) -> Term {
535 6555 : self.state.acceptor_state.get_epoch(self.flush_lsn())
536 6555 : }
537 :
538 : /// wal_store wrapper avoiding commit_lsn <= flush_lsn violation when we don't have WAL yet.
539 85271 : pub fn flush_lsn(&self) -> Lsn {
540 85271 : max(self.wal_store.flush_lsn(), self.state.timeline_start_lsn)
541 85271 : }
542 :
543 : /// Process message from proposer and possibly form reply. Concurrent
544 : /// callers must exclude each other.
545 230076 : pub async fn process_msg(
546 230076 : &mut self,
547 230076 : msg: &ProposerAcceptorMessage,
548 230076 : ) -> Result<Option<AcceptorProposerMessage>> {
549 230076 : match msg {
550 159121 : ProposerAcceptorMessage::Greeting(msg) => self.handle_greeting(msg).await,
551 24745 : ProposerAcceptorMessage::VoteRequest(msg) => self.handle_vote_request(msg).await,
552 6551 : ProposerAcceptorMessage::Elected(msg) => self.handle_elected(msg).await,
553 4 : ProposerAcceptorMessage::AppendRequest(msg) => {
554 4 : self.handle_append_request(msg, true).await
555 : }
556 21691 : ProposerAcceptorMessage::NoFlushAppendRequest(msg) => {
557 21691 : self.handle_append_request(msg, false).await
558 : }
559 17964 : ProposerAcceptorMessage::FlushWAL => self.handle_flush().await,
560 : }
561 230076 : }
562 :
563 : /// Handle initial message from proposer: check its sanity and send my
564 : /// current term.
565 159121 : async fn handle_greeting(
566 159121 : &mut self,
567 159121 : msg: &ProposerGreeting,
568 159121 : ) -> Result<Option<AcceptorProposerMessage>> {
569 159121 : // Check protocol compatibility
570 159121 : if msg.protocol_version != SK_PROTOCOL_VERSION {
571 0 : bail!(
572 0 : "incompatible protocol version {}, expected {}",
573 0 : msg.protocol_version,
574 0 : SK_PROTOCOL_VERSION
575 0 : );
576 159121 : }
577 159121 : /* Postgres major version mismatch is treated as fatal error
578 159121 : * because safekeepers parse WAL headers and the format
579 159121 : * may change between versions.
580 159121 : */
581 159121 : if msg.pg_version / 10000 != self.state.server.pg_version / 10000
582 0 : && self.state.server.pg_version != UNKNOWN_SERVER_VERSION
583 : {
584 0 : bail!(
585 0 : "incompatible server version {}, expected {}",
586 0 : msg.pg_version,
587 0 : self.state.server.pg_version
588 0 : );
589 159121 : }
590 159121 :
591 159121 : if msg.tenant_id != self.state.tenant_id {
592 0 : bail!(
593 0 : "invalid tenant ID, got {}, expected {}",
594 0 : msg.tenant_id,
595 0 : self.state.tenant_id
596 0 : );
597 159121 : }
598 159121 : if msg.timeline_id != self.state.timeline_id {
599 0 : bail!(
600 0 : "invalid timeline ID, got {}, expected {}",
601 0 : msg.timeline_id,
602 0 : self.state.timeline_id
603 0 : );
604 159121 : }
605 159121 : if self.state.server.wal_seg_size != msg.wal_seg_size {
606 0 : bail!(
607 0 : "invalid wal_seg_size, got {}, expected {}",
608 0 : msg.wal_seg_size,
609 0 : self.state.server.wal_seg_size
610 0 : );
611 159121 : }
612 159121 :
613 159121 : // system_id will be updated on mismatch
614 159121 : // sync-safekeepers doesn't know sysid and sends 0, ignore it
615 159121 : if self.state.server.system_id != msg.system_id && msg.system_id != 0 {
616 0 : if self.state.server.system_id != 0 {
617 0 : warn!(
618 0 : "unexpected system ID arrived, got {}, expected {}",
619 0 : msg.system_id, self.state.server.system_id
620 : );
621 0 : }
622 :
623 0 : let mut state = self.state.start_change();
624 0 : state.server.system_id = msg.system_id;
625 0 : if msg.pg_version != UNKNOWN_SERVER_VERSION {
626 0 : state.server.pg_version = msg.pg_version;
627 0 : }
628 0 : self.state.finish_change(&state).await?;
629 159121 : }
630 :
631 159121 : info!(
632 0 : "processed greeting from walproposer {}, sending term {:?}",
633 4832 : msg.proposer_id.map(|b| format!("{:X}", b)).join(""),
634 0 : self.state.acceptor_state.term
635 : );
636 159121 : Ok(Some(AcceptorProposerMessage::Greeting(AcceptorGreeting {
637 159121 : term: self.state.acceptor_state.term,
638 159121 : node_id: self.node_id,
639 159121 : })))
640 159121 : }
641 :
642 : /// Give vote for the given term, if we haven't done that previously.
643 24745 : async fn handle_vote_request(
644 24745 : &mut self,
645 24745 : msg: &VoteRequest,
646 24745 : ) -> Result<Option<AcceptorProposerMessage>> {
647 24745 : // Once voted, we won't accept data from older proposers; flush
648 24745 : // everything we've already received so that new proposer starts
649 24745 : // streaming at end of our WAL, without overlap. Currently we truncate
650 24745 : // WAL at streaming point, so this avoids truncating already committed
651 24745 : // WAL.
652 24745 : //
653 24745 : // TODO: it would be smoother to not truncate committed piece at
654 24745 : // handle_elected instead. Currently not a big deal, as proposer is the
655 24745 : // only source of WAL; with peer2peer recovery it would be more
656 24745 : // important.
657 24745 : self.wal_store.flush_wal().await?;
658 : // initialize with refusal
659 24745 : let mut resp = VoteResponse {
660 24745 : term: self.state.acceptor_state.term,
661 24745 : vote_given: false as u64,
662 24745 : flush_lsn: self.flush_lsn(),
663 24745 : truncate_lsn: self.state.inmem.peer_horizon_lsn,
664 24745 : term_history: self.get_term_history(),
665 24745 : timeline_start_lsn: self.state.timeline_start_lsn,
666 24745 : };
667 24745 : if self.state.acceptor_state.term < msg.term {
668 23475 : let mut state = self.state.start_change();
669 23475 : state.acceptor_state.term = msg.term;
670 23475 : // persist vote before sending it out
671 23475 : self.state.finish_change(&state).await?;
672 :
673 23475 : resp.term = self.state.acceptor_state.term;
674 23475 : resp.vote_given = true as u64;
675 1270 : }
676 24745 : info!("processed VoteRequest for term {}: {:?}", msg.term, &resp);
677 24745 : Ok(Some(AcceptorProposerMessage::VoteResponse(resp)))
678 24745 : }
679 :
680 : /// Form AppendResponse from current state.
681 17968 : fn append_response(&self) -> AppendResponse {
682 17968 : let ar = AppendResponse {
683 17968 : term: self.state.acceptor_state.term,
684 17968 : flush_lsn: self.flush_lsn(),
685 17968 : commit_lsn: self.state.commit_lsn,
686 17968 : // will be filled by the upper code to avoid bothering safekeeper
687 17968 : hs_feedback: HotStandbyFeedback::empty(),
688 17968 : pageserver_feedback: None,
689 17968 : };
690 17968 : trace!("formed AppendResponse {:?}", ar);
691 17968 : ar
692 17968 : }
693 :
694 6551 : async fn handle_elected(
695 6551 : &mut self,
696 6551 : msg: &ProposerElected,
697 6551 : ) -> Result<Option<AcceptorProposerMessage>> {
698 6551 : info!("received ProposerElected {:?}", msg);
699 6551 : if self.state.acceptor_state.term < msg.term {
700 2 : let mut state = self.state.start_change();
701 2 : state.acceptor_state.term = msg.term;
702 2 : self.state.finish_change(&state).await?;
703 6549 : }
704 :
705 : // If our term is higher, ignore the message (next feedback will inform the compute)
706 6551 : if self.state.acceptor_state.term > msg.term {
707 0 : return Ok(None);
708 6551 : }
709 6551 :
710 6551 : // This might happen in a rare race when another (old) connection from
711 6551 : // the same walproposer writes + flushes WAL after this connection
712 6551 : // already sent flush_lsn in VoteRequest. It is generally safe to
713 6551 : // proceed, but to prevent commit_lsn surprisingly going down we should
714 6551 : // either refuse the session (simpler) or skip the part we already have
715 6551 : // from the stream (can be implemented).
716 6551 : if msg.term == self.get_epoch() && self.flush_lsn() > msg.start_streaming_at {
717 0 : bail!("refusing ProposerElected which is going to overwrite correct WAL: term={}, flush_lsn={}, start_streaming_at={}; restarting the handshake should help",
718 0 : msg.term, self.flush_lsn(), msg.start_streaming_at)
719 6551 : }
720 6551 : // Otherwise we must never attempt to truncate committed data.
721 6551 : assert!(
722 6551 : msg.start_streaming_at >= self.state.inmem.commit_lsn,
723 0 : "attempt to truncate committed data: start_streaming_at={}, commit_lsn={}",
724 : msg.start_streaming_at,
725 : self.state.inmem.commit_lsn
726 : );
727 :
728 : // Before first WAL write initialize its segment. It makes first segment
729 : // pg_waldump'able because stream from compute doesn't include its
730 : // segment and page headers.
731 : //
732 : // If we fail before first WAL write flush this action would be
733 : // repeated, that's ok because it is idempotent.
734 6551 : if self.wal_store.flush_lsn() == Lsn::INVALID {
735 1098 : self.wal_store
736 1098 : .initialize_first_segment(msg.start_streaming_at)
737 0 : .await?;
738 5453 : }
739 :
740 : // TODO: cross check divergence point, check if msg.start_streaming_at corresponds to
741 : // intersection of our history and history from msg
742 :
743 : // truncate wal, update the LSNs
744 6551 : self.wal_store.truncate_wal(msg.start_streaming_at).await?;
745 :
746 : // and now adopt term history from proposer
747 : {
748 6551 : let mut state = self.state.start_change();
749 6551 :
750 6551 : // Here we learn initial LSN for the first time, set fields
751 6551 : // interested in that.
752 6551 :
753 6551 : if state.timeline_start_lsn == Lsn(0) {
754 : // Remember point where WAL begins globally.
755 1098 : state.timeline_start_lsn = msg.timeline_start_lsn;
756 1098 : info!(
757 0 : "setting timeline_start_lsn to {:?}",
758 : state.timeline_start_lsn
759 : );
760 5453 : }
761 6551 : if state.peer_horizon_lsn == Lsn(0) {
762 1098 : // Update peer_horizon_lsn as soon as we know where timeline starts.
763 1098 : // It means that peer_horizon_lsn cannot be zero after we know timeline_start_lsn.
764 1098 : state.peer_horizon_lsn = msg.timeline_start_lsn;
765 5453 : }
766 6551 : if state.local_start_lsn == Lsn(0) {
767 1098 : state.local_start_lsn = msg.start_streaming_at;
768 1098 : info!("setting local_start_lsn to {:?}", state.local_start_lsn);
769 5453 : }
770 : // Initializing commit_lsn before acking first flushed record is
771 : // important to let find_end_of_wal skip the hole in the beginning
772 : // of the first segment.
773 : //
774 : // NB: on new clusters, this happens at the same time as
775 : // timeline_start_lsn initialization, it is taken outside to provide
776 : // upgrade.
777 6551 : state.commit_lsn = max(state.commit_lsn, state.timeline_start_lsn);
778 6551 :
779 6551 : // Initializing backup_lsn is useful to avoid making backup think it should upload 0 segment.
780 6551 : state.backup_lsn = max(state.backup_lsn, state.timeline_start_lsn);
781 6551 :
782 6551 : state.acceptor_state.term_history = msg.term_history.clone();
783 6551 : self.state.finish_change(&state).await?;
784 : }
785 :
786 6551 : info!("start receiving WAL since {:?}", msg.start_streaming_at);
787 :
788 : // Cache LSN where term starts to immediately fsync control file with
789 : // commit_lsn once we reach it -- sync-safekeepers finishes when
790 : // persisted commit_lsn on majority of safekeepers aligns.
791 6551 : self.epoch_start_lsn = match msg.term_history.0.last() {
792 0 : None => bail!("proposer elected with empty term history"),
793 6551 : Some(term_lsn_start) => term_lsn_start.lsn,
794 6551 : };
795 6551 :
796 6551 : Ok(None)
797 6551 : }
798 :
799 : /// Advance commit_lsn taking into account what we have locally.
800 : ///
801 : /// Note: it is assumed that 'WAL we have is from the right term' check has
802 : /// already been done outside.
803 10834 : async fn update_commit_lsn(&mut self, mut candidate: Lsn) -> Result<()> {
804 10834 : // Both peers and walproposer communicate this value, we might already
805 10834 : // have a fresher (higher) version.
806 10834 : candidate = max(candidate, self.state.inmem.commit_lsn);
807 10834 : let commit_lsn = min(candidate, self.flush_lsn());
808 10834 : assert!(
809 10834 : commit_lsn >= self.state.inmem.commit_lsn,
810 0 : "commit_lsn monotonicity violated: old={} new={}",
811 : self.state.inmem.commit_lsn,
812 : commit_lsn
813 : );
814 :
815 10834 : self.state.inmem.commit_lsn = commit_lsn;
816 10834 :
817 10834 : // If new commit_lsn reached epoch switch, force sync of control
818 10834 : // file: walproposer in sync mode is very interested when this
819 10834 : // happens. Note: this is for sync-safekeepers mode only, as
820 10834 : // otherwise commit_lsn might jump over epoch_start_lsn.
821 10834 : if commit_lsn >= self.epoch_start_lsn && self.state.commit_lsn < self.epoch_start_lsn {
822 848 : self.state.flush().await?;
823 9986 : }
824 :
825 10834 : Ok(())
826 10834 : }
827 :
828 : /// Persist control file if there is something to save and enough time
829 : /// passed after the last save.
830 0 : pub async fn maybe_persist_inmem_control_file(&mut self) -> Result<()> {
831 0 : const CF_SAVE_INTERVAL: Duration = Duration::from_secs(300);
832 0 : if self.state.pers.last_persist_at().elapsed() < CF_SAVE_INTERVAL {
833 0 : return Ok(());
834 0 : }
835 0 : let need_persist = self.state.inmem.commit_lsn > self.state.commit_lsn
836 0 : || self.state.inmem.backup_lsn > self.state.backup_lsn
837 0 : || self.state.inmem.peer_horizon_lsn > self.state.peer_horizon_lsn
838 0 : || self.state.inmem.remote_consistent_lsn > self.state.remote_consistent_lsn;
839 0 : if need_persist {
840 0 : self.state.flush().await?;
841 0 : trace!("saved control file: {CF_SAVE_INTERVAL:?} passed");
842 0 : }
843 0 : Ok(())
844 0 : }
845 :
846 : /// Handle request to append WAL.
847 : #[allow(clippy::comparison_chain)]
848 21695 : async fn handle_append_request(
849 21695 : &mut self,
850 21695 : msg: &AppendRequest,
851 21695 : require_flush: bool,
852 21695 : ) -> Result<Option<AcceptorProposerMessage>> {
853 21695 : if self.state.acceptor_state.term < msg.h.term {
854 0 : bail!("got AppendRequest before ProposerElected");
855 21695 : }
856 21695 :
857 21695 : // If our term is higher, immediately refuse the message.
858 21695 : if self.state.acceptor_state.term > msg.h.term {
859 0 : let resp = AppendResponse::term_only(self.state.acceptor_state.term);
860 0 : return Ok(Some(AcceptorProposerMessage::AppendResponse(resp)));
861 21695 : }
862 21695 :
863 21695 : // Now we know that we are in the same term as the proposer,
864 21695 : // processing the message.
865 21695 :
866 21695 : self.state.inmem.proposer_uuid = msg.h.proposer_uuid;
867 21695 :
868 21695 : // do the job
869 21695 : if !msg.wal_data.is_empty() {
870 4148 : self.wal_store
871 4148 : .write_wal(msg.h.begin_lsn, &msg.wal_data)
872 0 : .await?;
873 17547 : }
874 :
875 : // flush wal to the disk, if required
876 21695 : if require_flush {
877 4 : self.wal_store.flush_wal().await?;
878 21691 : }
879 :
880 : // Update commit_lsn.
881 21695 : if msg.h.commit_lsn != Lsn(0) {
882 10834 : self.update_commit_lsn(msg.h.commit_lsn).await?;
883 10861 : }
884 : // Value calculated by walproposer can always lag:
885 : // - safekeepers can forget inmem value and send to proposer lower
886 : // persisted one on restart;
887 : // - if we make safekeepers always send persistent value,
888 : // any compute restart would pull it down.
889 : // Thus, take max before adopting.
890 21695 : self.state.inmem.peer_horizon_lsn =
891 21695 : max(self.state.inmem.peer_horizon_lsn, msg.h.truncate_lsn);
892 21695 :
893 21695 : // Update truncate and commit LSN in control file.
894 21695 : // To avoid negative impact on performance of extra fsync, do it only
895 21695 : // when commit_lsn delta exceeds WAL segment size.
896 21695 : if self.state.commit_lsn + (self.state.server.wal_seg_size as u64)
897 21695 : < self.state.inmem.commit_lsn
898 : {
899 0 : self.state.flush().await?;
900 21695 : }
901 :
902 21695 : trace!(
903 0 : "processed AppendRequest of len {}, end_lsn={:?}, commit_lsn={:?}, truncate_lsn={:?}, flushed={:?}",
904 0 : msg.wal_data.len(),
905 : msg.h.end_lsn,
906 : msg.h.commit_lsn,
907 : msg.h.truncate_lsn,
908 : require_flush,
909 : );
910 :
911 : // If flush_lsn hasn't updated, AppendResponse is not very useful.
912 21695 : if !require_flush {
913 21691 : return Ok(None);
914 4 : }
915 4 :
916 4 : let resp = self.append_response();
917 4 : Ok(Some(AcceptorProposerMessage::AppendResponse(resp)))
918 21695 : }
919 :
920 : /// Flush WAL to disk. Return AppendResponse with latest LSNs.
921 17964 : async fn handle_flush(&mut self) -> Result<Option<AcceptorProposerMessage>> {
922 17964 : self.wal_store.flush_wal().await?;
923 17964 : Ok(Some(AcceptorProposerMessage::AppendResponse(
924 17964 : self.append_response(),
925 17964 : )))
926 17964 : }
927 :
928 : /// Update timeline state with peer safekeeper data.
929 0 : pub async fn record_safekeeper_info(&mut self, sk_info: &SafekeeperTimelineInfo) -> Result<()> {
930 0 : let mut sync_control_file = false;
931 0 :
932 0 : if (Lsn(sk_info.commit_lsn) != Lsn::INVALID) && (sk_info.last_log_term != INVALID_TERM) {
933 : // Note: the check is too restrictive, generally we can update local
934 : // commit_lsn if our history matches (is part of) history of advanced
935 : // commit_lsn provider.
936 0 : if sk_info.last_log_term == self.get_epoch() {
937 0 : self.update_commit_lsn(Lsn(sk_info.commit_lsn)).await?;
938 0 : }
939 0 : }
940 :
941 0 : self.state.inmem.backup_lsn = max(Lsn(sk_info.backup_lsn), self.state.inmem.backup_lsn);
942 0 : sync_control_file |= self.state.backup_lsn + (self.state.server.wal_seg_size as u64)
943 0 : < self.state.inmem.backup_lsn;
944 0 :
945 0 : self.state.inmem.remote_consistent_lsn = max(
946 0 : Lsn(sk_info.remote_consistent_lsn),
947 0 : self.state.inmem.remote_consistent_lsn,
948 0 : );
949 0 : sync_control_file |= self.state.remote_consistent_lsn
950 0 : + (self.state.server.wal_seg_size as u64)
951 0 : < self.state.inmem.remote_consistent_lsn;
952 0 :
953 0 : self.state.inmem.peer_horizon_lsn = max(
954 0 : Lsn(sk_info.peer_horizon_lsn),
955 0 : self.state.inmem.peer_horizon_lsn,
956 0 : );
957 0 : sync_control_file |= self.state.peer_horizon_lsn + (self.state.server.wal_seg_size as u64)
958 0 : < self.state.inmem.peer_horizon_lsn;
959 0 :
960 0 : if sync_control_file {
961 0 : self.state.flush().await?;
962 0 : }
963 0 : Ok(())
964 0 : }
965 : }
966 :
967 : #[cfg(test)]
968 : mod tests {
969 : use futures::future::BoxFuture;
970 : use postgres_ffi::{XLogSegNo, WAL_SEGMENT_SIZE};
971 :
972 : use super::*;
973 : use crate::{
974 : state::{PersistedPeers, TimelinePersistentState},
975 : wal_storage::Storage,
976 : };
977 : use std::{ops::Deref, str::FromStr, time::Instant};
978 :
979 : // fake storage for tests
980 : struct InMemoryState {
981 : persisted_state: TimelinePersistentState,
982 : }
983 :
984 : #[async_trait::async_trait]
985 : impl control_file::Storage for InMemoryState {
986 6 : async fn persist(&mut self, s: &TimelinePersistentState) -> Result<()> {
987 6 : self.persisted_state = s.clone();
988 6 : Ok(())
989 6 : }
990 :
991 0 : fn last_persist_at(&self) -> Instant {
992 0 : Instant::now()
993 0 : }
994 : }
995 :
996 : impl Deref for InMemoryState {
997 : type Target = TimelinePersistentState;
998 :
999 120 : fn deref(&self) -> &Self::Target {
1000 120 : &self.persisted_state
1001 120 : }
1002 : }
1003 :
1004 4 : fn test_sk_state() -> TimelinePersistentState {
1005 4 : let mut state = TimelinePersistentState::empty();
1006 4 : state.server.wal_seg_size = WAL_SEGMENT_SIZE as u32;
1007 4 : state.tenant_id = TenantId::from([1u8; 16]);
1008 4 : state.timeline_id = TimelineId::from([1u8; 16]);
1009 4 : state
1010 4 : }
1011 :
1012 : struct DummyWalStore {
1013 : lsn: Lsn,
1014 : }
1015 :
1016 : #[async_trait::async_trait]
1017 : impl wal_storage::Storage for DummyWalStore {
1018 20 : fn flush_lsn(&self) -> Lsn {
1019 20 : self.lsn
1020 20 : }
1021 :
1022 2 : async fn initialize_first_segment(&mut self, _init_lsn: Lsn) -> Result<()> {
1023 2 : Ok(())
1024 2 : }
1025 :
1026 4 : async fn write_wal(&mut self, startpos: Lsn, buf: &[u8]) -> Result<()> {
1027 4 : self.lsn = startpos + buf.len() as u64;
1028 4 : Ok(())
1029 4 : }
1030 :
1031 4 : async fn truncate_wal(&mut self, end_pos: Lsn) -> Result<()> {
1032 4 : self.lsn = end_pos;
1033 4 : Ok(())
1034 4 : }
1035 :
1036 8 : async fn flush_wal(&mut self) -> Result<()> {
1037 8 : Ok(())
1038 8 : }
1039 :
1040 0 : fn remove_up_to(&self, _segno_up_to: XLogSegNo) -> BoxFuture<'static, anyhow::Result<()>> {
1041 0 : Box::pin(async { Ok(()) })
1042 0 : }
1043 :
1044 0 : fn get_metrics(&self) -> crate::metrics::WalStorageMetrics {
1045 0 : crate::metrics::WalStorageMetrics::default()
1046 0 : }
1047 : }
1048 :
1049 : #[tokio::test]
1050 2 : async fn test_voting() {
1051 2 : let storage = InMemoryState {
1052 2 : persisted_state: test_sk_state(),
1053 2 : };
1054 2 : let wal_store = DummyWalStore { lsn: Lsn(0) };
1055 2 : let mut sk = SafeKeeper::new(storage, wal_store, NodeId(0)).unwrap();
1056 2 :
1057 2 : // check voting for 1 is ok
1058 2 : let vote_request = ProposerAcceptorMessage::VoteRequest(VoteRequest { term: 1 });
1059 2 : let mut vote_resp = sk.process_msg(&vote_request).await;
1060 2 : match vote_resp.unwrap() {
1061 2 : Some(AcceptorProposerMessage::VoteResponse(resp)) => assert!(resp.vote_given != 0),
1062 2 : r => panic!("unexpected response: {:?}", r),
1063 2 : }
1064 2 :
1065 2 : // reboot...
1066 2 : let state = sk.state.deref().clone();
1067 2 : let storage = InMemoryState {
1068 2 : persisted_state: state,
1069 2 : };
1070 2 :
1071 2 : sk = SafeKeeper::new(storage, sk.wal_store, NodeId(0)).unwrap();
1072 2 :
1073 2 : // and ensure voting second time for 1 is not ok
1074 2 : vote_resp = sk.process_msg(&vote_request).await;
1075 2 : match vote_resp.unwrap() {
1076 2 : Some(AcceptorProposerMessage::VoteResponse(resp)) => assert!(resp.vote_given == 0),
1077 2 : r => panic!("unexpected response: {:?}", r),
1078 2 : }
1079 2 : }
1080 :
1081 : #[tokio::test]
1082 2 : async fn test_epoch_switch() {
1083 2 : let storage = InMemoryState {
1084 2 : persisted_state: test_sk_state(),
1085 2 : };
1086 2 : let wal_store = DummyWalStore { lsn: Lsn(0) };
1087 2 :
1088 2 : let mut sk = SafeKeeper::new(storage, wal_store, NodeId(0)).unwrap();
1089 2 :
1090 2 : let mut ar_hdr = AppendRequestHeader {
1091 2 : term: 1,
1092 2 : epoch_start_lsn: Lsn(3),
1093 2 : begin_lsn: Lsn(1),
1094 2 : end_lsn: Lsn(2),
1095 2 : commit_lsn: Lsn(0),
1096 2 : truncate_lsn: Lsn(0),
1097 2 : proposer_uuid: [0; 16],
1098 2 : };
1099 2 : let mut append_request = AppendRequest {
1100 2 : h: ar_hdr.clone(),
1101 2 : wal_data: Bytes::from_static(b"b"),
1102 2 : };
1103 2 :
1104 2 : let pem = ProposerElected {
1105 2 : term: 1,
1106 2 : start_streaming_at: Lsn(1),
1107 2 : term_history: TermHistory(vec![TermLsn {
1108 2 : term: 1,
1109 2 : lsn: Lsn(3),
1110 2 : }]),
1111 2 : timeline_start_lsn: Lsn(0),
1112 2 : };
1113 2 : sk.process_msg(&ProposerAcceptorMessage::Elected(pem))
1114 2 : .await
1115 2 : .unwrap();
1116 2 :
1117 2 : // check that AppendRequest before epochStartLsn doesn't switch epoch
1118 2 : let resp = sk
1119 2 : .process_msg(&ProposerAcceptorMessage::AppendRequest(append_request))
1120 2 : .await;
1121 2 : assert!(resp.is_ok());
1122 2 : assert_eq!(sk.get_epoch(), 0);
1123 2 :
1124 2 : // but record at epochStartLsn does the switch
1125 2 : ar_hdr.begin_lsn = Lsn(2);
1126 2 : ar_hdr.end_lsn = Lsn(3);
1127 2 : append_request = AppendRequest {
1128 2 : h: ar_hdr,
1129 2 : wal_data: Bytes::from_static(b"b"),
1130 2 : };
1131 2 : let resp = sk
1132 2 : .process_msg(&ProposerAcceptorMessage::AppendRequest(append_request))
1133 2 : .await;
1134 2 : assert!(resp.is_ok());
1135 2 : sk.wal_store.truncate_wal(Lsn(3)).await.unwrap(); // imitate the complete record at 3 %)
1136 2 : assert_eq!(sk.get_epoch(), 1);
1137 2 : }
1138 :
1139 : #[test]
1140 2 : fn test_find_highest_common_point_none() {
1141 2 : let prop_th = TermHistory(vec![(0, Lsn(1)).into()]);
1142 2 : let sk_th = TermHistory(vec![(1, Lsn(1)).into(), (2, Lsn(2)).into()]);
1143 2 : assert_eq!(
1144 2 : TermHistory::find_highest_common_point(&prop_th, &sk_th, Lsn(3),),
1145 2 : None
1146 2 : );
1147 2 : }
1148 :
1149 : #[test]
1150 2 : fn test_find_highest_common_point_middle() {
1151 2 : let prop_th = TermHistory(vec![
1152 2 : (1, Lsn(10)).into(),
1153 2 : (2, Lsn(20)).into(),
1154 2 : (4, Lsn(40)).into(),
1155 2 : ]);
1156 2 : let sk_th = TermHistory(vec![
1157 2 : (1, Lsn(10)).into(),
1158 2 : (2, Lsn(20)).into(),
1159 2 : (3, Lsn(30)).into(), // sk ends last common term 2 at 30
1160 2 : ]);
1161 2 : assert_eq!(
1162 2 : TermHistory::find_highest_common_point(&prop_th, &sk_th, Lsn(40),),
1163 2 : Some(TermLsn {
1164 2 : term: 2,
1165 2 : lsn: Lsn(30),
1166 2 : })
1167 2 : );
1168 2 : }
1169 :
1170 : #[test]
1171 2 : fn test_find_highest_common_point_sk_end() {
1172 2 : let prop_th = TermHistory(vec![
1173 2 : (1, Lsn(10)).into(),
1174 2 : (2, Lsn(20)).into(), // last common term 2, sk will end it at 32 sk_end_lsn
1175 2 : (4, Lsn(40)).into(),
1176 2 : ]);
1177 2 : let sk_th = TermHistory(vec![(1, Lsn(10)).into(), (2, Lsn(20)).into()]);
1178 2 : assert_eq!(
1179 2 : TermHistory::find_highest_common_point(&prop_th, &sk_th, Lsn(32),),
1180 2 : Some(TermLsn {
1181 2 : term: 2,
1182 2 : lsn: Lsn(32),
1183 2 : })
1184 2 : );
1185 2 : }
1186 :
1187 : #[test]
1188 2 : fn test_find_highest_common_point_walprop() {
1189 2 : let prop_th = TermHistory(vec![(1, Lsn(10)).into(), (2, Lsn(20)).into()]);
1190 2 : let sk_th = TermHistory(vec![(1, Lsn(10)).into(), (2, Lsn(20)).into()]);
1191 2 : assert_eq!(
1192 2 : TermHistory::find_highest_common_point(&prop_th, &sk_th, Lsn(32),),
1193 2 : Some(TermLsn {
1194 2 : term: 2,
1195 2 : lsn: Lsn(32),
1196 2 : })
1197 2 : );
1198 2 : }
1199 :
1200 : #[test]
1201 2 : fn test_sk_state_bincode_serde_roundtrip() {
1202 2 : use utils::Hex;
1203 2 : let tenant_id = TenantId::from_str("cf0480929707ee75372337efaa5ecf96").unwrap();
1204 2 : let timeline_id = TimelineId::from_str("112ded66422aa5e953e5440fa5427ac4").unwrap();
1205 2 : let state = TimelinePersistentState {
1206 2 : tenant_id,
1207 2 : timeline_id,
1208 2 : acceptor_state: AcceptorState {
1209 2 : term: 42,
1210 2 : term_history: TermHistory(vec![TermLsn {
1211 2 : lsn: Lsn(0x1),
1212 2 : term: 41,
1213 2 : }]),
1214 2 : },
1215 2 : server: ServerInfo {
1216 2 : pg_version: 14,
1217 2 : system_id: 0x1234567887654321,
1218 2 : wal_seg_size: 0x12345678,
1219 2 : },
1220 2 : proposer_uuid: {
1221 2 : let mut arr = timeline_id.as_arr();
1222 2 : arr.reverse();
1223 2 : arr
1224 2 : },
1225 2 : timeline_start_lsn: Lsn(0x12345600),
1226 2 : local_start_lsn: Lsn(0x12),
1227 2 : commit_lsn: Lsn(1234567800),
1228 2 : backup_lsn: Lsn(1234567300),
1229 2 : peer_horizon_lsn: Lsn(9999999),
1230 2 : remote_consistent_lsn: Lsn(1234560000),
1231 2 : peers: PersistedPeers(vec![(
1232 2 : NodeId(1),
1233 2 : PersistedPeerInfo {
1234 2 : backup_lsn: Lsn(1234567000),
1235 2 : term: 42,
1236 2 : flush_lsn: Lsn(1234567800 - 8),
1237 2 : commit_lsn: Lsn(1234567600),
1238 2 : },
1239 2 : )]),
1240 2 : partial_backup: crate::wal_backup_partial::State::default(),
1241 2 : };
1242 2 :
1243 2 : let ser = state.ser().unwrap();
1244 2 :
1245 2 : #[rustfmt::skip]
1246 2 : let expected = [
1247 2 : // tenant_id as length prefixed hex
1248 2 : 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1249 2 : 0x63, 0x66, 0x30, 0x34, 0x38, 0x30, 0x39, 0x32, 0x39, 0x37, 0x30, 0x37, 0x65, 0x65, 0x37, 0x35, 0x33, 0x37, 0x32, 0x33, 0x33, 0x37, 0x65, 0x66, 0x61, 0x61, 0x35, 0x65, 0x63, 0x66, 0x39, 0x36,
1250 2 : // timeline_id as length prefixed hex
1251 2 : 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1252 2 : 0x31, 0x31, 0x32, 0x64, 0x65, 0x64, 0x36, 0x36, 0x34, 0x32, 0x32, 0x61, 0x61, 0x35, 0x65, 0x39, 0x35, 0x33, 0x65, 0x35, 0x34, 0x34, 0x30, 0x66, 0x61, 0x35, 0x34, 0x32, 0x37, 0x61, 0x63, 0x34,
1253 2 : // term
1254 2 : 0x2a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1255 2 : // length prefix
1256 2 : 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1257 2 : // unsure why this order is swapped
1258 2 : 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1259 2 : 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1260 2 : // pg_version
1261 2 : 0x0e, 0x00, 0x00, 0x00,
1262 2 : // systemid
1263 2 : 0x21, 0x43, 0x65, 0x87, 0x78, 0x56, 0x34, 0x12,
1264 2 : // wal_seg_size
1265 2 : 0x78, 0x56, 0x34, 0x12,
1266 2 : // pguuid as length prefixed hex
1267 2 : 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1268 2 : 0x63, 0x34, 0x37, 0x61, 0x34, 0x32, 0x61, 0x35, 0x30, 0x66, 0x34, 0x34, 0x65, 0x35, 0x35, 0x33, 0x65, 0x39, 0x61, 0x35, 0x32, 0x61, 0x34, 0x32, 0x36, 0x36, 0x65, 0x64, 0x32, 0x64, 0x31, 0x31,
1269 2 :
1270 2 : // timeline_start_lsn
1271 2 : 0x00, 0x56, 0x34, 0x12, 0x00, 0x00, 0x00, 0x00,
1272 2 : 0x12, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1273 2 : 0x78, 0x02, 0x96, 0x49, 0x00, 0x00, 0x00, 0x00,
1274 2 : 0x84, 0x00, 0x96, 0x49, 0x00, 0x00, 0x00, 0x00,
1275 2 : 0x7f, 0x96, 0x98, 0x00, 0x00, 0x00, 0x00, 0x00,
1276 2 : 0x00, 0xe4, 0x95, 0x49, 0x00, 0x00, 0x00, 0x00,
1277 2 : // length prefix for persistentpeers
1278 2 : 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1279 2 : // nodeid
1280 2 : 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1281 2 : // backuplsn
1282 2 : 0x58, 0xff, 0x95, 0x49, 0x00, 0x00, 0x00, 0x00,
1283 2 : 0x2a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1284 2 : 0x70, 0x02, 0x96, 0x49, 0x00, 0x00, 0x00, 0x00,
1285 2 : 0xb0, 0x01, 0x96, 0x49, 0x00, 0x00, 0x00, 0x00,
1286 2 : // partial_backup
1287 2 : 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1288 2 : ];
1289 2 :
1290 2 : assert_eq!(Hex(&ser), Hex(&expected));
1291 :
1292 2 : let deser = TimelinePersistentState::des(&ser).unwrap();
1293 2 :
1294 2 : assert_eq!(deser, state);
1295 2 : }
1296 : }
|