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