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