LCOV - code coverage report
Current view: top level - pageserver/src/tenant/timeline/walreceiver - walreceiver_connection.rs (source / functions) Coverage Total Hit
Test: 45c9170b95180e9ecfad9a53e031030abf2a178c.info Lines: 0.0 % 504 0
Test Date: 2025-02-21 15:51:08 Functions: 0.0 % 23 0

            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::{critical, 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 :     safekeeper_node: NodeId,
     122            0 :     ingest_batch_size: u64,
     123            0 :     validate_wal_contiguity: bool,
     124            0 : ) -> Result<(), WalReceiverError> {
     125            0 :     debug_assert_current_span_has_tenant_and_timeline_id();
     126              : 
     127              :     // prevent timeline shutdown from finishing until we have exited
     128            0 :     let _guard = timeline.gate.enter().map_err(|e| match e {
     129            0 :         GateError::GateClosed => WalReceiverError::ClosedGate,
     130            0 :     })?;
     131              :     // This function spawns a side-car task (WalReceiverConnectionPoller).
     132              :     // Get its gate guard now as well.
     133            0 :     let poller_guard = timeline.gate.enter().map_err(|e| match e {
     134            0 :         GateError::GateClosed => WalReceiverError::ClosedGate,
     135            0 :     })?;
     136              : 
     137            0 :     WALRECEIVER_STARTED_CONNECTIONS.inc();
     138            0 : 
     139            0 :     // Connect to the database in replication mode.
     140            0 :     info!("connecting to {wal_source_connconf:?}");
     141              : 
     142            0 :     let (replication_client, connection) = {
     143            0 :         let mut config = wal_source_connconf.to_tokio_postgres_config();
     144            0 :         config.application_name(format!("pageserver-{}", timeline.conf.id.0).as_str());
     145            0 :         config.replication_mode(tokio_postgres::config::ReplicationMode::Physical);
     146            0 :         match time::timeout(connect_timeout, config.connect(postgres::NoTls)).await {
     147            0 :             Ok(client_and_conn) => client_and_conn?,
     148            0 :             Err(_elapsed) => {
     149            0 :                 // Timing out to connect to a safekeeper node could happen long time, due to
     150            0 :                 // many reasons that pageserver cannot control.
     151            0 :                 // Do not produce an error, but make it visible, that timeouts happen by logging the `event.
     152            0 :                 info!("Timed out while waiting {connect_timeout:?} for walreceiver connection to open");
     153            0 :                 return Ok(());
     154              :             }
     155              :         }
     156              :     };
     157              : 
     158            0 :     debug!("connected!");
     159            0 :     let mut connection_status = WalConnectionStatus {
     160            0 :         is_connected: true,
     161            0 :         has_processed_wal: false,
     162            0 :         latest_connection_update: Utc::now().naive_utc(),
     163            0 :         latest_wal_update: Utc::now().naive_utc(),
     164            0 :         streaming_lsn: None,
     165            0 :         commit_lsn: None,
     166            0 :         node: safekeeper_node,
     167            0 :     };
     168            0 :     if let Err(e) = events_sender.send(TaskStateUpdate::Progress(connection_status)) {
     169            0 :         warn!("Wal connection event listener dropped right after connection init, aborting the connection: {e}");
     170            0 :         return Ok(());
     171            0 :     }
     172            0 : 
     173            0 :     // The connection object performs the actual communication with the database,
     174            0 :     // so spawn it off to run on its own. It shouldn't outlive this function, but,
     175            0 :     // due to lack of async drop, we can't enforce that. However, we ensure that
     176            0 :     // 1. it is sensitive to `cancellation` and
     177            0 :     // 2. holds the Timeline gate open so that after timeline shutdown,
     178            0 :     //    we know this task is gone.
     179            0 :     let _connection_ctx = ctx.detached_child(
     180            0 :         TaskKind::WalReceiverConnectionPoller,
     181            0 :         ctx.download_behavior(),
     182            0 :     );
     183            0 :     let connection_cancellation = cancellation.clone();
     184            0 :     WALRECEIVER_RUNTIME.spawn(
     185            0 :         async move {
     186            0 :             debug_assert_current_span_has_tenant_and_timeline_id();
     187            0 :             select! {
     188            0 :                 connection_result = connection => match connection_result {
     189            0 :                     Ok(()) => debug!("Walreceiver db connection closed"),
     190            0 :                     Err(connection_error) => {
     191            0 :                         match WalReceiverError::from(connection_error) {
     192            0 :                             WalReceiverError::ExpectedSafekeeperError(_) => {
     193            0 :                                 // silence, because most likely we've already exited the outer call
     194            0 :                                 // with a similar error.
     195            0 :                             },
     196            0 :                             WalReceiverError::SuccessfulCompletion(_) => {}
     197            0 :                             WalReceiverError::ClosedGate => {
     198            0 :                                 // doesn't happen at runtime
     199            0 :                             }
     200            0 :                             WalReceiverError::Other(err) => {
     201            0 :                                 warn!("Connection aborted: {err:#}")
     202              :                             }
     203              :                         }
     204              :                     }
     205              :                 },
     206            0 :                 _ = connection_cancellation.cancelled() => debug!("Connection cancelled"),
     207              :             }
     208            0 :             drop(poller_guard);
     209            0 :         }
     210              :         // Enrich the log lines emitted by this closure with meaningful context.
     211              :         // TODO: technically, this task outlives the surrounding function, so, the
     212              :         // spans won't be properly nested.
     213            0 :         .instrument(tracing::info_span!("poller")),
     214              :     );
     215              : 
     216            0 :     let _guard = LIVE_CONNECTIONS
     217            0 :         .with_label_values(&["wal_receiver"])
     218            0 :         .guard();
     219              : 
     220            0 :     let identify = identify_system(&replication_client).await?;
     221            0 :     info!("{identify:?}");
     222              : 
     223            0 :     let end_of_wal = Lsn::from(u64::from(identify.xlogpos));
     224            0 :     let mut caught_up = false;
     225            0 : 
     226            0 :     connection_status.latest_connection_update = Utc::now().naive_utc();
     227            0 :     connection_status.latest_wal_update = Utc::now().naive_utc();
     228            0 :     connection_status.commit_lsn = Some(end_of_wal);
     229            0 :     if let Err(e) = events_sender.send(TaskStateUpdate::Progress(connection_status)) {
     230            0 :         warn!("Wal connection event listener dropped after IDENTIFY_SYSTEM, aborting the connection: {e}");
     231            0 :         return Ok(());
     232            0 :     }
     233            0 : 
     234            0 :     //
     235            0 :     // Start streaming the WAL, from where we left off previously.
     236            0 :     //
     237            0 :     // If we had previously received WAL up to some point in the middle of a WAL record, we
     238            0 :     // better start from the end of last full WAL record, not in the middle of one.
     239            0 :     let mut last_rec_lsn = timeline.get_last_record_lsn();
     240            0 :     let mut startpoint = last_rec_lsn;
     241            0 : 
     242            0 :     if startpoint == Lsn(0) {
     243            0 :         return Err(WalReceiverError::Other(anyhow!("No previous WAL position")));
     244            0 :     }
     245            0 : 
     246            0 :     // There might be some padding after the last full record, skip it.
     247            0 :     startpoint += startpoint.calc_padding(8u32);
     248            0 : 
     249            0 :     // If the starting point is at a WAL page boundary, skip past the page header. We don't need the page headers
     250            0 :     // for anything, and in some corner cases, the compute node might have never generated the WAL for page headers
     251            0 :     //. That happens if you create a branch at page boundary: the start point of the branch is at the page boundary,
     252            0 :     // but when the compute node first starts on the branch, we normalize the first REDO position to just after the page
     253            0 :     // header (see generate_pg_control()), so the WAL for the page header is never streamed from the compute node
     254            0 :     //  to the safekeepers.
     255            0 :     startpoint = normalize_lsn(startpoint, WAL_SEGMENT_SIZE);
     256            0 : 
     257            0 :     info!("last_record_lsn {last_rec_lsn} starting replication from {startpoint}, safekeeper is at {end_of_wal}...");
     258              : 
     259            0 :     let query = format!("START_REPLICATION PHYSICAL {startpoint}");
     260              : 
     261            0 :     let copy_stream = replication_client.copy_both_simple(&query).await?;
     262            0 :     let mut physical_stream = pin!(ReplicationStream::new(copy_stream));
     263            0 : 
     264            0 :     let mut waldecoder = WalStreamDecoder::new(startpoint, timeline.pg_version);
     265              : 
     266            0 :     let mut walingest = WalIngest::new(timeline.as_ref(), startpoint, &ctx).await?;
     267              : 
     268            0 :     let shard = vec![*timeline.get_shard_identity()];
     269              : 
     270            0 :     let interpreted_proto_config = match protocol {
     271            0 :         PostgresClientProtocol::Vanilla => None,
     272              :         PostgresClientProtocol::Interpreted {
     273            0 :             format,
     274            0 :             compression,
     275            0 :         } => Some((format, compression)),
     276              :     };
     277              : 
     278            0 :     let mut expected_wal_start = startpoint;
     279            0 :     while let Some(replication_message) = {
     280            0 :         select! {
     281            0 :             _ = cancellation.cancelled() => {
     282            0 :                 debug!("walreceiver interrupted");
     283            0 :                 None
     284              :             }
     285            0 :             replication_message = physical_stream.next() => replication_message,
     286              :         }
     287              :     } {
     288            0 :         let replication_message = replication_message?;
     289              : 
     290            0 :         let now = Utc::now().naive_utc();
     291            0 :         let last_rec_lsn_before_msg = last_rec_lsn;
     292            0 : 
     293            0 :         // Update the connection status before processing the message. If the message processing
     294            0 :         // fails (e.g. in walingest), we still want to know latests LSNs from the safekeeper.
     295            0 :         match &replication_message {
     296            0 :             ReplicationMessage::XLogData(xlog_data) => {
     297            0 :                 connection_status.latest_connection_update = now;
     298            0 :                 connection_status.commit_lsn = Some(Lsn::from(xlog_data.wal_end()));
     299            0 :                 connection_status.streaming_lsn = Some(Lsn::from(
     300            0 :                     xlog_data.wal_start() + xlog_data.data().len() as u64,
     301            0 :                 ));
     302            0 :                 if !xlog_data.data().is_empty() {
     303            0 :                     connection_status.latest_wal_update = now;
     304            0 :                 }
     305              :             }
     306            0 :             ReplicationMessage::PrimaryKeepAlive(keepalive) => {
     307            0 :                 connection_status.latest_connection_update = now;
     308            0 :                 connection_status.commit_lsn = Some(Lsn::from(keepalive.wal_end()));
     309            0 :             }
     310            0 :             ReplicationMessage::RawInterpretedWalRecords(raw) => {
     311            0 :                 connection_status.latest_connection_update = now;
     312            0 :                 if !raw.data().is_empty() {
     313            0 :                     connection_status.latest_wal_update = now;
     314            0 :                 }
     315              : 
     316            0 :                 connection_status.commit_lsn = Some(Lsn::from(raw.commit_lsn()));
     317            0 :                 connection_status.streaming_lsn = Some(Lsn::from(raw.streaming_lsn()));
     318              :             }
     319            0 :             &_ => {}
     320              :         };
     321            0 :         if let Err(e) = events_sender.send(TaskStateUpdate::Progress(connection_status)) {
     322            0 :             warn!("Wal connection event listener dropped, aborting the connection: {e}");
     323            0 :             return Ok(());
     324            0 :         }
     325              : 
     326            0 :         let status_update = match replication_message {
     327            0 :             ReplicationMessage::RawInterpretedWalRecords(raw) => {
     328            0 :                 WAL_INGEST.bytes_received.inc_by(raw.data().len() as u64);
     329            0 : 
     330            0 :                 let mut uncommitted_records = 0;
     331            0 : 
     332            0 :                 // This is the end LSN of the raw WAL from which the records
     333            0 :                 // were interpreted.
     334            0 :                 let streaming_lsn = Lsn::from(raw.streaming_lsn());
     335            0 : 
     336            0 :                 let (format, compression) = interpreted_proto_config.unwrap();
     337            0 :                 let batch = InterpretedWalRecords::from_wire(raw.data(), format, compression)
     338            0 :                     .await
     339            0 :                     .with_context(|| {
     340            0 :                         anyhow::anyhow!(
     341            0 :                         "Failed to deserialize interpreted records ending at LSN {streaming_lsn}"
     342            0 :                     )
     343            0 :                     })?;
     344              : 
     345              :                 // Guard against WAL gaps. If the start LSN of the PG WAL section
     346              :                 // from which the interpreted records were extracted, doesn't match
     347              :                 // the end of the previous batch (or the starting point for the first batch),
     348              :                 // then kill this WAL receiver connection and start a new one.
     349            0 :                 if validate_wal_contiguity {
     350            0 :                     if let Some(raw_wal_start_lsn) = batch.raw_wal_start_lsn {
     351            0 :                         match raw_wal_start_lsn.cmp(&expected_wal_start) {
     352              :                             std::cmp::Ordering::Greater => {
     353            0 :                                 let msg = format!(
     354            0 :                                     "Gap in streamed WAL: [{}, {})",
     355            0 :                                     expected_wal_start, raw_wal_start_lsn
     356            0 :                                 );
     357            0 :                                 critical!("{msg}");
     358            0 :                                 return Err(WalReceiverError::Other(anyhow!(msg)));
     359              :                             }
     360              :                             std::cmp::Ordering::Less => {
     361              :                                 // Other shards are reading WAL behind us.
     362              :                                 // This is valid, but check that we received records
     363              :                                 // that we haven't seen before.
     364            0 :                                 if let Some(first_rec) = batch.records.first() {
     365            0 :                                     if first_rec.next_record_lsn < last_rec_lsn {
     366            0 :                                         let msg = format!(
     367            0 :                                             "Received record with next_record_lsn multiple times ({} < {})",
     368            0 :                                             first_rec.next_record_lsn, expected_wal_start
     369            0 :                                         );
     370            0 :                                         critical!("{msg}");
     371            0 :                                         return Err(WalReceiverError::Other(anyhow!(msg)));
     372            0 :                                     }
     373            0 :                                 }
     374              :                             }
     375            0 :                             std::cmp::Ordering::Equal => {}
     376              :                         }
     377            0 :                     }
     378            0 :                 }
     379              : 
     380              :                 let InterpretedWalRecords {
     381            0 :                     records,
     382            0 :                     next_record_lsn,
     383            0 :                     raw_wal_start_lsn: _,
     384            0 :                 } = batch;
     385            0 : 
     386            0 :                 tracing::debug!(
     387            0 :                     "Received WAL up to {} with next_record_lsn={}",
     388              :                     streaming_lsn,
     389              :                     next_record_lsn
     390              :                 );
     391              : 
     392              :                 // We start the modification at 0 because each interpreted record
     393              :                 // advances it to its end LSN. 0 is just an initialization placeholder.
     394            0 :                 let mut modification = timeline.begin_modification(Lsn(0));
     395              : 
     396            0 :                 async fn commit(
     397            0 :                     modification: &mut DatadirModification<'_>,
     398            0 :                     ctx: &RequestContext,
     399            0 :                     uncommitted: &mut u64,
     400            0 :                 ) -> anyhow::Result<()> {
     401            0 :                     let stats = modification.stats();
     402            0 :                     modification.commit(ctx).await?;
     403            0 :                     WAL_INGEST.records_committed.inc_by(*uncommitted);
     404            0 :                     WAL_INGEST.inc_values_committed(&stats);
     405            0 :                     *uncommitted = 0;
     406            0 :                     Ok(())
     407            0 :                 }
     408              : 
     409            0 :                 if !records.is_empty() {
     410            0 :                     timeline
     411            0 :                         .metrics
     412            0 :                         .wal_records_received
     413            0 :                         .inc_by(records.len() as u64);
     414            0 :                 }
     415              : 
     416            0 :                 for interpreted in records {
     417            0 :                     if matches!(interpreted.flush_uncommitted, FlushUncommittedRecords::Yes)
     418            0 :                         && uncommitted_records > 0
     419              :                     {
     420            0 :                         commit(&mut modification, &ctx, &mut uncommitted_records).await?;
     421            0 :                     }
     422              : 
     423            0 :                     let local_next_record_lsn = interpreted.next_record_lsn;
     424            0 : 
     425            0 :                     if interpreted.is_observed() {
     426            0 :                         WAL_INGEST.records_observed.inc();
     427            0 :                     }
     428              : 
     429            0 :                     walingest
     430            0 :                         .ingest_record(interpreted, &mut modification, &ctx)
     431            0 :                         .await
     432            0 :                         .with_context(|| {
     433            0 :                             format!("could not ingest record at {local_next_record_lsn}")
     434            0 :                         })
     435            0 :                         .inspect_err(|err| {
     436            0 :                             // TODO: we can't differentiate cancellation errors with
     437            0 :                             // anyhow::Error, so just ignore it if we're cancelled.
     438            0 :                             if !cancellation.is_cancelled() {
     439            0 :                                 critical!("{err:?}")
     440            0 :                             }
     441            0 :                         })?;
     442              : 
     443            0 :                     uncommitted_records += 1;
     444            0 : 
     445            0 :                     // FIXME: this cannot be made pausable_failpoint without fixing the
     446            0 :                     // failpoint library; in tests, the added amount of debugging will cause us
     447            0 :                     // to timeout the tests.
     448            0 :                     fail_point!("walreceiver-after-ingest");
     449            0 : 
     450            0 :                     // Commit every ingest_batch_size records. Even if we filtered out
     451            0 :                     // all records, we still need to call commit to advance the LSN.
     452            0 :                     if uncommitted_records >= ingest_batch_size
     453            0 :                         || modification.approx_pending_bytes()
     454            0 :                             > DatadirModification::MAX_PENDING_BYTES
     455              :                     {
     456            0 :                         commit(&mut modification, &ctx, &mut uncommitted_records).await?;
     457            0 :                     }
     458              :                 }
     459              : 
     460              :                 // Records might have been filtered out on the safekeeper side, but we still
     461              :                 // need to advance last record LSN on all shards. If we've not ingested the latest
     462              :                 // record, then set the LSN of the modification past it. This way all shards
     463              :                 // advance their last record LSN at the same time.
     464            0 :                 let needs_last_record_lsn_advance = if next_record_lsn > modification.get_lsn() {
     465            0 :                     modification.set_lsn(next_record_lsn).unwrap();
     466            0 :                     true
     467              :                 } else {
     468            0 :                     false
     469              :                 };
     470              : 
     471            0 :                 if uncommitted_records > 0 || needs_last_record_lsn_advance {
     472              :                     // Commit any uncommitted records
     473            0 :                     commit(&mut modification, &ctx, &mut uncommitted_records).await?;
     474            0 :                 }
     475              : 
     476            0 :                 if !caught_up && streaming_lsn >= end_of_wal {
     477            0 :                     info!("caught up at LSN {streaming_lsn}");
     478            0 :                     caught_up = true;
     479            0 :                 }
     480              : 
     481            0 :                 tracing::debug!(
     482            0 :                     "Ingested WAL up to {streaming_lsn}. Last record LSN is {}",
     483            0 :                     timeline.get_last_record_lsn()
     484              :                 );
     485              : 
     486            0 :                 last_rec_lsn = next_record_lsn;
     487            0 :                 expected_wal_start = streaming_lsn;
     488            0 : 
     489            0 :                 Some(streaming_lsn)
     490              :             }
     491              : 
     492            0 :             ReplicationMessage::XLogData(xlog_data) => {
     493            0 :                 async fn commit(
     494            0 :                     modification: &mut DatadirModification<'_>,
     495            0 :                     uncommitted: &mut u64,
     496            0 :                     filtered: &mut u64,
     497            0 :                     ctx: &RequestContext,
     498            0 :                 ) -> anyhow::Result<()> {
     499            0 :                     let stats = modification.stats();
     500            0 :                     modification.commit(ctx).await?;
     501            0 :                     WAL_INGEST
     502            0 :                         .records_committed
     503            0 :                         .inc_by(*uncommitted - *filtered);
     504            0 :                     WAL_INGEST.inc_values_committed(&stats);
     505            0 :                     *uncommitted = 0;
     506            0 :                     *filtered = 0;
     507            0 :                     Ok(())
     508            0 :                 }
     509              : 
     510              :                 // Pass the WAL data to the decoder, and see if we can decode
     511              :                 // more records as a result.
     512            0 :                 let data = xlog_data.data();
     513            0 :                 let startlsn = Lsn::from(xlog_data.wal_start());
     514            0 :                 let endlsn = startlsn + data.len() as u64;
     515            0 : 
     516            0 :                 trace!("received XLogData between {startlsn} and {endlsn}");
     517              : 
     518            0 :                 WAL_INGEST.bytes_received.inc_by(data.len() as u64);
     519            0 :                 waldecoder.feed_bytes(data);
     520            0 : 
     521            0 :                 {
     522            0 :                     let mut modification = timeline.begin_modification(startlsn);
     523            0 :                     let mut uncommitted_records = 0;
     524            0 :                     let mut filtered_records = 0;
     525              : 
     526            0 :                     while let Some((next_record_lsn, recdata)) = waldecoder.poll_decode()? {
     527              :                         // It is important to deal with the aligned records as lsn in getPage@LSN is
     528              :                         // aligned and can be several bytes bigger. Without this alignment we are
     529              :                         // at risk of hitting a deadlock.
     530            0 :                         if !next_record_lsn.is_aligned() {
     531            0 :                             return Err(WalReceiverError::Other(anyhow!("LSN not aligned")));
     532            0 :                         }
     533              : 
     534              :                         // Deserialize and interpret WAL record
     535            0 :                         let interpreted = InterpretedWalRecord::from_bytes_filtered(
     536            0 :                             recdata,
     537            0 :                             &shard,
     538            0 :                             next_record_lsn,
     539            0 :                             modification.tline.pg_version,
     540            0 :                         )?
     541            0 :                         .remove(timeline.get_shard_identity())
     542            0 :                         .unwrap();
     543              : 
     544            0 :                         if matches!(interpreted.flush_uncommitted, FlushUncommittedRecords::Yes)
     545            0 :                             && uncommitted_records > 0
     546              :                         {
     547              :                             // Special case: legacy PG database creations operate by reading pages from a 'template' database:
     548              :                             // these are the only kinds of WAL record that require reading data blocks while ingesting.  Ensure
     549              :                             // all earlier writes of data blocks are visible by committing any modification in flight.
     550            0 :                             commit(
     551            0 :                                 &mut modification,
     552            0 :                                 &mut uncommitted_records,
     553            0 :                                 &mut filtered_records,
     554            0 :                                 &ctx,
     555            0 :                             )
     556            0 :                             .await?;
     557            0 :                         }
     558              : 
     559              :                         // Ingest the records without immediately committing them.
     560            0 :                         timeline.metrics.wal_records_received.inc();
     561            0 :                         let ingested = walingest
     562            0 :                             .ingest_record(interpreted, &mut modification, &ctx)
     563            0 :                             .await
     564            0 :                             .with_context(|| {
     565            0 :                                 format!("could not ingest record at {next_record_lsn}")
     566            0 :                             })
     567            0 :                             .inspect_err(|err| {
     568            0 :                                 // TODO: we can't differentiate cancellation errors with
     569            0 :                                 // anyhow::Error, so just ignore it if we're cancelled.
     570            0 :                                 if !cancellation.is_cancelled() {
     571            0 :                                     critical!("{err:?}")
     572            0 :                                 }
     573            0 :                             })?;
     574            0 :                         if !ingested {
     575            0 :                             tracing::debug!("ingest: filtered out record @ LSN {next_record_lsn}");
     576            0 :                             WAL_INGEST.records_filtered.inc();
     577            0 :                             filtered_records += 1;
     578            0 :                         }
     579              : 
     580              :                         // FIXME: this cannot be made pausable_failpoint without fixing the
     581              :                         // failpoint library; in tests, the added amount of debugging will cause us
     582              :                         // to timeout the tests.
     583            0 :                         fail_point!("walreceiver-after-ingest");
     584            0 : 
     585            0 :                         last_rec_lsn = next_record_lsn;
     586            0 : 
     587            0 :                         // Commit every ingest_batch_size records. Even if we filtered out
     588            0 :                         // all records, we still need to call commit to advance the LSN.
     589            0 :                         uncommitted_records += 1;
     590            0 :                         if uncommitted_records >= ingest_batch_size
     591            0 :                             || modification.approx_pending_bytes()
     592            0 :                                 > DatadirModification::MAX_PENDING_BYTES
     593              :                         {
     594            0 :                             commit(
     595            0 :                                 &mut modification,
     596            0 :                                 &mut uncommitted_records,
     597            0 :                                 &mut filtered_records,
     598            0 :                                 &ctx,
     599            0 :                             )
     600            0 :                             .await?;
     601            0 :                         }
     602              :                     }
     603              : 
     604              :                     // Commit the remaining records.
     605            0 :                     if uncommitted_records > 0 {
     606            0 :                         commit(
     607            0 :                             &mut modification,
     608            0 :                             &mut uncommitted_records,
     609            0 :                             &mut filtered_records,
     610            0 :                             &ctx,
     611            0 :                         )
     612            0 :                         .await?;
     613            0 :                     }
     614              :                 }
     615              : 
     616            0 :                 if !caught_up && endlsn >= end_of_wal {
     617            0 :                     info!("caught up at LSN {endlsn}");
     618            0 :                     caught_up = true;
     619            0 :                 }
     620              : 
     621            0 :                 Some(endlsn)
     622              :             }
     623              : 
     624            0 :             ReplicationMessage::PrimaryKeepAlive(keepalive) => {
     625            0 :                 let wal_end = keepalive.wal_end();
     626            0 :                 let timestamp = keepalive.timestamp();
     627            0 :                 let reply_requested = keepalive.reply() != 0;
     628            0 : 
     629            0 :                 trace!("received PrimaryKeepAlive(wal_end: {wal_end}, timestamp: {timestamp:?} reply: {reply_requested})");
     630              : 
     631            0 :                 if reply_requested {
     632            0 :                     Some(last_rec_lsn)
     633              :                 } else {
     634            0 :                     None
     635              :                 }
     636              :             }
     637              : 
     638            0 :             _ => None,
     639              :         };
     640              : 
     641            0 :         if !connection_status.has_processed_wal && last_rec_lsn > last_rec_lsn_before_msg {
     642              :             // We have successfully processed at least one WAL record.
     643            0 :             connection_status.has_processed_wal = true;
     644            0 :             if let Err(e) = events_sender.send(TaskStateUpdate::Progress(connection_status)) {
     645            0 :                 warn!("Wal connection event listener dropped, aborting the connection: {e}");
     646            0 :                 return Ok(());
     647            0 :             }
     648            0 :         }
     649              : 
     650            0 :         if let Some(last_lsn) = status_update {
     651            0 :             let timeline_remote_consistent_lsn = timeline
     652            0 :                 .get_remote_consistent_lsn_visible()
     653            0 :                 .unwrap_or(Lsn(0));
     654            0 : 
     655            0 :             // The last LSN we processed. It is not guaranteed to survive pageserver crash.
     656            0 :             let last_received_lsn = last_lsn;
     657            0 :             // `disk_consistent_lsn` is the LSN at which page server guarantees local persistence of all received data
     658            0 :             let disk_consistent_lsn = timeline.get_disk_consistent_lsn();
     659            0 :             // The last LSN that is synced to remote storage and is guaranteed to survive pageserver crash
     660            0 :             // Used by safekeepers to remove WAL preceding `remote_consistent_lsn`.
     661            0 :             let remote_consistent_lsn = timeline_remote_consistent_lsn;
     662            0 :             let ts = SystemTime::now();
     663            0 : 
     664            0 :             // Update the status about what we just received. This is shown in the mgmt API.
     665            0 :             let last_received_wal = WalReceiverInfo {
     666            0 :                 wal_source_connconf: wal_source_connconf.clone(),
     667            0 :                 last_received_msg_lsn: last_lsn,
     668            0 :                 last_received_msg_ts: ts
     669            0 :                     .duration_since(SystemTime::UNIX_EPOCH)
     670            0 :                     .expect("Received message time should be before UNIX EPOCH!")
     671            0 :                     .as_micros(),
     672            0 :             };
     673            0 :             *timeline.last_received_wal.lock().unwrap() = Some(last_received_wal);
     674              : 
     675              :             // Send the replication feedback message.
     676              :             // Regular standby_status_update fields are put into this message.
     677            0 :             let current_timeline_size = if timeline.tenant_shard_id.is_shard_zero() {
     678            0 :                 timeline
     679            0 :                     .get_current_logical_size(
     680            0 :                         crate::tenant::timeline::GetLogicalSizePriority::User,
     681            0 :                         &ctx,
     682            0 :                     )
     683            0 :                     // FIXME: https://github.com/neondatabase/neon/issues/5963
     684            0 :                     .size_dont_care_about_accuracy()
     685              :             } else {
     686              :                 // Non-zero shards send zero for logical size.  The safekeeper will ignore
     687              :                 // this number.  This is because in a sharded tenant, only shard zero maintains
     688              :                 // accurate logical size.
     689            0 :                 0
     690              :             };
     691              : 
     692            0 :             let status_update = PageserverFeedback {
     693            0 :                 current_timeline_size,
     694            0 :                 last_received_lsn,
     695            0 :                 disk_consistent_lsn,
     696            0 :                 remote_consistent_lsn,
     697            0 :                 replytime: ts,
     698            0 :                 shard_number: timeline.tenant_shard_id.shard_number.0 as u32,
     699            0 :             };
     700            0 : 
     701            0 :             debug!("neon_status_update {status_update:?}");
     702              : 
     703            0 :             let mut data = BytesMut::new();
     704            0 :             status_update.serialize(&mut data);
     705            0 :             physical_stream
     706            0 :                 .as_mut()
     707            0 :                 .zenith_status_update(data.len() as u64, &data)
     708            0 :                 .await?;
     709            0 :         }
     710              :     }
     711              : 
     712            0 :     Ok(())
     713            0 : }
     714              : 
     715              : /// Data returned from the postgres `IDENTIFY_SYSTEM` command
     716              : ///
     717              : /// See the [postgres docs] for more details.
     718              : ///
     719              : /// [postgres docs]: https://www.postgresql.org/docs/current/protocol-replication.html
     720              : #[derive(Debug)]
     721              : // As of nightly 2021-09-11, fields that are only read by the type's `Debug` impl still count as
     722              : // unused. Relevant issue: https://github.com/rust-lang/rust/issues/88900
     723              : #[allow(dead_code)]
     724              : struct IdentifySystem {
     725              :     systemid: u64,
     726              :     timeline: u32,
     727              :     xlogpos: PgLsn,
     728              :     dbname: Option<String>,
     729              : }
     730              : 
     731              : /// There was a problem parsing the response to
     732              : /// a postgres IDENTIFY_SYSTEM command.
     733              : #[derive(Debug, thiserror::Error)]
     734              : #[error("IDENTIFY_SYSTEM parse error")]
     735              : struct IdentifyError;
     736              : 
     737              : /// Run the postgres `IDENTIFY_SYSTEM` command
     738            0 : async fn identify_system(client: &Client) -> anyhow::Result<IdentifySystem> {
     739            0 :     let query_str = "IDENTIFY_SYSTEM";
     740            0 :     let response = client.simple_query(query_str).await?;
     741              : 
     742              :     // get(N) from row, then parse it as some destination type.
     743            0 :     fn get_parse<T>(row: &SimpleQueryRow, idx: usize) -> Result<T, IdentifyError>
     744            0 :     where
     745            0 :         T: FromStr,
     746            0 :     {
     747            0 :         let val = row.get(idx).ok_or(IdentifyError)?;
     748            0 :         val.parse::<T>().or(Err(IdentifyError))
     749            0 :     }
     750              : 
     751              :     // extract the row contents into an IdentifySystem struct.
     752              :     // written as a closure so I can use ? for Option here.
     753            0 :     if let Some(SimpleQueryMessage::Row(first_row)) = response.first() {
     754              :         Ok(IdentifySystem {
     755            0 :             systemid: get_parse(first_row, 0)?,
     756            0 :             timeline: get_parse(first_row, 1)?,
     757            0 :             xlogpos: get_parse(first_row, 2)?,
     758            0 :             dbname: get_parse(first_row, 3).ok(),
     759              :         })
     760              :     } else {
     761            0 :         Err(IdentifyError.into())
     762              :     }
     763            0 : }
        

Generated by: LCOV version 2.1-beta