Line data Source code
1 : //! Actual Postgres connection handler to stream WAL to the server.
2 :
3 : use std::{
4 : error::Error,
5 : pin::pin,
6 : str::FromStr,
7 : sync::Arc,
8 : time::{Duration, SystemTime},
9 : };
10 :
11 : use anyhow::{anyhow, Context};
12 : use bytes::BytesMut;
13 : use chrono::{NaiveDateTime, Utc};
14 : use fail::fail_point;
15 : use futures::StreamExt;
16 : use postgres::{error::SqlState, SimpleQueryMessage, SimpleQueryRow};
17 : use postgres_ffi::WAL_SEGMENT_SIZE;
18 : use postgres_ffi::{v14::xlog_utils::normalize_lsn, waldecoder::WalDecodeError};
19 : use postgres_protocol::message::backend::ReplicationMessage;
20 : use postgres_types::PgLsn;
21 : use tokio::{select, sync::watch, time};
22 : use tokio_postgres::{replication::ReplicationStream, Client};
23 : use tokio_util::sync::CancellationToken;
24 : use tracing::{debug, error, info, trace, warn, Instrument};
25 : use wal_decoder::{
26 : models::{FlushUncommittedRecords, InterpretedWalRecord, InterpretedWalRecords},
27 : wire_format::FromWireFormat,
28 : };
29 :
30 : use super::TaskStateUpdate;
31 : use crate::{
32 : context::RequestContext,
33 : metrics::{LIVE_CONNECTIONS, WALRECEIVER_STARTED_CONNECTIONS, WAL_INGEST},
34 : pgdatadir_mapping::DatadirModification,
35 : task_mgr::{TaskKind, WALRECEIVER_RUNTIME},
36 : tenant::{debug_assert_current_span_has_tenant_and_timeline_id, Timeline, WalReceiverInfo},
37 : walingest::WalIngest,
38 : };
39 : use postgres_backend::is_expected_io_error;
40 : use postgres_connection::PgConnectionConfig;
41 : use postgres_ffi::waldecoder::WalStreamDecoder;
42 : use utils::{id::NodeId, lsn::Lsn, postgres_client::PostgresClientProtocol};
43 : use utils::{pageserver_feedback::PageserverFeedback, sync::gate::GateError};
44 :
45 : /// Status of the connection.
46 : #[derive(Debug, Clone, Copy)]
47 : pub(super) struct WalConnectionStatus {
48 : /// If we were able to initiate a postgres connection, this means that safekeeper process is at least running.
49 : pub is_connected: bool,
50 : /// Defines a healthy connection as one on which pageserver received WAL from safekeeper
51 : /// and is able to process it in walingest without errors.
52 : pub has_processed_wal: bool,
53 : /// Connection establishment time or the timestamp of a latest connection message received.
54 : pub latest_connection_update: NaiveDateTime,
55 : /// Time of the latest WAL message received.
56 : pub latest_wal_update: NaiveDateTime,
57 : /// Latest WAL update contained WAL up to this LSN. Next WAL message with start from that LSN.
58 : pub streaming_lsn: Option<Lsn>,
59 : /// Latest commit_lsn received from the safekeeper. Can be zero if no message has been received yet.
60 : pub commit_lsn: Option<Lsn>,
61 : /// The node it is connected to
62 : pub node: NodeId,
63 : }
64 :
65 : pub(super) enum WalReceiverError {
66 : /// An error of a type that does not indicate an issue, e.g. a connection closing
67 : ExpectedSafekeeperError(postgres::Error),
68 : /// An "error" message that carries a SUCCESSFUL_COMPLETION status code. Carries
69 : /// the message part of the original postgres error
70 : SuccessfulCompletion(String),
71 : /// Generic error
72 : Other(anyhow::Error),
73 : ClosedGate,
74 : }
75 :
76 : impl From<tokio_postgres::Error> for WalReceiverError {
77 0 : fn from(err: tokio_postgres::Error) -> Self {
78 0 : if let Some(dberror) = err.as_db_error().filter(|db_error| {
79 0 : db_error.code() == &SqlState::SUCCESSFUL_COMPLETION
80 0 : && db_error.message().contains("ending streaming")
81 0 : }) {
82 : // Strip the outer DbError, which carries a misleading "error" severity
83 0 : Self::SuccessfulCompletion(dberror.message().to_string())
84 0 : } else if err.is_closed()
85 0 : || err
86 0 : .source()
87 0 : .and_then(|source| source.downcast_ref::<std::io::Error>())
88 0 : .map(is_expected_io_error)
89 0 : .unwrap_or(false)
90 : {
91 0 : Self::ExpectedSafekeeperError(err)
92 : } else {
93 0 : Self::Other(anyhow::Error::new(err))
94 : }
95 0 : }
96 : }
97 :
98 : impl From<anyhow::Error> for WalReceiverError {
99 0 : fn from(err: anyhow::Error) -> Self {
100 0 : Self::Other(err)
101 0 : }
102 : }
103 :
104 : impl From<WalDecodeError> for WalReceiverError {
105 0 : fn from(err: WalDecodeError) -> Self {
106 0 : Self::Other(anyhow::Error::new(err))
107 0 : }
108 : }
109 :
110 : /// Open a connection to the given safekeeper and receive WAL, sending back progress
111 : /// messages as we go.
112 : #[allow(clippy::too_many_arguments)]
113 0 : pub(super) async fn handle_walreceiver_connection(
114 0 : timeline: Arc<Timeline>,
115 0 : protocol: PostgresClientProtocol,
116 0 : wal_source_connconf: PgConnectionConfig,
117 0 : events_sender: watch::Sender<TaskStateUpdate<WalConnectionStatus>>,
118 0 : cancellation: CancellationToken,
119 0 : connect_timeout: Duration,
120 0 : ctx: RequestContext,
121 0 : node: NodeId,
122 0 : ingest_batch_size: u64,
123 0 : ) -> Result<(), WalReceiverError> {
124 0 : debug_assert_current_span_has_tenant_and_timeline_id();
125 :
126 : // prevent timeline shutdown from finishing until we have exited
127 0 : let _guard = timeline.gate.enter().map_err(|e| match e {
128 0 : GateError::GateClosed => WalReceiverError::ClosedGate,
129 0 : })?;
130 : // This function spawns a side-car task (WalReceiverConnectionPoller).
131 : // Get its gate guard now as well.
132 0 : let poller_guard = timeline.gate.enter().map_err(|e| match e {
133 0 : GateError::GateClosed => WalReceiverError::ClosedGate,
134 0 : })?;
135 :
136 0 : WALRECEIVER_STARTED_CONNECTIONS.inc();
137 0 :
138 0 : // Connect to the database in replication mode.
139 0 : info!("connecting to {wal_source_connconf:?}");
140 :
141 0 : let (replication_client, connection) = {
142 0 : let mut config = wal_source_connconf.to_tokio_postgres_config();
143 0 : config.application_name("pageserver");
144 0 : config.replication_mode(tokio_postgres::config::ReplicationMode::Physical);
145 0 : match time::timeout(connect_timeout, config.connect(postgres::NoTls)).await {
146 0 : Ok(client_and_conn) => client_and_conn?,
147 0 : Err(_elapsed) => {
148 0 : // Timing out to connect to a safekeeper node could happen long time, due to
149 0 : // many reasons that pageserver cannot control.
150 0 : // Do not produce an error, but make it visible, that timeouts happen by logging the `event.
151 0 : info!("Timed out while waiting {connect_timeout:?} for walreceiver connection to open");
152 0 : return Ok(());
153 : }
154 : }
155 : };
156 :
157 0 : debug!("connected!");
158 0 : let mut connection_status = WalConnectionStatus {
159 0 : is_connected: true,
160 0 : has_processed_wal: false,
161 0 : latest_connection_update: Utc::now().naive_utc(),
162 0 : latest_wal_update: Utc::now().naive_utc(),
163 0 : streaming_lsn: None,
164 0 : commit_lsn: None,
165 0 : node,
166 0 : };
167 0 : if let Err(e) = events_sender.send(TaskStateUpdate::Progress(connection_status)) {
168 0 : warn!("Wal connection event listener dropped right after connection init, aborting the connection: {e}");
169 0 : return Ok(());
170 0 : }
171 0 :
172 0 : // The connection object performs the actual communication with the database,
173 0 : // so spawn it off to run on its own. It shouldn't outlive this function, but,
174 0 : // due to lack of async drop, we can't enforce that. However, we ensure that
175 0 : // 1. it is sensitive to `cancellation` and
176 0 : // 2. holds the Timeline gate open so that after timeline shutdown,
177 0 : // we know this task is gone.
178 0 : let _connection_ctx = ctx.detached_child(
179 0 : TaskKind::WalReceiverConnectionPoller,
180 0 : ctx.download_behavior(),
181 0 : );
182 0 : let connection_cancellation = cancellation.clone();
183 0 : WALRECEIVER_RUNTIME.spawn(
184 0 : async move {
185 0 : debug_assert_current_span_has_tenant_and_timeline_id();
186 0 : select! {
187 0 : connection_result = connection => match connection_result {
188 0 : Ok(()) => debug!("Walreceiver db connection closed"),
189 0 : Err(connection_error) => {
190 0 : match WalReceiverError::from(connection_error) {
191 0 : WalReceiverError::ExpectedSafekeeperError(_) => {
192 0 : // silence, because most likely we've already exited the outer call
193 0 : // with a similar error.
194 0 : },
195 0 : WalReceiverError::SuccessfulCompletion(_) => {}
196 0 : WalReceiverError::ClosedGate => {
197 0 : // doesn't happen at runtime
198 0 : }
199 0 : WalReceiverError::Other(err) => {
200 0 : warn!("Connection aborted: {err:#}")
201 : }
202 : }
203 : }
204 : },
205 0 : _ = connection_cancellation.cancelled() => debug!("Connection cancelled"),
206 : }
207 0 : drop(poller_guard);
208 0 : }
209 : // Enrich the log lines emitted by this closure with meaningful context.
210 : // TODO: technically, this task outlives the surrounding function, so, the
211 : // spans won't be properly nested.
212 0 : .instrument(tracing::info_span!("poller")),
213 : );
214 :
215 0 : let _guard = LIVE_CONNECTIONS
216 0 : .with_label_values(&["wal_receiver"])
217 0 : .guard();
218 :
219 0 : let identify = identify_system(&replication_client).await?;
220 0 : info!("{identify:?}");
221 :
222 0 : let end_of_wal = Lsn::from(u64::from(identify.xlogpos));
223 0 : let mut caught_up = false;
224 0 :
225 0 : connection_status.latest_connection_update = Utc::now().naive_utc();
226 0 : connection_status.latest_wal_update = Utc::now().naive_utc();
227 0 : connection_status.commit_lsn = Some(end_of_wal);
228 0 : if let Err(e) = events_sender.send(TaskStateUpdate::Progress(connection_status)) {
229 0 : warn!("Wal connection event listener dropped after IDENTIFY_SYSTEM, aborting the connection: {e}");
230 0 : return Ok(());
231 0 : }
232 0 :
233 0 : //
234 0 : // Start streaming the WAL, from where we left off previously.
235 0 : //
236 0 : // If we had previously received WAL up to some point in the middle of a WAL record, we
237 0 : // better start from the end of last full WAL record, not in the middle of one.
238 0 : let mut last_rec_lsn = timeline.get_last_record_lsn();
239 0 : let mut startpoint = last_rec_lsn;
240 0 :
241 0 : if startpoint == Lsn(0) {
242 0 : return Err(WalReceiverError::Other(anyhow!("No previous WAL position")));
243 0 : }
244 0 :
245 0 : // There might be some padding after the last full record, skip it.
246 0 : startpoint += startpoint.calc_padding(8u32);
247 0 :
248 0 : // If the starting point is at a WAL page boundary, skip past the page header. We don't need the page headers
249 0 : // for anything, and in some corner cases, the compute node might have never generated the WAL for page headers
250 0 : //. That happens if you create a branch at page boundary: the start point of the branch is at the page boundary,
251 0 : // but when the compute node first starts on the branch, we normalize the first REDO position to just after the page
252 0 : // header (see generate_pg_control()), so the WAL for the page header is never streamed from the compute node
253 0 : // to the safekeepers.
254 0 : startpoint = normalize_lsn(startpoint, WAL_SEGMENT_SIZE);
255 0 :
256 0 : info!("last_record_lsn {last_rec_lsn} starting replication from {startpoint}, safekeeper is at {end_of_wal}...");
257 :
258 0 : let query = format!("START_REPLICATION PHYSICAL {startpoint}");
259 :
260 0 : let copy_stream = replication_client.copy_both_simple(&query).await?;
261 0 : let mut physical_stream = pin!(ReplicationStream::new(copy_stream));
262 0 :
263 0 : let mut waldecoder = WalStreamDecoder::new(startpoint, timeline.pg_version);
264 :
265 0 : let mut walingest = WalIngest::new(timeline.as_ref(), startpoint, &ctx).await?;
266 :
267 0 : let interpreted_proto_config = match protocol {
268 0 : PostgresClientProtocol::Vanilla => None,
269 : PostgresClientProtocol::Interpreted {
270 0 : format,
271 0 : compression,
272 0 : } => Some((format, compression)),
273 : };
274 :
275 0 : while let Some(replication_message) = {
276 0 : select! {
277 0 : _ = cancellation.cancelled() => {
278 0 : debug!("walreceiver interrupted");
279 0 : None
280 : }
281 0 : replication_message = physical_stream.next() => replication_message,
282 : }
283 : } {
284 0 : let replication_message = replication_message?;
285 :
286 0 : let now = Utc::now().naive_utc();
287 0 : let last_rec_lsn_before_msg = last_rec_lsn;
288 0 :
289 0 : // Update the connection status before processing the message. If the message processing
290 0 : // fails (e.g. in walingest), we still want to know latests LSNs from the safekeeper.
291 0 : match &replication_message {
292 0 : ReplicationMessage::XLogData(xlog_data) => {
293 0 : connection_status.latest_connection_update = now;
294 0 : connection_status.commit_lsn = Some(Lsn::from(xlog_data.wal_end()));
295 0 : connection_status.streaming_lsn = Some(Lsn::from(
296 0 : xlog_data.wal_start() + xlog_data.data().len() as u64,
297 0 : ));
298 0 : if !xlog_data.data().is_empty() {
299 0 : connection_status.latest_wal_update = now;
300 0 : }
301 : }
302 0 : ReplicationMessage::PrimaryKeepAlive(keepalive) => {
303 0 : connection_status.latest_connection_update = now;
304 0 : connection_status.commit_lsn = Some(Lsn::from(keepalive.wal_end()));
305 0 : }
306 0 : ReplicationMessage::RawInterpretedWalRecords(raw) => {
307 0 : connection_status.latest_connection_update = now;
308 0 : if !raw.data().is_empty() {
309 0 : connection_status.latest_wal_update = now;
310 0 : }
311 :
312 0 : connection_status.commit_lsn = Some(Lsn::from(raw.commit_lsn()));
313 0 : connection_status.streaming_lsn = Some(Lsn::from(raw.streaming_lsn()));
314 : }
315 0 : &_ => {}
316 : };
317 0 : if let Err(e) = events_sender.send(TaskStateUpdate::Progress(connection_status)) {
318 0 : warn!("Wal connection event listener dropped, aborting the connection: {e}");
319 0 : return Ok(());
320 0 : }
321 :
322 0 : let status_update = match replication_message {
323 0 : ReplicationMessage::RawInterpretedWalRecords(raw) => {
324 0 : WAL_INGEST.bytes_received.inc_by(raw.data().len() as u64);
325 0 :
326 0 : let mut uncommitted_records = 0;
327 0 :
328 0 : // This is the end LSN of the raw WAL from which the records
329 0 : // were interpreted.
330 0 : let streaming_lsn = Lsn::from(raw.streaming_lsn());
331 0 :
332 0 : let (format, compression) = interpreted_proto_config.unwrap();
333 0 : let batch = InterpretedWalRecords::from_wire(raw.data(), format, compression)
334 0 : .await
335 0 : .with_context(|| {
336 0 : anyhow::anyhow!(
337 0 : "Failed to deserialize interpreted records ending at LSN {streaming_lsn}"
338 0 : )
339 0 : })?;
340 :
341 : let InterpretedWalRecords {
342 0 : records,
343 0 : next_record_lsn,
344 0 : } = batch;
345 0 :
346 0 : tracing::debug!(
347 0 : "Received WAL up to {} with next_record_lsn={:?}",
348 : streaming_lsn,
349 : next_record_lsn
350 : );
351 :
352 : // We start the modification at 0 because each interpreted record
353 : // advances it to its end LSN. 0 is just an initialization placeholder.
354 0 : let mut modification = timeline.begin_modification(Lsn(0));
355 0 :
356 0 : if !records.is_empty() {
357 0 : timeline
358 0 : .metrics
359 0 : .wal_records_received
360 0 : .inc_by(records.len() as u64);
361 0 : }
362 :
363 0 : for interpreted in records {
364 0 : if matches!(interpreted.flush_uncommitted, FlushUncommittedRecords::Yes)
365 0 : && uncommitted_records > 0
366 : {
367 0 : modification.commit(&ctx).await?;
368 0 : uncommitted_records = 0;
369 0 : }
370 :
371 0 : let local_next_record_lsn = interpreted.next_record_lsn;
372 0 :
373 0 : if interpreted.is_observed() {
374 0 : WAL_INGEST.records_observed.inc();
375 0 : }
376 :
377 0 : walingest
378 0 : .ingest_record(interpreted, &mut modification, &ctx)
379 0 : .await
380 0 : .with_context(|| {
381 0 : format!("could not ingest record at {local_next_record_lsn}")
382 0 : })?;
383 :
384 0 : uncommitted_records += 1;
385 0 :
386 0 : // FIXME: this cannot be made pausable_failpoint without fixing the
387 0 : // failpoint library; in tests, the added amount of debugging will cause us
388 0 : // to timeout the tests.
389 0 : fail_point!("walreceiver-after-ingest");
390 0 :
391 0 : // Commit every ingest_batch_size records. Even if we filtered out
392 0 : // all records, we still need to call commit to advance the LSN.
393 0 : if uncommitted_records >= ingest_batch_size
394 0 : || modification.approx_pending_bytes()
395 0 : > DatadirModification::MAX_PENDING_BYTES
396 : {
397 0 : modification.commit(&ctx).await?;
398 0 : uncommitted_records = 0;
399 0 : }
400 : }
401 :
402 : // Records might have been filtered out on the safekeeper side, but we still
403 : // need to advance last record LSN on all shards. If we've not ingested the latest
404 : // record, then set the LSN of the modification past it. This way all shards
405 : // advance their last record LSN at the same time.
406 0 : let needs_last_record_lsn_advance = match next_record_lsn.map(Lsn::from) {
407 0 : Some(lsn) if lsn > modification.get_lsn() => {
408 0 : modification.set_lsn(lsn).unwrap();
409 0 : true
410 : }
411 0 : _ => false,
412 : };
413 :
414 0 : if uncommitted_records > 0 || needs_last_record_lsn_advance {
415 : // Commit any uncommitted records
416 0 : modification.commit(&ctx).await?;
417 0 : }
418 :
419 0 : if !caught_up && streaming_lsn >= end_of_wal {
420 0 : info!("caught up at LSN {streaming_lsn}");
421 0 : caught_up = true;
422 0 : }
423 :
424 0 : tracing::debug!(
425 0 : "Ingested WAL up to {streaming_lsn}. Last record LSN is {}",
426 0 : timeline.get_last_record_lsn()
427 : );
428 :
429 0 : if let Some(lsn) = next_record_lsn {
430 0 : last_rec_lsn = lsn;
431 0 : }
432 :
433 0 : Some(streaming_lsn)
434 : }
435 :
436 0 : ReplicationMessage::XLogData(xlog_data) => {
437 0 : async fn commit(
438 0 : modification: &mut DatadirModification<'_>,
439 0 : uncommitted: &mut u64,
440 0 : filtered: &mut u64,
441 0 : ctx: &RequestContext,
442 0 : ) -> anyhow::Result<()> {
443 0 : WAL_INGEST
444 0 : .records_committed
445 0 : .inc_by(*uncommitted - *filtered);
446 0 : modification.commit(ctx).await?;
447 0 : *uncommitted = 0;
448 0 : *filtered = 0;
449 0 : Ok(())
450 0 : }
451 :
452 : // Pass the WAL data to the decoder, and see if we can decode
453 : // more records as a result.
454 0 : let data = xlog_data.data();
455 0 : let startlsn = Lsn::from(xlog_data.wal_start());
456 0 : let endlsn = startlsn + data.len() as u64;
457 0 :
458 0 : trace!("received XLogData between {startlsn} and {endlsn}");
459 :
460 0 : WAL_INGEST.bytes_received.inc_by(data.len() as u64);
461 0 : waldecoder.feed_bytes(data);
462 0 :
463 0 : {
464 0 : let mut modification = timeline.begin_modification(startlsn);
465 0 : let mut uncommitted_records = 0;
466 0 : let mut filtered_records = 0;
467 :
468 0 : while let Some((next_record_lsn, recdata)) = waldecoder.poll_decode()? {
469 : // It is important to deal with the aligned records as lsn in getPage@LSN is
470 : // aligned and can be several bytes bigger. Without this alignment we are
471 : // at risk of hitting a deadlock.
472 0 : if !next_record_lsn.is_aligned() {
473 0 : return Err(WalReceiverError::Other(anyhow!("LSN not aligned")));
474 0 : }
475 :
476 : // Deserialize and interpret WAL record
477 0 : let interpreted = InterpretedWalRecord::from_bytes_filtered(
478 0 : recdata,
479 0 : modification.tline.get_shard_identity(),
480 0 : next_record_lsn,
481 0 : modification.tline.pg_version,
482 0 : )?;
483 :
484 0 : if matches!(interpreted.flush_uncommitted, FlushUncommittedRecords::Yes)
485 0 : && uncommitted_records > 0
486 : {
487 : // Special case: legacy PG database creations operate by reading pages from a 'template' database:
488 : // these are the only kinds of WAL record that require reading data blocks while ingesting. Ensure
489 : // all earlier writes of data blocks are visible by committing any modification in flight.
490 0 : commit(
491 0 : &mut modification,
492 0 : &mut uncommitted_records,
493 0 : &mut filtered_records,
494 0 : &ctx,
495 0 : )
496 0 : .await?;
497 0 : }
498 :
499 : // Ingest the records without immediately committing them.
500 0 : timeline.metrics.wal_records_received.inc();
501 0 : let ingested = walingest
502 0 : .ingest_record(interpreted, &mut modification, &ctx)
503 0 : .await
504 0 : .with_context(|| {
505 0 : format!("could not ingest record at {next_record_lsn}")
506 0 : })?;
507 0 : if !ingested {
508 0 : tracing::debug!("ingest: filtered out record @ LSN {next_record_lsn}");
509 0 : WAL_INGEST.records_filtered.inc();
510 0 : filtered_records += 1;
511 0 : }
512 :
513 : // FIXME: this cannot be made pausable_failpoint without fixing the
514 : // failpoint library; in tests, the added amount of debugging will cause us
515 : // to timeout the tests.
516 0 : fail_point!("walreceiver-after-ingest");
517 0 :
518 0 : last_rec_lsn = next_record_lsn;
519 0 :
520 0 : // Commit every ingest_batch_size records. Even if we filtered out
521 0 : // all records, we still need to call commit to advance the LSN.
522 0 : uncommitted_records += 1;
523 0 : if uncommitted_records >= ingest_batch_size
524 0 : || modification.approx_pending_bytes()
525 0 : > DatadirModification::MAX_PENDING_BYTES
526 : {
527 0 : commit(
528 0 : &mut modification,
529 0 : &mut uncommitted_records,
530 0 : &mut filtered_records,
531 0 : &ctx,
532 0 : )
533 0 : .await?;
534 0 : }
535 : }
536 :
537 : // Commit the remaining records.
538 0 : if uncommitted_records > 0 {
539 0 : commit(
540 0 : &mut modification,
541 0 : &mut uncommitted_records,
542 0 : &mut filtered_records,
543 0 : &ctx,
544 0 : )
545 0 : .await?;
546 0 : }
547 : }
548 :
549 0 : if !caught_up && endlsn >= end_of_wal {
550 0 : info!("caught up at LSN {endlsn}");
551 0 : caught_up = true;
552 0 : }
553 :
554 0 : Some(endlsn)
555 : }
556 :
557 0 : ReplicationMessage::PrimaryKeepAlive(keepalive) => {
558 0 : let wal_end = keepalive.wal_end();
559 0 : let timestamp = keepalive.timestamp();
560 0 : let reply_requested = keepalive.reply() != 0;
561 0 :
562 0 : trace!("received PrimaryKeepAlive(wal_end: {wal_end}, timestamp: {timestamp:?} reply: {reply_requested})");
563 :
564 0 : if reply_requested {
565 0 : Some(last_rec_lsn)
566 : } else {
567 0 : None
568 : }
569 : }
570 :
571 0 : _ => None,
572 : };
573 :
574 0 : if !connection_status.has_processed_wal && last_rec_lsn > last_rec_lsn_before_msg {
575 : // We have successfully processed at least one WAL record.
576 0 : connection_status.has_processed_wal = true;
577 0 : if let Err(e) = events_sender.send(TaskStateUpdate::Progress(connection_status)) {
578 0 : warn!("Wal connection event listener dropped, aborting the connection: {e}");
579 0 : return Ok(());
580 0 : }
581 0 : }
582 :
583 0 : if let Some(last_lsn) = status_update {
584 0 : let timeline_remote_consistent_lsn = timeline
585 0 : .get_remote_consistent_lsn_visible()
586 0 : .unwrap_or(Lsn(0));
587 0 :
588 0 : // The last LSN we processed. It is not guaranteed to survive pageserver crash.
589 0 : let last_received_lsn = last_lsn;
590 0 : // `disk_consistent_lsn` is the LSN at which page server guarantees local persistence of all received data
591 0 : let disk_consistent_lsn = timeline.get_disk_consistent_lsn();
592 0 : // The last LSN that is synced to remote storage and is guaranteed to survive pageserver crash
593 0 : // Used by safekeepers to remove WAL preceding `remote_consistent_lsn`.
594 0 : let remote_consistent_lsn = timeline_remote_consistent_lsn;
595 0 : let ts = SystemTime::now();
596 0 :
597 0 : // Update the status about what we just received. This is shown in the mgmt API.
598 0 : let last_received_wal = WalReceiverInfo {
599 0 : wal_source_connconf: wal_source_connconf.clone(),
600 0 : last_received_msg_lsn: last_lsn,
601 0 : last_received_msg_ts: ts
602 0 : .duration_since(SystemTime::UNIX_EPOCH)
603 0 : .expect("Received message time should be before UNIX EPOCH!")
604 0 : .as_micros(),
605 0 : };
606 0 : *timeline.last_received_wal.lock().unwrap() = Some(last_received_wal);
607 :
608 : // Send the replication feedback message.
609 : // Regular standby_status_update fields are put into this message.
610 0 : let current_timeline_size = if timeline.tenant_shard_id.is_shard_zero() {
611 0 : timeline
612 0 : .get_current_logical_size(
613 0 : crate::tenant::timeline::GetLogicalSizePriority::User,
614 0 : &ctx,
615 0 : )
616 0 : // FIXME: https://github.com/neondatabase/neon/issues/5963
617 0 : .size_dont_care_about_accuracy()
618 : } else {
619 : // Non-zero shards send zero for logical size. The safekeeper will ignore
620 : // this number. This is because in a sharded tenant, only shard zero maintains
621 : // accurate logical size.
622 0 : 0
623 : };
624 :
625 0 : let status_update = PageserverFeedback {
626 0 : current_timeline_size,
627 0 : last_received_lsn,
628 0 : disk_consistent_lsn,
629 0 : remote_consistent_lsn,
630 0 : replytime: ts,
631 0 : shard_number: timeline.tenant_shard_id.shard_number.0 as u32,
632 0 : };
633 0 :
634 0 : debug!("neon_status_update {status_update:?}");
635 :
636 0 : let mut data = BytesMut::new();
637 0 : status_update.serialize(&mut data);
638 0 : physical_stream
639 0 : .as_mut()
640 0 : .zenith_status_update(data.len() as u64, &data)
641 0 : .await?;
642 0 : }
643 : }
644 :
645 0 : Ok(())
646 0 : }
647 :
648 : /// Data returned from the postgres `IDENTIFY_SYSTEM` command
649 : ///
650 : /// See the [postgres docs] for more details.
651 : ///
652 : /// [postgres docs]: https://www.postgresql.org/docs/current/protocol-replication.html
653 : #[derive(Debug)]
654 : // As of nightly 2021-09-11, fields that are only read by the type's `Debug` impl still count as
655 : // unused. Relevant issue: https://github.com/rust-lang/rust/issues/88900
656 : #[allow(dead_code)]
657 : struct IdentifySystem {
658 : systemid: u64,
659 : timeline: u32,
660 : xlogpos: PgLsn,
661 : dbname: Option<String>,
662 : }
663 :
664 : /// There was a problem parsing the response to
665 : /// a postgres IDENTIFY_SYSTEM command.
666 : #[derive(Debug, thiserror::Error)]
667 : #[error("IDENTIFY_SYSTEM parse error")]
668 : struct IdentifyError;
669 :
670 : /// Run the postgres `IDENTIFY_SYSTEM` command
671 0 : async fn identify_system(client: &Client) -> anyhow::Result<IdentifySystem> {
672 0 : let query_str = "IDENTIFY_SYSTEM";
673 0 : let response = client.simple_query(query_str).await?;
674 :
675 : // get(N) from row, then parse it as some destination type.
676 0 : fn get_parse<T>(row: &SimpleQueryRow, idx: usize) -> Result<T, IdentifyError>
677 0 : where
678 0 : T: FromStr,
679 0 : {
680 0 : let val = row.get(idx).ok_or(IdentifyError)?;
681 0 : val.parse::<T>().or(Err(IdentifyError))
682 0 : }
683 :
684 : // extract the row contents into an IdentifySystem struct.
685 : // written as a closure so I can use ? for Option here.
686 0 : if let Some(SimpleQueryMessage::Row(first_row)) = response.first() {
687 : Ok(IdentifySystem {
688 0 : systemid: get_parse(first_row, 0)?,
689 0 : timeline: get_parse(first_row, 1)?,
690 0 : xlogpos: get_parse(first_row, 2)?,
691 0 : dbname: get_parse(first_row, 3).ok(),
692 : })
693 : } else {
694 0 : Err(IdentifyError.into())
695 : }
696 0 : }
|