Line data Source code
1 : //! This module implements the streaming side of replication protocol, starting
2 : //! with the "START_REPLICATION" message, and registry of walsenders.
3 :
4 : use crate::handler::SafekeeperPostgresHandler;
5 : use crate::metrics::RECEIVED_PS_FEEDBACKS;
6 : use crate::receive_wal::WalReceivers;
7 : use crate::safekeeper::{Term, TermLsn};
8 : use crate::send_interpreted_wal::InterpretedWalSender;
9 : use crate::timeline::WalResidentTimeline;
10 : use crate::wal_reader_stream::WalReaderStreamBuilder;
11 : use crate::wal_service::ConnectionId;
12 : use crate::wal_storage::WalReader;
13 : use crate::GlobalTimelines;
14 : use anyhow::{bail, Context as AnyhowContext};
15 : use bytes::Bytes;
16 : use futures::future::Either;
17 : use parking_lot::Mutex;
18 : use postgres_backend::PostgresBackend;
19 : use postgres_backend::{CopyStreamHandlerEnd, PostgresBackendReader, QueryError};
20 : use postgres_ffi::get_current_timestamp;
21 : use postgres_ffi::{TimestampTz, MAX_SEND_SIZE};
22 : use pq_proto::{BeMessage, WalSndKeepAlive, XLogDataBody};
23 : use serde::{Deserialize, Serialize};
24 : use tokio::io::{AsyncRead, AsyncWrite};
25 : use utils::failpoint_support;
26 : use utils::id::TenantTimelineId;
27 : use utils::pageserver_feedback::PageserverFeedback;
28 : use utils::postgres_client::PostgresClientProtocol;
29 :
30 : use std::cmp::{max, min};
31 : use std::net::SocketAddr;
32 : use std::str;
33 : use std::sync::Arc;
34 : use std::time::Duration;
35 : use tokio::sync::watch::Receiver;
36 : use tokio::time::timeout;
37 : use tracing::*;
38 : use utils::{bin_ser::BeSer, lsn::Lsn};
39 :
40 : // See: https://www.postgresql.org/docs/13/protocol-replication.html
41 : const HOT_STANDBY_FEEDBACK_TAG_BYTE: u8 = b'h';
42 : const STANDBY_STATUS_UPDATE_TAG_BYTE: u8 = b'r';
43 : // neon extension of replication protocol
44 : const NEON_STATUS_UPDATE_TAG_BYTE: u8 = b'z';
45 :
46 : type FullTransactionId = u64;
47 :
48 : /// Hot standby feedback received from replica
49 0 : #[derive(Debug, Clone, Copy, Serialize, Deserialize)]
50 : pub struct HotStandbyFeedback {
51 : pub ts: TimestampTz,
52 : pub xmin: FullTransactionId,
53 : pub catalog_xmin: FullTransactionId,
54 : }
55 :
56 : const INVALID_FULL_TRANSACTION_ID: FullTransactionId = 0;
57 :
58 : impl HotStandbyFeedback {
59 3062 : pub fn empty() -> HotStandbyFeedback {
60 3062 : HotStandbyFeedback {
61 3062 : ts: 0,
62 3062 : xmin: 0,
63 3062 : catalog_xmin: 0,
64 3062 : }
65 3062 : }
66 : }
67 :
68 : /// Standby status update
69 0 : #[derive(Debug, Clone, Copy, Serialize, Deserialize)]
70 : pub struct StandbyReply {
71 : pub write_lsn: Lsn, // The location of the last WAL byte + 1 received and written to disk in the standby.
72 : pub flush_lsn: Lsn, // The location of the last WAL byte + 1 flushed to disk in the standby.
73 : pub apply_lsn: Lsn, // The location of the last WAL byte + 1 applied in the standby.
74 : pub reply_ts: TimestampTz, // The client's system clock at the time of transmission, as microseconds since midnight on 2000-01-01.
75 : pub reply_requested: bool,
76 : }
77 :
78 : impl StandbyReply {
79 8 : fn empty() -> Self {
80 8 : StandbyReply {
81 8 : write_lsn: Lsn::INVALID,
82 8 : flush_lsn: Lsn::INVALID,
83 8 : apply_lsn: Lsn::INVALID,
84 8 : reply_ts: 0,
85 8 : reply_requested: false,
86 8 : }
87 8 : }
88 : }
89 :
90 0 : #[derive(Debug, Clone, Copy, Serialize, Deserialize)]
91 : pub struct StandbyFeedback {
92 : pub reply: StandbyReply,
93 : pub hs_feedback: HotStandbyFeedback,
94 : }
95 :
96 : impl StandbyFeedback {
97 2 : pub fn empty() -> Self {
98 2 : StandbyFeedback {
99 2 : reply: StandbyReply::empty(),
100 2 : hs_feedback: HotStandbyFeedback::empty(),
101 2 : }
102 2 : }
103 : }
104 :
105 : /// WalSenders registry. Timeline holds it (wrapped in Arc).
106 : pub struct WalSenders {
107 : mutex: Mutex<WalSendersShared>,
108 : walreceivers: Arc<WalReceivers>,
109 : }
110 :
111 : impl WalSenders {
112 0 : pub fn new(walreceivers: Arc<WalReceivers>) -> Arc<WalSenders> {
113 0 : Arc::new(WalSenders {
114 0 : mutex: Mutex::new(WalSendersShared::new()),
115 0 : walreceivers,
116 0 : })
117 0 : }
118 :
119 : /// Register new walsender. Returned guard provides access to the slot and
120 : /// automatically deregisters in Drop.
121 0 : fn register(
122 0 : self: &Arc<WalSenders>,
123 0 : ttid: TenantTimelineId,
124 0 : addr: SocketAddr,
125 0 : conn_id: ConnectionId,
126 0 : appname: Option<String>,
127 0 : ) -> WalSenderGuard {
128 0 : let slots = &mut self.mutex.lock().slots;
129 0 : let walsender_state = WalSenderState {
130 0 : ttid,
131 0 : addr,
132 0 : conn_id,
133 0 : appname,
134 0 : feedback: ReplicationFeedback::Pageserver(PageserverFeedback::empty()),
135 0 : };
136 : // find empty slot or create new one
137 0 : let pos = if let Some(pos) = slots.iter().position(|s| s.is_none()) {
138 0 : slots[pos] = Some(walsender_state);
139 0 : pos
140 : } else {
141 0 : let pos = slots.len();
142 0 : slots.push(Some(walsender_state));
143 0 : pos
144 : };
145 0 : WalSenderGuard {
146 0 : id: pos,
147 0 : walsenders: self.clone(),
148 0 : }
149 0 : }
150 :
151 : /// Get state of all walsenders.
152 0 : pub fn get_all(self: &Arc<WalSenders>) -> Vec<WalSenderState> {
153 0 : self.mutex.lock().slots.iter().flatten().cloned().collect()
154 0 : }
155 :
156 : /// Get LSN of the most lagging pageserver receiver. Return None if there are no
157 : /// active walsenders.
158 0 : pub fn laggard_lsn(self: &Arc<WalSenders>) -> Option<Lsn> {
159 0 : self.mutex
160 0 : .lock()
161 0 : .slots
162 0 : .iter()
163 0 : .flatten()
164 0 : .filter_map(|s| match s.feedback {
165 0 : ReplicationFeedback::Pageserver(feedback) => Some(feedback.last_received_lsn),
166 0 : ReplicationFeedback::Standby(_) => None,
167 0 : })
168 0 : .min()
169 0 : }
170 :
171 : /// Returns total counter of pageserver feedbacks received and last feedback.
172 0 : pub fn get_ps_feedback_stats(self: &Arc<WalSenders>) -> (u64, PageserverFeedback) {
173 0 : let shared = self.mutex.lock();
174 0 : (shared.ps_feedback_counter, shared.last_ps_feedback)
175 0 : }
176 :
177 : /// Get aggregated hot standby feedback (we send it to compute).
178 0 : pub fn get_hotstandby(self: &Arc<WalSenders>) -> StandbyFeedback {
179 0 : self.mutex.lock().agg_standby_feedback
180 0 : }
181 :
182 : /// Record new pageserver feedback, update aggregated values.
183 0 : fn record_ps_feedback(self: &Arc<WalSenders>, id: WalSenderId, feedback: &PageserverFeedback) {
184 0 : let mut shared = self.mutex.lock();
185 0 : shared.get_slot_mut(id).feedback = ReplicationFeedback::Pageserver(*feedback);
186 0 : shared.last_ps_feedback = *feedback;
187 0 : shared.ps_feedback_counter += 1;
188 0 : drop(shared);
189 0 :
190 0 : RECEIVED_PS_FEEDBACKS.inc();
191 0 :
192 0 : // send feedback to connected walproposers
193 0 : self.walreceivers.broadcast_pageserver_feedback(*feedback);
194 0 : }
195 :
196 : /// Record standby reply.
197 0 : fn record_standby_reply(self: &Arc<WalSenders>, id: WalSenderId, reply: &StandbyReply) {
198 0 : let mut shared = self.mutex.lock();
199 0 : let slot = shared.get_slot_mut(id);
200 0 : debug!(
201 0 : "Record standby reply: ts={} apply_lsn={}",
202 : reply.reply_ts, reply.apply_lsn
203 : );
204 0 : match &mut slot.feedback {
205 0 : ReplicationFeedback::Standby(sf) => sf.reply = *reply,
206 : ReplicationFeedback::Pageserver(_) => {
207 0 : slot.feedback = ReplicationFeedback::Standby(StandbyFeedback {
208 0 : reply: *reply,
209 0 : hs_feedback: HotStandbyFeedback::empty(),
210 0 : })
211 : }
212 : }
213 0 : }
214 :
215 : /// Record hot standby feedback, update aggregated value.
216 0 : fn record_hs_feedback(self: &Arc<WalSenders>, id: WalSenderId, feedback: &HotStandbyFeedback) {
217 0 : let mut shared = self.mutex.lock();
218 0 : let slot = shared.get_slot_mut(id);
219 0 : match &mut slot.feedback {
220 0 : ReplicationFeedback::Standby(sf) => sf.hs_feedback = *feedback,
221 : ReplicationFeedback::Pageserver(_) => {
222 0 : slot.feedback = ReplicationFeedback::Standby(StandbyFeedback {
223 0 : reply: StandbyReply::empty(),
224 0 : hs_feedback: *feedback,
225 0 : })
226 : }
227 : }
228 0 : shared.update_reply_feedback();
229 0 : }
230 :
231 : /// Get remote_consistent_lsn reported by the pageserver. Returns None if
232 : /// client is not pageserver.
233 0 : pub fn get_ws_remote_consistent_lsn(self: &Arc<WalSenders>, id: WalSenderId) -> Option<Lsn> {
234 0 : let shared = self.mutex.lock();
235 0 : let slot = shared.get_slot(id);
236 0 : match slot.feedback {
237 0 : ReplicationFeedback::Pageserver(feedback) => Some(feedback.remote_consistent_lsn),
238 0 : _ => None,
239 : }
240 0 : }
241 :
242 : /// Unregister walsender.
243 0 : fn unregister(self: &Arc<WalSenders>, id: WalSenderId) {
244 0 : let mut shared = self.mutex.lock();
245 0 : shared.slots[id] = None;
246 0 : shared.update_reply_feedback();
247 0 : }
248 : }
249 :
250 : struct WalSendersShared {
251 : // aggregated over all walsenders value
252 : agg_standby_feedback: StandbyFeedback,
253 : // last feedback ever received from any pageserver, empty if none
254 : last_ps_feedback: PageserverFeedback,
255 : // total counter of pageserver feedbacks received
256 : ps_feedback_counter: u64,
257 : slots: Vec<Option<WalSenderState>>,
258 : }
259 :
260 : impl WalSendersShared {
261 2 : fn new() -> Self {
262 2 : WalSendersShared {
263 2 : agg_standby_feedback: StandbyFeedback::empty(),
264 2 : last_ps_feedback: PageserverFeedback::empty(),
265 2 : ps_feedback_counter: 0,
266 2 : slots: Vec::new(),
267 2 : }
268 2 : }
269 :
270 : /// Get content of provided id slot, it must exist.
271 0 : fn get_slot(&self, id: WalSenderId) -> &WalSenderState {
272 0 : self.slots[id].as_ref().expect("walsender doesn't exist")
273 0 : }
274 :
275 : /// Get mut content of provided id slot, it must exist.
276 0 : fn get_slot_mut(&mut self, id: WalSenderId) -> &mut WalSenderState {
277 0 : self.slots[id].as_mut().expect("walsender doesn't exist")
278 0 : }
279 :
280 : /// Update aggregated hot standy and normal reply feedbacks. We just take min of valid xmins
281 : /// and ts.
282 2 : fn update_reply_feedback(&mut self) {
283 2 : let mut agg = HotStandbyFeedback::empty();
284 2 : let mut reply_agg = StandbyReply::empty();
285 4 : for ws_state in self.slots.iter().flatten() {
286 4 : if let ReplicationFeedback::Standby(standby_feedback) = ws_state.feedback {
287 4 : let hs_feedback = standby_feedback.hs_feedback;
288 4 : // doing Option math like op1.iter().chain(op2.iter()).min()
289 4 : // would be nicer, but we serialize/deserialize this struct
290 4 : // directly, so leave as is for now
291 4 : if hs_feedback.xmin != INVALID_FULL_TRANSACTION_ID {
292 2 : if agg.xmin != INVALID_FULL_TRANSACTION_ID {
293 1 : agg.xmin = min(agg.xmin, hs_feedback.xmin);
294 1 : } else {
295 1 : agg.xmin = hs_feedback.xmin;
296 1 : }
297 2 : agg.ts = max(agg.ts, hs_feedback.ts);
298 2 : }
299 4 : if hs_feedback.catalog_xmin != INVALID_FULL_TRANSACTION_ID {
300 0 : if agg.catalog_xmin != INVALID_FULL_TRANSACTION_ID {
301 0 : agg.catalog_xmin = min(agg.catalog_xmin, hs_feedback.catalog_xmin);
302 0 : } else {
303 0 : agg.catalog_xmin = hs_feedback.catalog_xmin;
304 0 : }
305 0 : agg.ts = max(agg.ts, hs_feedback.ts);
306 4 : }
307 4 : let reply = standby_feedback.reply;
308 4 : if reply.write_lsn != Lsn::INVALID {
309 0 : if reply_agg.write_lsn != Lsn::INVALID {
310 0 : reply_agg.write_lsn = Lsn::min(reply_agg.write_lsn, reply.write_lsn);
311 0 : } else {
312 0 : reply_agg.write_lsn = reply.write_lsn;
313 0 : }
314 4 : }
315 4 : if reply.flush_lsn != Lsn::INVALID {
316 0 : if reply_agg.flush_lsn != Lsn::INVALID {
317 0 : reply_agg.flush_lsn = Lsn::min(reply_agg.flush_lsn, reply.flush_lsn);
318 0 : } else {
319 0 : reply_agg.flush_lsn = reply.flush_lsn;
320 0 : }
321 4 : }
322 4 : if reply.apply_lsn != Lsn::INVALID {
323 0 : if reply_agg.apply_lsn != Lsn::INVALID {
324 0 : reply_agg.apply_lsn = Lsn::min(reply_agg.apply_lsn, reply.apply_lsn);
325 0 : } else {
326 0 : reply_agg.apply_lsn = reply.apply_lsn;
327 0 : }
328 4 : }
329 4 : if reply.reply_ts != 0 {
330 0 : if reply_agg.reply_ts != 0 {
331 0 : reply_agg.reply_ts = TimestampTz::min(reply_agg.reply_ts, reply.reply_ts);
332 0 : } else {
333 0 : reply_agg.reply_ts = reply.reply_ts;
334 0 : }
335 4 : }
336 0 : }
337 : }
338 2 : self.agg_standby_feedback = StandbyFeedback {
339 2 : reply: reply_agg,
340 2 : hs_feedback: agg,
341 2 : };
342 2 : }
343 : }
344 :
345 : // Serialized is used only for pretty printing in json.
346 0 : #[derive(Debug, Clone, Serialize, Deserialize)]
347 : pub struct WalSenderState {
348 : ttid: TenantTimelineId,
349 : addr: SocketAddr,
350 : conn_id: ConnectionId,
351 : // postgres application_name
352 : appname: Option<String>,
353 : feedback: ReplicationFeedback,
354 : }
355 :
356 : // Receiver is either pageserver or regular standby, which have different
357 : // feedbacks.
358 0 : #[derive(Debug, Clone, Copy, Serialize, Deserialize)]
359 : enum ReplicationFeedback {
360 : Pageserver(PageserverFeedback),
361 : Standby(StandbyFeedback),
362 : }
363 :
364 : // id of the occupied slot in WalSenders to access it (and save in the
365 : // WalSenderGuard). We could give Arc directly to the slot, but there is not
366 : // much sense in that as values aggregation which is performed on each feedback
367 : // receival iterates over all walsenders.
368 : pub type WalSenderId = usize;
369 :
370 : /// Scope guard to access slot in WalSenders registry and unregister from it in
371 : /// Drop.
372 : pub struct WalSenderGuard {
373 : id: WalSenderId,
374 : walsenders: Arc<WalSenders>,
375 : }
376 :
377 : impl WalSenderGuard {
378 0 : pub fn id(&self) -> WalSenderId {
379 0 : self.id
380 0 : }
381 :
382 0 : pub fn walsenders(&self) -> &Arc<WalSenders> {
383 0 : &self.walsenders
384 0 : }
385 : }
386 :
387 : impl Drop for WalSenderGuard {
388 0 : fn drop(&mut self) {
389 0 : self.walsenders.unregister(self.id);
390 0 : }
391 : }
392 :
393 : impl SafekeeperPostgresHandler {
394 : /// Wrapper around handle_start_replication_guts handling result. Error is
395 : /// handled here while we're still in walsender ttid span; with API
396 : /// extension, this can probably be moved into postgres_backend.
397 0 : pub async fn handle_start_replication<IO: AsyncRead + AsyncWrite + Unpin>(
398 0 : &mut self,
399 0 : pgb: &mut PostgresBackend<IO>,
400 0 : start_pos: Lsn,
401 0 : term: Option<Term>,
402 0 : ) -> Result<(), QueryError> {
403 0 : let tli = GlobalTimelines::get(self.ttid).map_err(|e| QueryError::Other(e.into()))?;
404 0 : let residence_guard = tli.wal_residence_guard().await?;
405 :
406 0 : if let Err(end) = self
407 0 : .handle_start_replication_guts(pgb, start_pos, term, residence_guard)
408 0 : .await
409 : {
410 0 : let info = tli.get_safekeeper_info(&self.conf).await;
411 : // Log the result and probably send it to the client, closing the stream.
412 0 : pgb.handle_copy_stream_end(end)
413 0 : .instrument(info_span!("", term=%info.term, last_log_term=%info.last_log_term, flush_lsn=%Lsn(info.flush_lsn), commit_lsn=%Lsn(info.flush_lsn)))
414 0 : .await;
415 0 : }
416 0 : Ok(())
417 0 : }
418 :
419 0 : pub async fn handle_start_replication_guts<IO: AsyncRead + AsyncWrite + Unpin>(
420 0 : &mut self,
421 0 : pgb: &mut PostgresBackend<IO>,
422 0 : start_pos: Lsn,
423 0 : term: Option<Term>,
424 0 : tli: WalResidentTimeline,
425 0 : ) -> Result<(), CopyStreamHandlerEnd> {
426 0 : let appname = self.appname.clone();
427 0 :
428 0 : // Use a guard object to remove our entry from the timeline when we are done.
429 0 : let ws_guard = Arc::new(tli.get_walsenders().register(
430 0 : self.ttid,
431 0 : *pgb.get_peer_addr(),
432 0 : self.conn_id,
433 0 : self.appname.clone(),
434 0 : ));
435 :
436 : // Walsender can operate in one of two modes which we select by
437 : // application_name: give only committed WAL (used by pageserver) or all
438 : // existing WAL (up to flush_lsn, used by walproposer or peer recovery).
439 : // The second case is always driven by a consensus leader which term
440 : // must be supplied.
441 0 : let end_watch = if term.is_some() {
442 0 : EndWatch::Flush(tli.get_term_flush_lsn_watch_rx())
443 : } else {
444 0 : EndWatch::Commit(tli.get_commit_lsn_watch_rx())
445 : };
446 : // we don't check term here; it will be checked on first waiting/WAL reading anyway.
447 0 : let end_pos = end_watch.get();
448 0 :
449 0 : if end_pos < start_pos {
450 0 : warn!(
451 0 : "requested start_pos {} is ahead of available WAL end_pos {}",
452 : start_pos, end_pos
453 : );
454 0 : }
455 :
456 0 : info!(
457 0 : "starting streaming from {:?}, available WAL ends at {}, recovery={}, appname={:?}, protocol={}",
458 : start_pos,
459 : end_pos,
460 0 : matches!(end_watch, EndWatch::Flush(_)),
461 : appname,
462 0 : self.protocol(),
463 : );
464 :
465 : // switch to copy
466 0 : pgb.write_message(&BeMessage::CopyBothResponse).await?;
467 :
468 0 : let wal_reader = tli.get_walreader(start_pos).await?;
469 :
470 : // Split to concurrently receive and send data; replies are generally
471 : // not synchronized with sends, so this avoids deadlocks.
472 0 : let reader = pgb.split().context("START_REPLICATION split")?;
473 :
474 0 : let send_fut = match self.protocol() {
475 : PostgresClientProtocol::Vanilla => {
476 0 : let sender = WalSender {
477 0 : pgb,
478 0 : // should succeed since we're already holding another guard
479 0 : tli: tli.wal_residence_guard().await?,
480 0 : appname,
481 0 : start_pos,
482 0 : end_pos,
483 0 : term,
484 0 : end_watch,
485 0 : ws_guard: ws_guard.clone(),
486 0 : wal_reader,
487 0 : send_buf: vec![0u8; MAX_SEND_SIZE],
488 0 : };
489 0 :
490 0 : Either::Left(sender.run())
491 : }
492 : PostgresClientProtocol::Interpreted => {
493 0 : let pg_version = tli.tli.get_state().await.1.server.pg_version / 10000;
494 0 : let end_watch_view = end_watch.view();
495 0 : let wal_stream_builder = WalReaderStreamBuilder {
496 0 : tli: tli.wal_residence_guard().await?,
497 0 : start_pos,
498 0 : end_pos,
499 0 : term,
500 0 : end_watch,
501 0 : wal_sender_guard: ws_guard.clone(),
502 0 : };
503 0 :
504 0 : let sender = InterpretedWalSender {
505 0 : pgb,
506 0 : wal_stream_builder,
507 0 : end_watch_view,
508 0 : shard: self.shard.unwrap(),
509 0 : pg_version,
510 0 : appname,
511 0 : };
512 0 :
513 0 : Either::Right(sender.run())
514 : }
515 : };
516 :
517 0 : let tli_cancel = tli.cancel.clone();
518 0 :
519 0 : let mut reply_reader = ReplyReader {
520 0 : reader,
521 0 : ws_guard: ws_guard.clone(),
522 0 : tli,
523 0 : };
524 :
525 0 : let res = tokio::select! {
526 : // todo: add read|write .context to these errors
527 0 : r = send_fut => r,
528 0 : r = reply_reader.run() => r,
529 0 : _ = tli_cancel.cancelled() => {
530 0 : return Err(CopyStreamHandlerEnd::Cancelled);
531 : }
532 : };
533 :
534 0 : let ws_state = ws_guard
535 0 : .walsenders
536 0 : .mutex
537 0 : .lock()
538 0 : .get_slot(ws_guard.id)
539 0 : .clone();
540 0 : info!(
541 0 : "finished streaming to {}, feedback={:?}",
542 : ws_state.addr, ws_state.feedback,
543 : );
544 :
545 : // Join pg backend back.
546 0 : pgb.unsplit(reply_reader.reader)?;
547 :
548 0 : res
549 0 : }
550 : }
551 :
552 : /// TODO(vlad): maybe lift this instead
553 : /// Walsender streams either up to commit_lsn (normally) or flush_lsn in the
554 : /// given term (recovery by walproposer or peer safekeeper).
555 : #[derive(Clone)]
556 : pub(crate) enum EndWatch {
557 : Commit(Receiver<Lsn>),
558 : Flush(Receiver<TermLsn>),
559 : }
560 :
561 : impl EndWatch {
562 0 : pub(crate) fn view(&self) -> EndWatchView {
563 0 : EndWatchView(self.clone())
564 0 : }
565 :
566 : /// Get current end of WAL.
567 0 : pub(crate) fn get(&self) -> Lsn {
568 0 : match self {
569 0 : EndWatch::Commit(r) => *r.borrow(),
570 0 : EndWatch::Flush(r) => r.borrow().lsn,
571 : }
572 0 : }
573 :
574 : /// Wait for the update.
575 0 : pub(crate) async fn changed(&mut self) -> anyhow::Result<()> {
576 0 : match self {
577 0 : EndWatch::Commit(r) => r.changed().await?,
578 0 : EndWatch::Flush(r) => r.changed().await?,
579 : }
580 0 : Ok(())
581 0 : }
582 :
583 0 : pub(crate) async fn wait_for_lsn(
584 0 : &mut self,
585 0 : lsn: Lsn,
586 0 : client_term: Option<Term>,
587 0 : ) -> anyhow::Result<Lsn> {
588 : loop {
589 0 : let end_pos = self.get();
590 0 : if end_pos > lsn {
591 0 : return Ok(end_pos);
592 0 : }
593 0 : if let EndWatch::Flush(rx) = &self {
594 0 : let curr_term = rx.borrow().term;
595 0 : if let Some(client_term) = client_term {
596 0 : if curr_term != client_term {
597 0 : bail!("term changed: requested {}, now {}", client_term, curr_term);
598 0 : }
599 0 : }
600 0 : }
601 0 : self.changed().await?;
602 : }
603 0 : }
604 : }
605 :
606 : pub(crate) struct EndWatchView(EndWatch);
607 :
608 : impl EndWatchView {
609 0 : pub(crate) fn get(&self) -> Lsn {
610 0 : self.0.get()
611 0 : }
612 : }
613 : /// A half driving sending WAL.
614 : struct WalSender<'a, IO> {
615 : pgb: &'a mut PostgresBackend<IO>,
616 : tli: WalResidentTimeline,
617 : appname: Option<String>,
618 : // Position since which we are sending next chunk.
619 : start_pos: Lsn,
620 : // WAL up to this position is known to be locally available.
621 : // Usually this is the same as the latest commit_lsn, but in case of
622 : // walproposer recovery, this is flush_lsn.
623 : //
624 : // We send this LSN to the receiver as wal_end, so that it knows how much
625 : // WAL this safekeeper has. This LSN should be as fresh as possible.
626 : end_pos: Lsn,
627 : /// When streaming uncommitted part, the term the client acts as the leader
628 : /// in. Streaming is stopped if local term changes to a different (higher)
629 : /// value.
630 : term: Option<Term>,
631 : /// Watch channel receiver to learn end of available WAL (and wait for its advancement).
632 : end_watch: EndWatch,
633 : ws_guard: Arc<WalSenderGuard>,
634 : wal_reader: WalReader,
635 : // buffer for readling WAL into to send it
636 : send_buf: Vec<u8>,
637 : }
638 :
639 : const POLL_STATE_TIMEOUT: Duration = Duration::from_secs(1);
640 :
641 : impl<IO: AsyncRead + AsyncWrite + Unpin> WalSender<'_, IO> {
642 : /// Send WAL until
643 : /// - an error occurs
644 : /// - receiver is caughtup and there is no computes (if streaming up to commit_lsn)
645 : /// - timeline's cancellation token fires
646 : ///
647 : /// Err(CopyStreamHandlerEnd) is always returned; Result is used only for ?
648 : /// convenience.
649 0 : async fn run(mut self) -> Result<(), CopyStreamHandlerEnd> {
650 : loop {
651 : // Wait for the next portion if it is not there yet, or just
652 : // update our end of WAL available for sending value, we
653 : // communicate it to the receiver.
654 0 : self.wait_wal().await?;
655 0 : assert!(
656 0 : self.end_pos > self.start_pos,
657 0 : "nothing to send after waiting for WAL"
658 : );
659 :
660 : // try to send as much as available, capped by MAX_SEND_SIZE
661 0 : let mut chunk_end_pos = self.start_pos + MAX_SEND_SIZE as u64;
662 0 : // if we went behind available WAL, back off
663 0 : if chunk_end_pos >= self.end_pos {
664 0 : chunk_end_pos = self.end_pos;
665 0 : } else {
666 0 : // If sending not up to end pos, round down to page boundary to
667 0 : // avoid breaking WAL record not at page boundary, as protocol
668 0 : // demands. See walsender.c (XLogSendPhysical).
669 0 : chunk_end_pos = chunk_end_pos
670 0 : .checked_sub(chunk_end_pos.block_offset())
671 0 : .unwrap();
672 0 : }
673 0 : let send_size = (chunk_end_pos.0 - self.start_pos.0) as usize;
674 0 : let send_buf = &mut self.send_buf[..send_size];
675 : let send_size: usize;
676 : {
677 : // If uncommitted part is being pulled, check that the term is
678 : // still the expected one.
679 0 : let _term_guard = if let Some(t) = self.term {
680 0 : Some(self.tli.acquire_term(t).await?)
681 : } else {
682 0 : None
683 : };
684 : // Read WAL into buffer. send_size can be additionally capped to
685 : // segment boundary here.
686 0 : send_size = self.wal_reader.read(send_buf).await?
687 : };
688 0 : let send_buf = &send_buf[..send_size];
689 0 :
690 0 : // and send it, while respecting Timeline::cancel
691 0 : let msg = BeMessage::XLogData(XLogDataBody {
692 0 : wal_start: self.start_pos.0,
693 0 : wal_end: self.end_pos.0,
694 0 : timestamp: get_current_timestamp(),
695 0 : data: send_buf,
696 0 : });
697 0 : self.pgb.write_message(&msg).await?;
698 :
699 0 : if let Some(appname) = &self.appname {
700 0 : if appname == "replica" {
701 0 : failpoint_support::sleep_millis_async!("sk-send-wal-replica-sleep");
702 0 : }
703 0 : }
704 0 : trace!(
705 0 : "sent {} bytes of WAL {}-{}",
706 0 : send_size,
707 0 : self.start_pos,
708 0 : self.start_pos + send_size as u64
709 : );
710 0 : self.start_pos += send_size as u64;
711 : }
712 0 : }
713 :
714 : /// wait until we have WAL to stream, sending keepalives and checking for
715 : /// exit in the meanwhile
716 0 : async fn wait_wal(&mut self) -> Result<(), CopyStreamHandlerEnd> {
717 : loop {
718 0 : self.end_pos = self.end_watch.get();
719 0 : let have_something_to_send = (|| {
720 0 : fail::fail_point!(
721 0 : "sk-pause-send",
722 0 : self.appname.as_deref() != Some("pageserver"),
723 0 : |_| { false }
724 0 : );
725 0 : self.end_pos > self.start_pos
726 0 : })();
727 0 :
728 0 : if have_something_to_send {
729 0 : trace!("got end_pos {:?}, streaming", self.end_pos);
730 0 : return Ok(());
731 0 : }
732 :
733 : // Wait for WAL to appear, now self.end_pos == self.start_pos.
734 0 : if let Some(lsn) = self.wait_for_lsn().await? {
735 0 : self.end_pos = lsn;
736 0 : trace!("got end_pos {:?}, streaming", self.end_pos);
737 0 : return Ok(());
738 0 : }
739 0 :
740 0 : // Timed out waiting for WAL, check for termination and send KA.
741 0 : // Check for termination only if we are streaming up to commit_lsn
742 0 : // (to pageserver).
743 0 : if let EndWatch::Commit(_) = self.end_watch {
744 0 : if let Some(remote_consistent_lsn) = self
745 0 : .ws_guard
746 0 : .walsenders
747 0 : .get_ws_remote_consistent_lsn(self.ws_guard.id)
748 : {
749 0 : if self.tli.should_walsender_stop(remote_consistent_lsn).await {
750 : // Terminate if there is nothing more to send.
751 : // Note that "ending streaming" part of the string is used by
752 : // pageserver to identify WalReceiverError::SuccessfulCompletion,
753 : // do not change this string without updating pageserver.
754 0 : return Err(CopyStreamHandlerEnd::ServerInitiated(format!(
755 0 : "ending streaming to {:?} at {}, receiver is caughtup and there is no computes",
756 0 : self.appname, self.start_pos,
757 0 : )));
758 0 : }
759 0 : }
760 0 : }
761 :
762 0 : let msg = BeMessage::KeepAlive(WalSndKeepAlive {
763 0 : wal_end: self.end_pos.0,
764 0 : timestamp: get_current_timestamp(),
765 0 : request_reply: true,
766 0 : });
767 0 :
768 0 : self.pgb.write_message(&msg).await?;
769 : }
770 0 : }
771 :
772 : /// Wait until we have available WAL > start_pos or timeout expires. Returns
773 : /// - Ok(Some(end_pos)) if needed lsn is successfully observed;
774 : /// - Ok(None) if timeout expired;
775 : /// - Err in case of error -- only if 1) term changed while fetching in recovery
776 : /// mode 2) watch channel closed, which must never happen.
777 0 : async fn wait_for_lsn(&mut self) -> anyhow::Result<Option<Lsn>> {
778 0 : let fp = (|| {
779 0 : fail::fail_point!(
780 0 : "sk-pause-send",
781 0 : self.appname.as_deref() != Some("pageserver"),
782 0 : |_| { true }
783 0 : );
784 0 : false
785 0 : })();
786 0 : if fp {
787 0 : tokio::time::sleep(POLL_STATE_TIMEOUT).await;
788 0 : return Ok(None);
789 0 : }
790 :
791 0 : let res = timeout(POLL_STATE_TIMEOUT, async move {
792 : loop {
793 0 : let end_pos = self.end_watch.get();
794 0 : if end_pos > self.start_pos {
795 0 : return Ok(end_pos);
796 0 : }
797 0 : if let EndWatch::Flush(rx) = &self.end_watch {
798 0 : let curr_term = rx.borrow().term;
799 0 : if let Some(client_term) = self.term {
800 0 : if curr_term != client_term {
801 0 : bail!("term changed: requested {}, now {}", client_term, curr_term);
802 0 : }
803 0 : }
804 0 : }
805 0 : self.end_watch.changed().await?;
806 : }
807 0 : })
808 0 : .await;
809 :
810 0 : match res {
811 : // success
812 0 : Ok(Ok(commit_lsn)) => Ok(Some(commit_lsn)),
813 : // error inside closure
814 0 : Ok(Err(err)) => Err(err),
815 : // timeout
816 0 : Err(_) => Ok(None),
817 : }
818 0 : }
819 : }
820 :
821 : /// A half driving receiving replies.
822 : struct ReplyReader<IO> {
823 : reader: PostgresBackendReader<IO>,
824 : ws_guard: Arc<WalSenderGuard>,
825 : tli: WalResidentTimeline,
826 : }
827 :
828 : impl<IO: AsyncRead + AsyncWrite + Unpin> ReplyReader<IO> {
829 0 : async fn run(&mut self) -> Result<(), CopyStreamHandlerEnd> {
830 : loop {
831 0 : let msg = self.reader.read_copy_message().await?;
832 0 : self.handle_feedback(&msg).await?
833 : }
834 0 : }
835 :
836 0 : async fn handle_feedback(&mut self, msg: &Bytes) -> anyhow::Result<()> {
837 0 : match msg.first().cloned() {
838 : Some(HOT_STANDBY_FEEDBACK_TAG_BYTE) => {
839 : // Note: deserializing is on m[1..] because we skip the tag byte.
840 0 : let mut hs_feedback = HotStandbyFeedback::des(&msg[1..])
841 0 : .context("failed to deserialize HotStandbyFeedback")?;
842 : // TODO: xmin/catalog_xmin are serialized by walreceiver.c in this way:
843 : // pq_sendint32(&reply_message, xmin);
844 : // pq_sendint32(&reply_message, xmin_epoch);
845 : // So it is two big endian 32-bit words in low endian order!
846 0 : hs_feedback.xmin = hs_feedback.xmin.rotate_left(32);
847 0 : hs_feedback.catalog_xmin = hs_feedback.catalog_xmin.rotate_left(32);
848 0 : self.ws_guard
849 0 : .walsenders
850 0 : .record_hs_feedback(self.ws_guard.id, &hs_feedback);
851 : }
852 : Some(STANDBY_STATUS_UPDATE_TAG_BYTE) => {
853 0 : let reply =
854 0 : StandbyReply::des(&msg[1..]).context("failed to deserialize StandbyReply")?;
855 0 : self.ws_guard
856 0 : .walsenders
857 0 : .record_standby_reply(self.ws_guard.id, &reply);
858 : }
859 : Some(NEON_STATUS_UPDATE_TAG_BYTE) => {
860 : // pageserver sends this.
861 : // Note: deserializing is on m[9..] because we skip the tag byte and len bytes.
862 0 : let buf = Bytes::copy_from_slice(&msg[9..]);
863 0 : let ps_feedback = PageserverFeedback::parse(buf);
864 0 :
865 0 : trace!("PageserverFeedback is {:?}", ps_feedback);
866 0 : self.ws_guard
867 0 : .walsenders
868 0 : .record_ps_feedback(self.ws_guard.id, &ps_feedback);
869 0 : self.tli
870 0 : .update_remote_consistent_lsn(ps_feedback.remote_consistent_lsn)
871 0 : .await;
872 : // in principle new remote_consistent_lsn could allow to
873 : // deactivate the timeline, but we check that regularly through
874 : // broker updated, not need to do it here
875 : }
876 0 : _ => warn!("unexpected message {:?}", msg),
877 : }
878 0 : Ok(())
879 0 : }
880 : }
881 :
882 : #[cfg(test)]
883 : mod tests {
884 : use utils::id::{TenantId, TimelineId};
885 :
886 : use super::*;
887 :
888 4 : fn mock_ttid() -> TenantTimelineId {
889 4 : TenantTimelineId {
890 4 : tenant_id: TenantId::from_slice(&[0x00; 16]).unwrap(),
891 4 : timeline_id: TimelineId::from_slice(&[0x00; 16]).unwrap(),
892 4 : }
893 4 : }
894 :
895 4 : fn mock_addr() -> SocketAddr {
896 4 : "127.0.0.1:8080".parse().unwrap()
897 4 : }
898 :
899 : // add to wss specified feedback setting other fields to dummy values
900 4 : fn push_feedback(wss: &mut WalSendersShared, feedback: ReplicationFeedback) {
901 4 : let walsender_state = WalSenderState {
902 4 : ttid: mock_ttid(),
903 4 : addr: mock_addr(),
904 4 : conn_id: 1,
905 4 : appname: None,
906 4 : feedback,
907 4 : };
908 4 : wss.slots.push(Some(walsender_state))
909 4 : }
910 :
911 : // form standby feedback with given hot standby feedback ts/xmin and the
912 : // rest set to dummy values.
913 4 : fn hs_feedback(ts: TimestampTz, xmin: FullTransactionId) -> ReplicationFeedback {
914 4 : ReplicationFeedback::Standby(StandbyFeedback {
915 4 : reply: StandbyReply::empty(),
916 4 : hs_feedback: HotStandbyFeedback {
917 4 : ts,
918 4 : xmin,
919 4 : catalog_xmin: 0,
920 4 : },
921 4 : })
922 4 : }
923 :
924 : // test that hs aggregation works as expected
925 : #[test]
926 1 : fn test_hs_feedback_no_valid() {
927 1 : let mut wss = WalSendersShared::new();
928 1 : push_feedback(&mut wss, hs_feedback(1, INVALID_FULL_TRANSACTION_ID));
929 1 : wss.update_reply_feedback();
930 1 : assert_eq!(
931 1 : wss.agg_standby_feedback.hs_feedback.xmin,
932 1 : INVALID_FULL_TRANSACTION_ID
933 1 : );
934 1 : }
935 :
936 : #[test]
937 1 : fn test_hs_feedback() {
938 1 : let mut wss = WalSendersShared::new();
939 1 : push_feedback(&mut wss, hs_feedback(1, INVALID_FULL_TRANSACTION_ID));
940 1 : push_feedback(&mut wss, hs_feedback(1, 42));
941 1 : push_feedback(&mut wss, hs_feedback(1, 64));
942 1 : wss.update_reply_feedback();
943 1 : assert_eq!(wss.agg_standby_feedback.hs_feedback.xmin, 42);
944 1 : }
945 : }
|