Line data Source code
1 : //! WAL receiver logic that ensures the pageserver gets connectected to safekeeper,
2 : //! that contains the latest WAL to stream and this connection does not go stale.
3 : //!
4 : //! To achieve that, a storage broker is used: safekepers propagate their timelines' state in it,
5 : //! the manager subscribes for changes and accumulates those to query the one with the biggest Lsn for connection.
6 : //! Current connection state is tracked too, to ensure it's not getting stale.
7 : //!
8 : //! After every connection or storage broker update fetched, the state gets updated correspondingly and rechecked for the new conneciton leader,
9 : //! then a (re)connection happens, if necessary.
10 : //! Only WAL streaming task expects to be finished, other loops (storage broker, connection management) never exit unless cancelled explicitly via the dedicated channel.
11 :
12 : use std::collections::HashMap;
13 : use std::num::NonZeroU64;
14 : use std::ops::ControlFlow;
15 : use std::sync::Arc;
16 : use std::time::Duration;
17 :
18 : use anyhow::Context;
19 : use chrono::{NaiveDateTime, Utc};
20 : use pageserver_api::models::TimelineState;
21 : use postgres_connection::PgConnectionConfig;
22 : use storage_broker::proto::{
23 : FilterTenantTimelineId, MessageType, SafekeeperDiscoveryRequest, SafekeeperDiscoveryResponse,
24 : SubscribeByFilterRequest, TenantTimelineId as ProtoTenantTimelineId, TypeSubscription,
25 : TypedMessage,
26 : };
27 : use storage_broker::{BrokerClientChannel, Code, Streaming};
28 : use tokio_util::sync::CancellationToken;
29 : use tracing::*;
30 : use utils::backoff::{
31 : DEFAULT_BASE_BACKOFF_SECONDS, DEFAULT_MAX_BACKOFF_SECONDS, exponential_backoff,
32 : };
33 : use utils::id::{NodeId, TenantTimelineId};
34 : use utils::lsn::Lsn;
35 : use utils::postgres_client::{ConnectionConfigArgs, wal_stream_connection_config};
36 :
37 : use super::walreceiver_connection::{WalConnectionStatus, WalReceiverError};
38 : use super::{TaskEvent, TaskHandle, TaskStateUpdate, WalReceiverConf};
39 : use crate::context::{DownloadBehavior, RequestContext};
40 : use crate::metrics::{
41 : WALRECEIVER_ACTIVE_MANAGERS, WALRECEIVER_BROKER_UPDATES, WALRECEIVER_CANDIDATES_ADDED,
42 : WALRECEIVER_CANDIDATES_REMOVED, WALRECEIVER_SWITCHES,
43 : };
44 : use crate::task_mgr::TaskKind;
45 : use crate::tenant::{Timeline, debug_assert_current_span_has_tenant_and_timeline_id};
46 :
47 : pub(crate) struct Cancelled;
48 :
49 : /// Attempts to subscribe for timeline updates, pushed by safekeepers into the broker.
50 : /// Based on the updates, desides whether to start, keep or stop a WAL receiver task.
51 : /// If storage broker subscription is cancelled, exits.
52 : ///
53 : /// # Cancel-Safety
54 : ///
55 : /// Not cancellation-safe. Use `cancel` token to request cancellation.
56 0 : pub(super) async fn connection_manager_loop_step(
57 0 : broker_client: &mut BrokerClientChannel,
58 0 : connection_manager_state: &mut ConnectionManagerState,
59 0 : ctx: &RequestContext,
60 0 : cancel: &CancellationToken,
61 0 : manager_status: &std::sync::RwLock<Option<ConnectionManagerStatus>>,
62 0 : ) -> Result<(), Cancelled> {
63 0 : match tokio::select! {
64 0 : _ = cancel.cancelled() => { return Err(Cancelled); },
65 0 : st = connection_manager_state.timeline.wait_to_become_active(ctx) => { st }
66 : } {
67 0 : Ok(()) => {}
68 0 : Err(new_state) => {
69 0 : debug!(
70 : ?new_state,
71 0 : "state changed, stopping wal connection manager loop"
72 : );
73 0 : return Err(Cancelled);
74 : }
75 : }
76 :
77 0 : WALRECEIVER_ACTIVE_MANAGERS.inc();
78 0 : scopeguard::defer! {
79 0 : WALRECEIVER_ACTIVE_MANAGERS.dec();
80 0 : }
81 0 :
82 0 : let id = TenantTimelineId {
83 0 : tenant_id: connection_manager_state.timeline.tenant_shard_id.tenant_id,
84 0 : timeline_id: connection_manager_state.timeline.timeline_id,
85 0 : };
86 0 :
87 0 : let mut timeline_state_updates = connection_manager_state
88 0 : .timeline
89 0 : .subscribe_for_state_updates();
90 0 :
91 0 : let mut wait_lsn_status = connection_manager_state
92 0 : .timeline
93 0 : .subscribe_for_wait_lsn_updates();
94 0 :
95 0 : // TODO: create a separate config option for discovery request interval
96 0 : let discovery_request_interval = connection_manager_state.conf.lagging_wal_timeout;
97 0 : let mut last_discovery_ts: Option<std::time::Instant> = None;
98 :
99 : // Subscribe to the broker updates. Stream shares underlying TCP connection
100 : // with other streams on this client (other connection managers). When
101 : // object goes out of scope, stream finishes in drop() automatically.
102 0 : let mut broker_subscription = subscribe_for_timeline_updates(broker_client, id, cancel).await?;
103 0 : debug!("Subscribed for broker timeline updates");
104 :
105 : loop {
106 0 : let time_until_next_retry = connection_manager_state.time_until_next_retry();
107 0 : let any_activity = connection_manager_state.wal_connection.is_some()
108 0 : || !connection_manager_state.wal_stream_candidates.is_empty();
109 :
110 : // These things are happening concurrently:
111 : //
112 : // - cancellation request
113 : // - keep receiving WAL on the current connection
114 : // - if the shared state says we need to change connection, disconnect and return
115 : // - this runs in a separate task and we receive updates via a watch channel
116 : // - change connection if the rules decide so, or if the current connection dies
117 : // - receive updates from broker
118 : // - this might change the current desired connection
119 : // - timeline state changes to something that does not allow walreceiver to run concurrently
120 : // - if there's no connection and no candidates, try to send a discovery request
121 :
122 : // NB: make sure each of the select expressions are cancellation-safe
123 : // (no need for arms to be cancellation-safe).
124 0 : tokio::select! {
125 0 : _ = cancel.cancelled() => { return Err(Cancelled); }
126 0 : Some(wal_connection_update) = async {
127 0 : match connection_manager_state.wal_connection.as_mut() {
128 0 : Some(wal_connection) => Some(wal_connection.connection_task.next_task_event().await),
129 0 : None => None,
130 : }
131 0 : } => {
132 0 : let wal_connection = connection_manager_state.wal_connection.as_mut()
133 0 : .expect("Should have a connection, as checked by the corresponding select! guard");
134 0 : match wal_connection_update {
135 0 : TaskEvent::Update(TaskStateUpdate::Started) => {},
136 0 : TaskEvent::Update(TaskStateUpdate::Progress(new_status)) => {
137 0 : if new_status.has_processed_wal {
138 0 : // We have advanced last_record_lsn by processing the WAL received
139 0 : // from this safekeeper. This is good enough to clean unsuccessful
140 0 : // retries history and allow reconnecting to this safekeeper without
141 0 : // sleeping for a long time.
142 0 : connection_manager_state.wal_connection_retries.remove(&wal_connection.sk_id);
143 0 : }
144 0 : wal_connection.status = new_status;
145 : }
146 0 : TaskEvent::End(walreceiver_task_result) => {
147 0 : match walreceiver_task_result {
148 0 : Ok(()) => debug!("WAL receiving task finished"),
149 0 : Err(e) => error!("wal receiver task finished with an error: {e:?}"),
150 : }
151 0 : connection_manager_state.drop_old_connection(false).await;
152 : },
153 : }
154 : },
155 :
156 : // Got a new update from the broker
157 0 : broker_update = broker_subscription.message() /* TODO: review cancellation-safety */ => {
158 0 : match broker_update {
159 0 : Ok(Some(broker_update)) => connection_manager_state.register_timeline_update(broker_update),
160 0 : Err(status) => {
161 0 : match status.code() {
162 0 : Code::Unknown if status.message().contains("stream closed because of a broken pipe") || status.message().contains("connection reset") || status.message().contains("error reading a body from connection") => {
163 0 : // tonic's error handling doesn't provide a clear code for disconnections: we get
164 0 : // "h2 protocol error: error reading a body from connection: stream closed because of a broken pipe"
165 0 : // => https://github.com/neondatabase/neon/issues/9562
166 0 : info!("broker disconnected: {status}");
167 : },
168 : _ => {
169 0 : warn!("broker subscription failed: {status}");
170 : }
171 : }
172 0 : return Ok(());
173 : }
174 : Ok(None) => {
175 0 : error!("broker subscription stream ended"); // can't happen
176 0 : return Ok(());
177 : }
178 : }
179 : },
180 :
181 0 : new_event = async {
182 : // Reminder: this match arm needs to be cancellation-safe.
183 : loop {
184 0 : if connection_manager_state.timeline.current_state() == TimelineState::Loading {
185 0 : warn!("wal connection manager should only be launched after timeline has become active");
186 0 : }
187 0 : match timeline_state_updates.changed().await {
188 : Ok(()) => {
189 0 : let new_state = connection_manager_state.timeline.current_state();
190 0 : match new_state {
191 : // we're already active as walreceiver, no need to reactivate
192 0 : TimelineState::Active => continue,
193 : TimelineState::Broken { .. } | TimelineState::Stopping => {
194 0 : debug!("timeline entered terminal state {new_state:?}, stopping wal connection manager loop");
195 0 : return ControlFlow::Break(());
196 : }
197 : TimelineState::Loading => {
198 0 : warn!("timeline transitioned back to Loading state, that should not happen");
199 0 : return ControlFlow::Continue(());
200 : }
201 : }
202 : }
203 0 : Err(_sender_dropped_error) => return ControlFlow::Break(()),
204 : }
205 : }
206 0 : } => match new_event {
207 : ControlFlow::Continue(()) => {
208 0 : return Ok(());
209 : }
210 : ControlFlow::Break(()) => {
211 0 : debug!("Timeline is no longer active, stopping wal connection manager loop");
212 0 : return Err(Cancelled);
213 : }
214 : },
215 :
216 0 : Some(()) = async {
217 0 : match time_until_next_retry {
218 0 : Some(sleep_time) => {
219 0 : tokio::time::sleep(sleep_time).await;
220 0 : Some(())
221 : },
222 : None => {
223 0 : debug!("No candidates to retry, waiting indefinitely for the broker events");
224 0 : None
225 : }
226 : }
227 0 : } => debug!("Waking up for the next retry after waiting for {time_until_next_retry:?}"),
228 :
229 0 : Some(()) = async {
230 0 : // Reminder: this match arm needs to be cancellation-safe.
231 0 : // Calculating time needed to wait until sending the next discovery request.
232 0 : // Current implementation is conservative and sends discovery requests only when there are no candidates.
233 0 :
234 0 : if any_activity {
235 : // No need to send discovery requests if there is an active connection or candidates.
236 0 : return None;
237 0 : }
238 :
239 : // Waiting for an active wait_lsn request.
240 0 : while wait_lsn_status.borrow().is_none() {
241 0 : if wait_lsn_status.changed().await.is_err() {
242 : // wait_lsn_status channel was closed, exiting
243 0 : warn!("wait_lsn_status channel was closed in connection_manager_loop_step");
244 0 : return None;
245 0 : }
246 : }
247 :
248 : // All preconditions met, preparing to send a discovery request.
249 0 : let now = std::time::Instant::now();
250 0 : let next_discovery_ts = last_discovery_ts
251 0 : .map(|ts| ts + discovery_request_interval)
252 0 : .unwrap_or_else(|| now);
253 0 :
254 0 : if next_discovery_ts > now {
255 : // Prevent sending discovery requests too frequently.
256 0 : tokio::time::sleep(next_discovery_ts - now).await;
257 0 : }
258 :
259 0 : let tenant_timeline_id = Some(ProtoTenantTimelineId {
260 0 : tenant_id: id.tenant_id.as_ref().to_owned(),
261 0 : timeline_id: id.timeline_id.as_ref().to_owned(),
262 0 : });
263 0 : let request = SafekeeperDiscoveryRequest { tenant_timeline_id };
264 0 : let msg = TypedMessage {
265 0 : r#type: MessageType::SafekeeperDiscoveryRequest as i32,
266 0 : safekeeper_timeline_info: None,
267 0 : safekeeper_discovery_request: Some(request),
268 0 : safekeeper_discovery_response: None,
269 0 : };
270 0 :
271 0 : last_discovery_ts = Some(std::time::Instant::now());
272 0 : info!("No active connection and no candidates, sending discovery request to the broker");
273 :
274 : // Cancellation safety: we want to send a message to the broker, but publish_one()
275 : // function can get cancelled by the other select! arm. This is absolutely fine, because
276 : // we just want to receive broker updates and discovery is not important if we already
277 : // receive updates.
278 : //
279 : // It is possible that `last_discovery_ts` will be updated, but the message will not be sent.
280 : // This is totally fine because of the reason above.
281 :
282 : // This is a fire-and-forget request, we don't care about the response
283 0 : let _ = broker_client.publish_one(msg).await;
284 0 : debug!("Discovery request sent to the broker");
285 0 : None
286 0 : } => {}
287 : }
288 :
289 0 : if let Some(new_candidate) = connection_manager_state.next_connection_candidate() {
290 0 : info!("Switching to new connection candidate: {new_candidate:?}");
291 0 : connection_manager_state
292 0 : .change_connection(new_candidate, ctx)
293 0 : .await
294 0 : }
295 0 : *manager_status.write().unwrap() = Some(connection_manager_state.manager_status());
296 : }
297 0 : }
298 :
299 : /// Endlessly try to subscribe for broker updates for a given timeline.
300 0 : async fn subscribe_for_timeline_updates(
301 0 : broker_client: &mut BrokerClientChannel,
302 0 : id: TenantTimelineId,
303 0 : cancel: &CancellationToken,
304 0 : ) -> Result<Streaming<TypedMessage>, Cancelled> {
305 0 : let mut attempt = 0;
306 : loop {
307 0 : exponential_backoff(
308 0 : attempt,
309 0 : DEFAULT_BASE_BACKOFF_SECONDS,
310 0 : DEFAULT_MAX_BACKOFF_SECONDS,
311 0 : cancel,
312 0 : )
313 0 : .await;
314 0 : attempt += 1;
315 0 :
316 0 : // subscribe to the specific timeline
317 0 : let request = SubscribeByFilterRequest {
318 0 : types: vec![
319 0 : TypeSubscription {
320 0 : r#type: MessageType::SafekeeperTimelineInfo as i32,
321 0 : },
322 0 : TypeSubscription {
323 0 : r#type: MessageType::SafekeeperDiscoveryResponse as i32,
324 0 : },
325 0 : ],
326 0 : tenant_timeline_id: Some(FilterTenantTimelineId {
327 0 : enabled: true,
328 0 : tenant_timeline_id: Some(ProtoTenantTimelineId {
329 0 : tenant_id: id.tenant_id.as_ref().to_owned(),
330 0 : timeline_id: id.timeline_id.as_ref().to_owned(),
331 0 : }),
332 0 : }),
333 0 : };
334 0 :
335 0 : match {
336 0 : tokio::select! {
337 0 : r = broker_client.subscribe_by_filter(request) => { r }
338 0 : _ = cancel.cancelled() => { return Err(Cancelled); }
339 : }
340 : } {
341 0 : Ok(resp) => {
342 0 : return Ok(resp.into_inner());
343 : }
344 0 : Err(e) => {
345 0 : // Safekeeper nodes can stop pushing timeline updates to the broker, when no new writes happen and
346 0 : // entire WAL is streamed. Keep this noticeable with logging, but do not warn/error.
347 0 : info!(
348 0 : "Attempt #{attempt}, failed to subscribe for timeline {id} updates in broker: {e:#}"
349 : );
350 0 : continue;
351 : }
352 : }
353 : }
354 0 : }
355 :
356 : const WALCONNECTION_RETRY_MIN_BACKOFF_SECONDS: f64 = 0.1;
357 : const WALCONNECTION_RETRY_MAX_BACKOFF_SECONDS: f64 = 15.0;
358 : const WALCONNECTION_RETRY_BACKOFF_MULTIPLIER: f64 = 1.5;
359 :
360 : /// All data that's needed to run endless broker loop and keep the WAL streaming connection alive, if possible.
361 : pub(super) struct ConnectionManagerState {
362 : id: TenantTimelineId,
363 : /// Use pageserver data about the timeline to filter out some of the safekeepers.
364 : timeline: Arc<Timeline>,
365 : /// Child token of [`super::WalReceiver::cancel`], inherited to all tasks we spawn.
366 : cancel: CancellationToken,
367 : conf: WalReceiverConf,
368 : /// Current connection to safekeeper for WAL streaming.
369 : wal_connection: Option<WalConnection>,
370 : /// Info about retries and unsuccessful attempts to connect to safekeepers.
371 : wal_connection_retries: HashMap<NodeId, RetryInfo>,
372 : /// Data about all timelines, available for connection, fetched from storage broker, grouped by their corresponding safekeeper node id.
373 : wal_stream_candidates: HashMap<NodeId, BrokerSkTimeline>,
374 : }
375 :
376 : /// An information about connection manager's current connection and connection candidates.
377 : #[derive(Debug, Clone)]
378 : pub struct ConnectionManagerStatus {
379 : existing_connection: Option<WalConnectionStatus>,
380 : wal_stream_candidates: HashMap<NodeId, BrokerSkTimeline>,
381 : }
382 :
383 : impl ConnectionManagerStatus {
384 : /// Generates a string, describing current connection status in a form, suitable for logging.
385 0 : pub fn to_human_readable_string(&self) -> String {
386 0 : let mut resulting_string = String::new();
387 0 : match &self.existing_connection {
388 0 : Some(connection) => {
389 0 : if connection.has_processed_wal {
390 0 : resulting_string.push_str(&format!(
391 0 : " (update {}): streaming WAL from node {}, ",
392 0 : connection.latest_wal_update.format("%Y-%m-%d %H:%M:%S"),
393 0 : connection.node,
394 0 : ));
395 0 :
396 0 : match (connection.streaming_lsn, connection.commit_lsn) {
397 0 : (None, None) => resulting_string.push_str("no streaming data"),
398 0 : (None, Some(commit_lsn)) => {
399 0 : resulting_string.push_str(&format!("commit Lsn: {commit_lsn}"))
400 : }
401 0 : (Some(streaming_lsn), None) => {
402 0 : resulting_string.push_str(&format!("streaming Lsn: {streaming_lsn}"))
403 : }
404 0 : (Some(streaming_lsn), Some(commit_lsn)) => resulting_string.push_str(
405 0 : &format!("commit|streaming Lsn: {commit_lsn}|{streaming_lsn}"),
406 0 : ),
407 : }
408 0 : } else if connection.is_connected {
409 0 : resulting_string.push_str(&format!(
410 0 : " (update {}): connecting to node {}",
411 0 : connection
412 0 : .latest_connection_update
413 0 : .format("%Y-%m-%d %H:%M:%S"),
414 0 : connection.node,
415 0 : ));
416 0 : } else {
417 0 : resulting_string.push_str(&format!(
418 0 : " (update {}): initializing node {} connection",
419 0 : connection
420 0 : .latest_connection_update
421 0 : .format("%Y-%m-%d %H:%M:%S"),
422 0 : connection.node,
423 0 : ));
424 0 : }
425 : }
426 0 : None => resulting_string.push_str(": disconnected"),
427 : }
428 :
429 0 : resulting_string.push_str(", safekeeper candidates (id|update_time|commit_lsn): [");
430 0 : let mut candidates = self.wal_stream_candidates.iter().peekable();
431 0 : while let Some((node_id, candidate_info)) = candidates.next() {
432 0 : resulting_string.push_str(&format!(
433 0 : "({}|{}|{})",
434 0 : node_id,
435 0 : candidate_info.latest_update.format("%H:%M:%S"),
436 0 : Lsn(candidate_info.timeline.commit_lsn)
437 0 : ));
438 0 : if candidates.peek().is_some() {
439 0 : resulting_string.push_str(", ");
440 0 : }
441 : }
442 0 : resulting_string.push(']');
443 0 :
444 0 : resulting_string
445 0 : }
446 : }
447 :
448 : /// Current connection data.
449 : #[derive(Debug)]
450 : struct WalConnection {
451 : /// Time when the connection was initiated.
452 : started_at: NaiveDateTime,
453 : /// Current safekeeper pageserver is connected to for WAL streaming.
454 : sk_id: NodeId,
455 : /// Availability zone of the safekeeper.
456 : availability_zone: Option<String>,
457 : /// Status of the connection.
458 : status: WalConnectionStatus,
459 : /// WAL streaming task handle.
460 : connection_task: TaskHandle<WalConnectionStatus>,
461 : /// Have we discovered that other safekeeper has more recent WAL than we do?
462 : discovered_new_wal: Option<NewCommittedWAL>,
463 : }
464 :
465 : /// Notion of a new committed WAL, which exists on other safekeeper.
466 : #[derive(Debug, Clone, Copy)]
467 : struct NewCommittedWAL {
468 : /// LSN of the new committed WAL.
469 : lsn: Lsn,
470 : /// When we discovered that the new committed WAL exists on other safekeeper.
471 : discovered_at: NaiveDateTime,
472 : }
473 :
474 : #[derive(Debug, Clone, Copy)]
475 : struct RetryInfo {
476 : next_retry_at: Option<NaiveDateTime>,
477 : retry_duration_seconds: f64,
478 : }
479 :
480 : /// Data about the timeline to connect to, received from the broker.
481 : #[derive(Debug, Clone)]
482 : struct BrokerSkTimeline {
483 : timeline: SafekeeperDiscoveryResponse,
484 : /// Time at which the data was fetched from the broker last time, to track the stale data.
485 : latest_update: NaiveDateTime,
486 : }
487 :
488 : impl ConnectionManagerState {
489 0 : pub(super) fn new(
490 0 : timeline: Arc<Timeline>,
491 0 : conf: WalReceiverConf,
492 0 : cancel: CancellationToken,
493 0 : ) -> Self {
494 0 : let id = TenantTimelineId {
495 0 : tenant_id: timeline.tenant_shard_id.tenant_id,
496 0 : timeline_id: timeline.timeline_id,
497 0 : };
498 0 : Self {
499 0 : id,
500 0 : timeline,
501 0 : cancel,
502 0 : conf,
503 0 : wal_connection: None,
504 0 : wal_stream_candidates: HashMap::new(),
505 0 : wal_connection_retries: HashMap::new(),
506 0 : }
507 0 : }
508 :
509 5 : fn spawn<Fut>(
510 5 : &self,
511 5 : task: impl FnOnce(
512 5 : tokio::sync::watch::Sender<TaskStateUpdate<WalConnectionStatus>>,
513 5 : CancellationToken,
514 5 : ) -> Fut
515 5 : + Send
516 5 : + 'static,
517 5 : ) -> TaskHandle<WalConnectionStatus>
518 5 : where
519 5 : Fut: std::future::Future<Output = anyhow::Result<()>> + Send,
520 5 : {
521 5 : // TODO: get rid of TaskHandle
522 5 : super::TaskHandle::spawn(&self.cancel, task)
523 5 : }
524 :
525 : /// Shuts down the current connection (if any) and immediately starts another one with the given connection string.
526 0 : async fn change_connection(&mut self, new_sk: NewWalConnectionCandidate, ctx: &RequestContext) {
527 0 : WALRECEIVER_SWITCHES
528 0 : .with_label_values(&[new_sk.reason.name()])
529 0 : .inc();
530 0 :
531 0 : self.drop_old_connection(true).await;
532 :
533 0 : let node_id = new_sk.safekeeper_id;
534 0 : let connect_timeout = self.conf.wal_connect_timeout;
535 0 : let ingest_batch_size = self.conf.ingest_batch_size;
536 0 : let protocol = self.conf.protocol;
537 0 : let validate_wal_contiguity = self.conf.validate_wal_contiguity;
538 0 : let timeline = Arc::clone(&self.timeline);
539 0 : let ctx = ctx.detached_child(
540 0 : TaskKind::WalReceiverConnectionHandler,
541 0 : DownloadBehavior::Download,
542 0 : );
543 :
544 0 : let span = info_span!("connection", %node_id);
545 0 : let connection_handle = self.spawn(move |events_sender, cancellation| {
546 0 : async move {
547 0 : debug_assert_current_span_has_tenant_and_timeline_id();
548 :
549 0 : let res = super::walreceiver_connection::handle_walreceiver_connection(
550 0 : timeline,
551 0 : protocol,
552 0 : new_sk.wal_source_connconf,
553 0 : events_sender,
554 0 : cancellation.clone(),
555 0 : connect_timeout,
556 0 : ctx,
557 0 : node_id,
558 0 : ingest_batch_size,
559 0 : validate_wal_contiguity,
560 0 : )
561 0 : .await;
562 :
563 0 : match res {
564 0 : Ok(()) => Ok(()),
565 0 : Err(e) => {
566 0 : match e {
567 0 : WalReceiverError::SuccessfulCompletion(msg) => {
568 0 : info!("walreceiver connection handling ended with success: {msg}");
569 0 : Ok(())
570 : }
571 0 : WalReceiverError::ExpectedSafekeeperError(e) => {
572 0 : info!("walreceiver connection handling ended: {e}");
573 0 : Ok(())
574 : }
575 : WalReceiverError::ClosedGate => {
576 0 : info!(
577 0 : "walreceiver connection handling ended because of closed gate"
578 : );
579 0 : Ok(())
580 : }
581 0 : WalReceiverError::Cancelled => Ok(()),
582 0 : WalReceiverError::Other(e) => {
583 0 : // give out an error to have task_mgr give it a really verbose logging
584 0 : if cancellation.is_cancelled() {
585 : // Ideally we would learn about this via some path other than Other, but
586 : // that requires refactoring all the intermediate layers of ingest code
587 : // that only emit anyhow::Error
588 0 : Ok(())
589 : } else {
590 0 : Err(e).context("walreceiver connection handling failure")
591 : }
592 : }
593 : }
594 : }
595 : }
596 0 : }
597 0 : .instrument(span)
598 0 : });
599 0 :
600 0 : let now = Utc::now().naive_utc();
601 0 : self.wal_connection = Some(WalConnection {
602 0 : started_at: now,
603 0 : sk_id: new_sk.safekeeper_id,
604 0 : availability_zone: new_sk.availability_zone,
605 0 : status: WalConnectionStatus {
606 0 : is_connected: false,
607 0 : has_processed_wal: false,
608 0 : latest_connection_update: now,
609 0 : latest_wal_update: now,
610 0 : streaming_lsn: None,
611 0 : commit_lsn: None,
612 0 : node: node_id,
613 0 : },
614 0 : connection_task: connection_handle,
615 0 : discovered_new_wal: None,
616 0 : });
617 0 : }
618 :
619 : /// Drops the current connection (if any) and updates retry timeout for the next
620 : /// connection attempt to the same safekeeper.
621 : ///
622 : /// # Cancel-Safety
623 : ///
624 : /// Not cancellation-safe.
625 0 : async fn drop_old_connection(&mut self, needs_shutdown: bool) {
626 0 : let wal_connection = match self.wal_connection.take() {
627 0 : Some(wal_connection) => wal_connection,
628 0 : None => return,
629 : };
630 :
631 0 : if needs_shutdown {
632 0 : wal_connection
633 0 : .connection_task
634 0 : .shutdown()
635 0 : // This here is why this function isn't cancellation-safe.
636 0 : // If we got cancelled here, then self.wal_connection is already None and we lose track of the task.
637 0 : // Even if our caller diligently calls Self::shutdown(), it will find a self.wal_connection=None
638 0 : // and thus be ineffective.
639 0 : .await;
640 0 : }
641 :
642 0 : let retry = self
643 0 : .wal_connection_retries
644 0 : .entry(wal_connection.sk_id)
645 0 : .or_insert(RetryInfo {
646 0 : next_retry_at: None,
647 0 : retry_duration_seconds: WALCONNECTION_RETRY_MIN_BACKOFF_SECONDS,
648 0 : });
649 0 :
650 0 : let now = Utc::now().naive_utc();
651 0 :
652 0 : // Schedule the next retry attempt. We want to have exponential backoff for connection attempts,
653 0 : // and we add backoff to the time when we started the connection attempt. If the connection
654 0 : // was active for a long time, then next_retry_at will be in the past.
655 0 : retry.next_retry_at =
656 0 : wal_connection
657 0 : .started_at
658 0 : .checked_add_signed(chrono::Duration::milliseconds(
659 0 : (retry.retry_duration_seconds * 1000.0) as i64,
660 0 : ));
661 :
662 0 : if let Some(next) = &retry.next_retry_at {
663 0 : if next > &now {
664 0 : info!(
665 0 : "Next connection retry to {:?} is at {}",
666 : wal_connection.sk_id, next
667 : );
668 0 : }
669 0 : }
670 :
671 0 : let next_retry_duration =
672 0 : retry.retry_duration_seconds * WALCONNECTION_RETRY_BACKOFF_MULTIPLIER;
673 0 : // Clamp the next retry duration to the maximum allowed.
674 0 : let next_retry_duration = next_retry_duration.min(WALCONNECTION_RETRY_MAX_BACKOFF_SECONDS);
675 0 : // Clamp the next retry duration to the minimum allowed.
676 0 : let next_retry_duration = next_retry_duration.max(WALCONNECTION_RETRY_MIN_BACKOFF_SECONDS);
677 0 :
678 0 : retry.retry_duration_seconds = next_retry_duration;
679 0 : }
680 :
681 : /// Returns time needed to wait to have a new candidate for WAL streaming.
682 0 : fn time_until_next_retry(&self) -> Option<Duration> {
683 0 : let now = Utc::now().naive_utc();
684 :
685 0 : let next_retry_at = self
686 0 : .wal_connection_retries
687 0 : .values()
688 0 : .filter_map(|retry| retry.next_retry_at)
689 0 : .filter(|next_retry_at| next_retry_at > &now)
690 0 : .min()?;
691 :
692 0 : (next_retry_at - now).to_std().ok()
693 0 : }
694 :
695 : /// Adds another broker timeline into the state, if its more recent than the one already added there for the same key.
696 0 : fn register_timeline_update(&mut self, typed_msg: TypedMessage) {
697 0 : let mut is_discovery = false;
698 0 : let timeline_update = match typed_msg.r#type() {
699 : MessageType::SafekeeperTimelineInfo => {
700 0 : let info = match typed_msg.safekeeper_timeline_info {
701 0 : Some(info) => info,
702 : None => {
703 0 : warn!("bad proto message from broker: no safekeeper_timeline_info");
704 0 : return;
705 : }
706 : };
707 0 : SafekeeperDiscoveryResponse {
708 0 : safekeeper_id: info.safekeeper_id,
709 0 : tenant_timeline_id: info.tenant_timeline_id,
710 0 : commit_lsn: info.commit_lsn,
711 0 : safekeeper_connstr: info.safekeeper_connstr,
712 0 : availability_zone: info.availability_zone,
713 0 : standby_horizon: info.standby_horizon,
714 0 : }
715 : }
716 : MessageType::SafekeeperDiscoveryResponse => {
717 0 : is_discovery = true;
718 0 : match typed_msg.safekeeper_discovery_response {
719 0 : Some(response) => response,
720 : None => {
721 0 : warn!("bad proto message from broker: no safekeeper_discovery_response");
722 0 : return;
723 : }
724 : }
725 : }
726 : _ => {
727 : // unexpected message
728 0 : return;
729 : }
730 : };
731 :
732 0 : WALRECEIVER_BROKER_UPDATES.inc();
733 0 :
734 0 : trace!(
735 0 : "safekeeper info update: standby_horizon(cutoff)={}",
736 : timeline_update.standby_horizon
737 : );
738 0 : if timeline_update.standby_horizon != 0 {
739 0 : // ignore reports from safekeepers not connected to replicas
740 0 : self.timeline
741 0 : .standby_horizon
742 0 : .store(Lsn(timeline_update.standby_horizon));
743 0 : self.timeline
744 0 : .metrics
745 0 : .standby_horizon_gauge
746 0 : .set(timeline_update.standby_horizon as i64);
747 0 : }
748 :
749 0 : let new_safekeeper_id = NodeId(timeline_update.safekeeper_id);
750 0 : let old_entry = self.wal_stream_candidates.insert(
751 0 : new_safekeeper_id,
752 0 : BrokerSkTimeline {
753 0 : timeline: timeline_update,
754 0 : latest_update: Utc::now().naive_utc(),
755 0 : },
756 0 : );
757 0 :
758 0 : if old_entry.is_none() {
759 0 : info!(
760 : ?is_discovery,
761 : %new_safekeeper_id,
762 0 : "New SK node was added",
763 : );
764 0 : WALRECEIVER_CANDIDATES_ADDED.inc();
765 0 : }
766 0 : }
767 :
768 : /// Cleans up stale broker records and checks the rest for the new connection candidate.
769 : /// Returns a new candidate, if the current state is absent or somewhat lagging, `None` otherwise.
770 : /// The current rules for approving new candidates:
771 : /// * pick a candidate different from the connected safekeeper with biggest `commit_lsn` and lowest failed connection attemps
772 : /// * if there's no such entry, no new candidate found, abort
773 : /// * otherwise check if the candidate is much better than the current one
774 : ///
775 : /// To understand exact rules for determining if the candidate is better than the current one, refer to this function's implementation.
776 : /// General rules are following:
777 : /// * if connected safekeeper is not present, pick the candidate
778 : /// * if we haven't received any updates for some time, pick the candidate
779 : /// * if the candidate commit_lsn is much higher than the current one, pick the candidate
780 : /// * if the candidate commit_lsn is same, but candidate is located in the same AZ as the pageserver, pick the candidate
781 : /// * if connected safekeeper stopped sending us new WAL which is available on other safekeeper, pick the candidate
782 : ///
783 : /// This way we ensure to keep up with the most up-to-date safekeeper and don't try to jump from one safekeeper to another too frequently.
784 : /// Both thresholds are configured per tenant.
785 9 : fn next_connection_candidate(&mut self) -> Option<NewWalConnectionCandidate> {
786 9 : self.cleanup_old_candidates();
787 9 :
788 9 : match &self.wal_connection {
789 5 : Some(existing_wal_connection) => {
790 5 : let connected_sk_node = existing_wal_connection.sk_id;
791 :
792 5 : let (new_sk_id, new_safekeeper_broker_data, new_wal_source_connconf) =
793 5 : self.select_connection_candidate(Some(connected_sk_node))?;
794 5 : let new_availability_zone = new_safekeeper_broker_data.availability_zone.clone();
795 5 :
796 5 : let now = Utc::now().naive_utc();
797 5 : if let Ok(latest_interaciton) =
798 5 : (now - existing_wal_connection.status.latest_connection_update).to_std()
799 : {
800 : // Drop connection if we haven't received keepalive message for a while.
801 5 : if latest_interaciton > self.conf.wal_connect_timeout {
802 1 : return Some(NewWalConnectionCandidate {
803 1 : safekeeper_id: new_sk_id,
804 1 : wal_source_connconf: new_wal_source_connconf,
805 1 : availability_zone: new_availability_zone,
806 1 : reason: ReconnectReason::NoKeepAlives {
807 1 : last_keep_alive: Some(
808 1 : existing_wal_connection.status.latest_connection_update,
809 1 : ),
810 1 : check_time: now,
811 1 : threshold: self.conf.wal_connect_timeout,
812 1 : },
813 1 : });
814 4 : }
815 0 : }
816 :
817 4 : if !existing_wal_connection.status.is_connected {
818 : // We haven't connected yet and we shouldn't switch until connection timeout (condition above).
819 0 : return None;
820 4 : }
821 :
822 4 : if let Some(current_commit_lsn) = existing_wal_connection.status.commit_lsn {
823 4 : let new_commit_lsn = Lsn(new_safekeeper_broker_data.commit_lsn);
824 4 : // Check if the new candidate has much more WAL than the current one.
825 4 : match new_commit_lsn.0.checked_sub(current_commit_lsn.0) {
826 4 : Some(new_sk_lsn_advantage) => {
827 4 : if new_sk_lsn_advantage >= self.conf.max_lsn_wal_lag.get() {
828 1 : return Some(NewWalConnectionCandidate {
829 1 : safekeeper_id: new_sk_id,
830 1 : wal_source_connconf: new_wal_source_connconf,
831 1 : availability_zone: new_availability_zone,
832 1 : reason: ReconnectReason::LaggingWal {
833 1 : current_commit_lsn,
834 1 : new_commit_lsn,
835 1 : threshold: self.conf.max_lsn_wal_lag,
836 1 : },
837 1 : });
838 3 : }
839 3 : // If we have a candidate with the same commit_lsn as the current one, which is in the same AZ as pageserver,
840 3 : // and the current one is not, switch to the new one.
841 3 : if self.conf.availability_zone.is_some()
842 1 : && existing_wal_connection.availability_zone
843 1 : != self.conf.availability_zone
844 1 : && self.conf.availability_zone == new_availability_zone
845 : {
846 1 : return Some(NewWalConnectionCandidate {
847 1 : safekeeper_id: new_sk_id,
848 1 : availability_zone: new_availability_zone,
849 1 : wal_source_connconf: new_wal_source_connconf,
850 1 : reason: ReconnectReason::SwitchAvailabilityZone,
851 1 : });
852 2 : }
853 : }
854 0 : None => debug!(
855 0 : "Best SK candidate has its commit_lsn behind connected SK's commit_lsn"
856 : ),
857 : }
858 0 : }
859 :
860 2 : let current_lsn = match existing_wal_connection.status.streaming_lsn {
861 2 : Some(lsn) => lsn,
862 0 : None => self.timeline.get_last_record_lsn(),
863 : };
864 2 : let current_commit_lsn = existing_wal_connection
865 2 : .status
866 2 : .commit_lsn
867 2 : .unwrap_or(current_lsn);
868 2 : let candidate_commit_lsn = Lsn(new_safekeeper_broker_data.commit_lsn);
869 2 :
870 2 : // Keep discovered_new_wal only if connected safekeeper has not caught up yet.
871 2 : let mut discovered_new_wal = existing_wal_connection
872 2 : .discovered_new_wal
873 2 : .filter(|new_wal| new_wal.lsn > current_commit_lsn);
874 2 :
875 2 : if discovered_new_wal.is_none() {
876 : // Check if the new candidate has more WAL than the current one.
877 : // If the new candidate has more WAL than the current one, we consider switching to the new candidate.
878 1 : discovered_new_wal = if candidate_commit_lsn > current_commit_lsn {
879 1 : trace!(
880 0 : "New candidate has commit_lsn {}, higher than current_commit_lsn {}",
881 : candidate_commit_lsn, current_commit_lsn
882 : );
883 1 : Some(NewCommittedWAL {
884 1 : lsn: candidate_commit_lsn,
885 1 : discovered_at: Utc::now().naive_utc(),
886 1 : })
887 : } else {
888 0 : None
889 : };
890 1 : }
891 :
892 2 : let waiting_for_new_lsn_since = if current_lsn < current_commit_lsn {
893 : // Connected safekeeper has more WAL, but we haven't received updates for some time.
894 0 : trace!(
895 0 : "Connected safekeeper has more WAL, but we haven't received updates for {:?}. current_lsn: {}, current_commit_lsn: {}",
896 0 : (now - existing_wal_connection.status.latest_wal_update).to_std(),
897 : current_lsn,
898 : current_commit_lsn
899 : );
900 0 : Some(existing_wal_connection.status.latest_wal_update)
901 : } else {
902 2 : discovered_new_wal.as_ref().map(|new_wal| {
903 2 : // We know that new WAL is available on other safekeeper, but connected safekeeper don't have it.
904 2 : new_wal
905 2 : .discovered_at
906 2 : .max(existing_wal_connection.status.latest_wal_update)
907 2 : })
908 : };
909 :
910 : // If we haven't received any WAL updates for a while and candidate has more WAL, switch to it.
911 2 : if let Some(waiting_for_new_lsn_since) = waiting_for_new_lsn_since {
912 2 : if let Ok(waiting_for_new_wal) = (now - waiting_for_new_lsn_since).to_std() {
913 1 : if candidate_commit_lsn > current_commit_lsn
914 1 : && waiting_for_new_wal > self.conf.lagging_wal_timeout
915 : {
916 1 : return Some(NewWalConnectionCandidate {
917 1 : safekeeper_id: new_sk_id,
918 1 : wal_source_connconf: new_wal_source_connconf,
919 1 : availability_zone: new_availability_zone,
920 1 : reason: ReconnectReason::NoWalTimeout {
921 1 : current_lsn,
922 1 : current_commit_lsn,
923 1 : candidate_commit_lsn,
924 1 : last_wal_interaction: Some(
925 1 : existing_wal_connection.status.latest_wal_update,
926 1 : ),
927 1 : check_time: now,
928 1 : threshold: self.conf.lagging_wal_timeout,
929 1 : },
930 1 : });
931 0 : }
932 1 : }
933 0 : }
934 :
935 1 : self.wal_connection.as_mut().unwrap().discovered_new_wal = discovered_new_wal;
936 : }
937 : None => {
938 3 : let (new_sk_id, new_safekeeper_broker_data, new_wal_source_connconf) =
939 4 : self.select_connection_candidate(None)?;
940 3 : return Some(NewWalConnectionCandidate {
941 3 : safekeeper_id: new_sk_id,
942 3 : availability_zone: new_safekeeper_broker_data.availability_zone.clone(),
943 3 : wal_source_connconf: new_wal_source_connconf,
944 3 : reason: ReconnectReason::NoExistingConnection,
945 3 : });
946 : }
947 : }
948 :
949 1 : None
950 9 : }
951 :
952 : /// Selects the best possible candidate, based on the data collected from the broker updates about the safekeepers.
953 : /// Optionally, omits the given node, to support gracefully switching from a healthy safekeeper to another.
954 : ///
955 : /// The candidate that is chosen:
956 : /// * has no pending retry cooldown
957 : /// * has greatest commit_lsn among the ones that are left
958 9 : fn select_connection_candidate(
959 9 : &self,
960 9 : node_to_omit: Option<NodeId>,
961 9 : ) -> Option<(NodeId, &SafekeeperDiscoveryResponse, PgConnectionConfig)> {
962 9 : self.applicable_connection_candidates()
963 13 : .filter(|&(sk_id, _, _)| Some(sk_id) != node_to_omit)
964 10 : .max_by_key(|(_, info, _)| info.commit_lsn)
965 9 : }
966 :
967 : /// Returns a list of safekeepers that have valid info and ready for connection.
968 : /// Some safekeepers are filtered by the retry cooldown.
969 9 : fn applicable_connection_candidates(
970 9 : &self,
971 9 : ) -> impl Iterator<Item = (NodeId, &SafekeeperDiscoveryResponse, PgConnectionConfig)> {
972 9 : let now = Utc::now().naive_utc();
973 9 :
974 9 : self.wal_stream_candidates
975 9 : .iter()
976 18 : .filter(|(_, info)| Lsn(info.timeline.commit_lsn) != Lsn::INVALID)
977 16 : .filter(move |(sk_id, _)| {
978 16 : let next_retry_at = self
979 16 : .wal_connection_retries
980 16 : .get(sk_id)
981 16 : .and_then(|retry_info| {
982 1 : retry_info.next_retry_at
983 16 : });
984 16 :
985 16 : next_retry_at.is_none() || next_retry_at.unwrap() <= now
986 16 : }).filter_map(|(sk_id, broker_info)| {
987 15 : let info = &broker_info.timeline;
988 15 : if info.safekeeper_connstr.is_empty() {
989 2 : return None; // no connection string, ignore sk
990 13 : }
991 13 :
992 13 : let shard_identity = self.timeline.get_shard_identity();
993 13 : let (shard_number, shard_count, shard_stripe_size) = (
994 13 : Some(shard_identity.number.0),
995 13 : Some(shard_identity.count.0),
996 13 : Some(shard_identity.stripe_size.0),
997 13 : );
998 13 :
999 13 : let connection_conf_args = ConnectionConfigArgs {
1000 13 : protocol: self.conf.protocol,
1001 13 : ttid: self.id,
1002 13 : shard_number,
1003 13 : shard_count,
1004 13 : shard_stripe_size,
1005 13 : listen_pg_addr_str: info.safekeeper_connstr.as_ref(),
1006 13 : auth_token: self.conf.auth_token.as_ref().map(|t| t.as_str()),
1007 13 : availability_zone: self.conf.availability_zone.as_deref()
1008 13 : };
1009 13 :
1010 13 : match wal_stream_connection_config(connection_conf_args) {
1011 13 : Ok(connstr) => Some((*sk_id, info, connstr)),
1012 0 : Err(e) => {
1013 0 : error!("Failed to create wal receiver connection string from broker data of safekeeper node {}: {e:#}", sk_id);
1014 0 : None
1015 : }
1016 : }
1017 15 : })
1018 9 : }
1019 :
1020 : /// Remove candidates which haven't sent broker updates for a while.
1021 9 : fn cleanup_old_candidates(&mut self) {
1022 9 : let mut node_ids_to_remove = Vec::with_capacity(self.wal_stream_candidates.len());
1023 9 : let lagging_wal_timeout = self.conf.lagging_wal_timeout;
1024 9 :
1025 19 : self.wal_stream_candidates.retain(|node_id, broker_info| {
1026 19 : if let Ok(time_since_latest_broker_update) =
1027 19 : (Utc::now().naive_utc() - broker_info.latest_update).to_std()
1028 : {
1029 19 : let should_retain = time_since_latest_broker_update < lagging_wal_timeout;
1030 19 : if !should_retain {
1031 1 : node_ids_to_remove.push(*node_id);
1032 18 : }
1033 19 : should_retain
1034 : } else {
1035 0 : true
1036 : }
1037 19 : });
1038 9 :
1039 9 : if !node_ids_to_remove.is_empty() {
1040 2 : for node_id in node_ids_to_remove {
1041 1 : info!(
1042 0 : "Safekeeper node {node_id} did not send events for over {lagging_wal_timeout:?}, not retrying the connections"
1043 : );
1044 1 : self.wal_connection_retries.remove(&node_id);
1045 1 : WALRECEIVER_CANDIDATES_REMOVED.inc();
1046 : }
1047 8 : }
1048 9 : }
1049 :
1050 : /// # Cancel-Safety
1051 : ///
1052 : /// Not cancellation-safe.
1053 0 : pub(super) async fn shutdown(mut self) {
1054 0 : if let Some(wal_connection) = self.wal_connection.take() {
1055 0 : wal_connection.connection_task.shutdown().await;
1056 0 : }
1057 0 : }
1058 :
1059 0 : fn manager_status(&self) -> ConnectionManagerStatus {
1060 0 : ConnectionManagerStatus {
1061 0 : existing_connection: self.wal_connection.as_ref().map(|conn| conn.status),
1062 0 : wal_stream_candidates: self.wal_stream_candidates.clone(),
1063 0 : }
1064 0 : }
1065 : }
1066 :
1067 : #[derive(Debug)]
1068 : struct NewWalConnectionCandidate {
1069 : safekeeper_id: NodeId,
1070 : wal_source_connconf: PgConnectionConfig,
1071 : availability_zone: Option<String>,
1072 : reason: ReconnectReason,
1073 : }
1074 :
1075 : /// Stores the reason why WAL connection was switched, for furter debugging purposes.
1076 : #[derive(Debug, PartialEq, Eq)]
1077 : enum ReconnectReason {
1078 : NoExistingConnection,
1079 : LaggingWal {
1080 : current_commit_lsn: Lsn,
1081 : new_commit_lsn: Lsn,
1082 : threshold: NonZeroU64,
1083 : },
1084 : SwitchAvailabilityZone,
1085 : NoWalTimeout {
1086 : current_lsn: Lsn,
1087 : current_commit_lsn: Lsn,
1088 : candidate_commit_lsn: Lsn,
1089 : last_wal_interaction: Option<NaiveDateTime>,
1090 : check_time: NaiveDateTime,
1091 : threshold: Duration,
1092 : },
1093 : NoKeepAlives {
1094 : last_keep_alive: Option<NaiveDateTime>,
1095 : check_time: NaiveDateTime,
1096 : threshold: Duration,
1097 : },
1098 : }
1099 :
1100 : impl ReconnectReason {
1101 0 : fn name(&self) -> &str {
1102 0 : match self {
1103 0 : ReconnectReason::NoExistingConnection => "NoExistingConnection",
1104 0 : ReconnectReason::LaggingWal { .. } => "LaggingWal",
1105 0 : ReconnectReason::SwitchAvailabilityZone => "SwitchAvailabilityZone",
1106 0 : ReconnectReason::NoWalTimeout { .. } => "NoWalTimeout",
1107 0 : ReconnectReason::NoKeepAlives { .. } => "NoKeepAlives",
1108 : }
1109 0 : }
1110 : }
1111 :
1112 : #[cfg(test)]
1113 : mod tests {
1114 : use url::Host;
1115 : use utils::postgres_client::PostgresClientProtocol;
1116 :
1117 : use super::*;
1118 : use crate::tenant::harness::{TIMELINE_ID, TenantHarness};
1119 :
1120 19 : fn dummy_broker_sk_timeline(
1121 19 : commit_lsn: u64,
1122 19 : safekeeper_connstr: &str,
1123 19 : latest_update: NaiveDateTime,
1124 19 : ) -> BrokerSkTimeline {
1125 19 : BrokerSkTimeline {
1126 19 : timeline: SafekeeperDiscoveryResponse {
1127 19 : safekeeper_id: 0,
1128 19 : tenant_timeline_id: None,
1129 19 : commit_lsn,
1130 19 : safekeeper_connstr: safekeeper_connstr.to_owned(),
1131 19 : availability_zone: None,
1132 19 : standby_horizon: 0,
1133 19 : },
1134 19 : latest_update,
1135 19 : }
1136 19 : }
1137 :
1138 : #[tokio::test]
1139 1 : async fn no_connection_no_candidate() -> anyhow::Result<()> {
1140 1 : let harness = TenantHarness::create("no_connection_no_candidate").await?;
1141 1 : let mut state = dummy_state(&harness).await;
1142 1 : let now = Utc::now().naive_utc();
1143 1 :
1144 1 : let lagging_wal_timeout = chrono::Duration::from_std(state.conf.lagging_wal_timeout)?;
1145 1 : let delay_over_threshold = now - lagging_wal_timeout - lagging_wal_timeout;
1146 1 :
1147 1 : state.wal_connection = None;
1148 1 : state.wal_stream_candidates = HashMap::from([
1149 1 : (NodeId(0), dummy_broker_sk_timeline(1, "", now)),
1150 1 : (NodeId(1), dummy_broker_sk_timeline(0, "no_commit_lsn", now)),
1151 1 : (NodeId(2), dummy_broker_sk_timeline(0, "no_commit_lsn", now)),
1152 1 : (
1153 1 : NodeId(3),
1154 1 : dummy_broker_sk_timeline(
1155 1 : 1 + state.conf.max_lsn_wal_lag.get(),
1156 1 : "delay_over_threshold",
1157 1 : delay_over_threshold,
1158 1 : ),
1159 1 : ),
1160 1 : ]);
1161 1 :
1162 1 : let no_candidate = state.next_connection_candidate();
1163 1 : assert!(
1164 1 : no_candidate.is_none(),
1165 1 : "Expected no candidate selected out of non full data options, but got {no_candidate:?}"
1166 1 : );
1167 1 :
1168 1 : Ok(())
1169 1 : }
1170 :
1171 : #[tokio::test]
1172 1 : async fn connection_no_candidate() -> anyhow::Result<()> {
1173 1 : let harness = TenantHarness::create("connection_no_candidate").await?;
1174 1 : let mut state = dummy_state(&harness).await;
1175 1 : let now = Utc::now().naive_utc();
1176 1 :
1177 1 : let connected_sk_id = NodeId(0);
1178 1 : let current_lsn = 100_000;
1179 1 :
1180 1 : let connection_status = WalConnectionStatus {
1181 1 : is_connected: true,
1182 1 : has_processed_wal: true,
1183 1 : latest_connection_update: now,
1184 1 : latest_wal_update: now,
1185 1 : commit_lsn: Some(Lsn(current_lsn)),
1186 1 : streaming_lsn: Some(Lsn(current_lsn)),
1187 1 : node: NodeId(1),
1188 1 : };
1189 1 :
1190 1 : state.conf.max_lsn_wal_lag = NonZeroU64::new(100).unwrap();
1191 1 : state.wal_connection = Some(WalConnection {
1192 1 : started_at: now,
1193 1 : sk_id: connected_sk_id,
1194 1 : availability_zone: None,
1195 1 : status: connection_status,
1196 1 : connection_task: state.spawn(move |sender, _| async move {
1197 1 : sender
1198 1 : .send(TaskStateUpdate::Progress(connection_status))
1199 1 : .ok();
1200 1 : Ok(())
1201 1 : }),
1202 1 : discovered_new_wal: None,
1203 1 : });
1204 1 : state.wal_stream_candidates = HashMap::from([
1205 1 : (
1206 1 : connected_sk_id,
1207 1 : dummy_broker_sk_timeline(
1208 1 : current_lsn + state.conf.max_lsn_wal_lag.get() * 2,
1209 1 : DUMMY_SAFEKEEPER_HOST,
1210 1 : now,
1211 1 : ),
1212 1 : ),
1213 1 : (
1214 1 : NodeId(1),
1215 1 : dummy_broker_sk_timeline(current_lsn, "not_advanced_lsn", now),
1216 1 : ),
1217 1 : (
1218 1 : NodeId(2),
1219 1 : dummy_broker_sk_timeline(
1220 1 : current_lsn + state.conf.max_lsn_wal_lag.get() / 2,
1221 1 : "not_enough_advanced_lsn",
1222 1 : now,
1223 1 : ),
1224 1 : ),
1225 1 : ]);
1226 1 :
1227 1 : let no_candidate = state.next_connection_candidate();
1228 1 : assert!(
1229 1 : no_candidate.is_none(),
1230 1 : "Expected no candidate selected out of valid options since candidate Lsn data is ignored and others' was not advanced enough, but got {no_candidate:?}"
1231 1 : );
1232 1 :
1233 1 : Ok(())
1234 1 : }
1235 :
1236 : #[tokio::test]
1237 1 : async fn no_connection_candidate() -> anyhow::Result<()> {
1238 1 : let harness = TenantHarness::create("no_connection_candidate").await?;
1239 1 : let mut state = dummy_state(&harness).await;
1240 1 : let now = Utc::now().naive_utc();
1241 1 :
1242 1 : state.wal_connection = None;
1243 1 : state.wal_stream_candidates = HashMap::from([(
1244 1 : NodeId(0),
1245 1 : dummy_broker_sk_timeline(
1246 1 : 1 + state.conf.max_lsn_wal_lag.get(),
1247 1 : DUMMY_SAFEKEEPER_HOST,
1248 1 : now,
1249 1 : ),
1250 1 : )]);
1251 1 :
1252 1 : let only_candidate = state
1253 1 : .next_connection_candidate()
1254 1 : .expect("Expected one candidate selected out of the only data option, but got none");
1255 1 : assert_eq!(only_candidate.safekeeper_id, NodeId(0));
1256 1 : assert_eq!(
1257 1 : only_candidate.reason,
1258 1 : ReconnectReason::NoExistingConnection,
1259 1 : "Should select new safekeeper due to missing connection, even if there's also a lag in the wal over the threshold"
1260 1 : );
1261 1 : assert_eq!(
1262 1 : only_candidate.wal_source_connconf.host(),
1263 1 : &Host::Domain(DUMMY_SAFEKEEPER_HOST.to_owned())
1264 1 : );
1265 1 :
1266 1 : let selected_lsn = 100_000;
1267 1 : state.wal_stream_candidates = HashMap::from([
1268 1 : (
1269 1 : NodeId(0),
1270 1 : dummy_broker_sk_timeline(selected_lsn - 100, "smaller_commit_lsn", now),
1271 1 : ),
1272 1 : (
1273 1 : NodeId(1),
1274 1 : dummy_broker_sk_timeline(selected_lsn, DUMMY_SAFEKEEPER_HOST, now),
1275 1 : ),
1276 1 : (
1277 1 : NodeId(2),
1278 1 : dummy_broker_sk_timeline(selected_lsn + 100, "", now),
1279 1 : ),
1280 1 : ]);
1281 1 : let biggest_wal_candidate = state.next_connection_candidate().expect(
1282 1 : "Expected one candidate selected out of multiple valid data options, but got none",
1283 1 : );
1284 1 :
1285 1 : assert_eq!(biggest_wal_candidate.safekeeper_id, NodeId(1));
1286 1 : assert_eq!(
1287 1 : biggest_wal_candidate.reason,
1288 1 : ReconnectReason::NoExistingConnection,
1289 1 : "Should select new safekeeper due to missing connection, even if there's also a lag in the wal over the threshold"
1290 1 : );
1291 1 : assert_eq!(
1292 1 : biggest_wal_candidate.wal_source_connconf.host(),
1293 1 : &Host::Domain(DUMMY_SAFEKEEPER_HOST.to_owned())
1294 1 : );
1295 1 :
1296 1 : Ok(())
1297 1 : }
1298 :
1299 : #[tokio::test]
1300 1 : async fn candidate_with_many_connection_failures() -> anyhow::Result<()> {
1301 1 : let harness = TenantHarness::create("candidate_with_many_connection_failures").await?;
1302 1 : let mut state = dummy_state(&harness).await;
1303 1 : let now = Utc::now().naive_utc();
1304 1 :
1305 1 : let current_lsn = Lsn(100_000).align();
1306 1 : let bigger_lsn = Lsn(current_lsn.0 + 100).align();
1307 1 :
1308 1 : state.wal_connection = None;
1309 1 : state.wal_stream_candidates = HashMap::from([
1310 1 : (
1311 1 : NodeId(0),
1312 1 : dummy_broker_sk_timeline(bigger_lsn.0, DUMMY_SAFEKEEPER_HOST, now),
1313 1 : ),
1314 1 : (
1315 1 : NodeId(1),
1316 1 : dummy_broker_sk_timeline(current_lsn.0, DUMMY_SAFEKEEPER_HOST, now),
1317 1 : ),
1318 1 : ]);
1319 1 : state.wal_connection_retries = HashMap::from([(
1320 1 : NodeId(0),
1321 1 : RetryInfo {
1322 1 : next_retry_at: now.checked_add_signed(chrono::Duration::hours(1)),
1323 1 : retry_duration_seconds: WALCONNECTION_RETRY_MAX_BACKOFF_SECONDS,
1324 1 : },
1325 1 : )]);
1326 1 :
1327 1 : let candidate_with_less_errors = state
1328 1 : .next_connection_candidate()
1329 1 : .expect("Expected one candidate selected, but got none");
1330 1 : assert_eq!(
1331 1 : candidate_with_less_errors.safekeeper_id,
1332 1 : NodeId(1),
1333 1 : "Should select the node with no pending retry cooldown"
1334 1 : );
1335 1 :
1336 1 : Ok(())
1337 1 : }
1338 :
1339 : #[tokio::test]
1340 1 : async fn lsn_wal_over_threshold_current_candidate() -> anyhow::Result<()> {
1341 1 : let harness = TenantHarness::create("lsn_wal_over_threshcurrent_candidate").await?;
1342 1 : let mut state = dummy_state(&harness).await;
1343 1 : let current_lsn = Lsn(100_000).align();
1344 1 : let now = Utc::now().naive_utc();
1345 1 :
1346 1 : let connected_sk_id = NodeId(0);
1347 1 : let new_lsn = Lsn(current_lsn.0 + state.conf.max_lsn_wal_lag.get() + 1);
1348 1 :
1349 1 : let connection_status = WalConnectionStatus {
1350 1 : is_connected: true,
1351 1 : has_processed_wal: true,
1352 1 : latest_connection_update: now,
1353 1 : latest_wal_update: now,
1354 1 : commit_lsn: Some(current_lsn),
1355 1 : streaming_lsn: Some(current_lsn),
1356 1 : node: connected_sk_id,
1357 1 : };
1358 1 :
1359 1 : state.wal_connection = Some(WalConnection {
1360 1 : started_at: now,
1361 1 : sk_id: connected_sk_id,
1362 1 : availability_zone: None,
1363 1 : status: connection_status,
1364 1 : connection_task: state.spawn(move |sender, _| async move {
1365 1 : sender
1366 1 : .send(TaskStateUpdate::Progress(connection_status))
1367 1 : .ok();
1368 1 : Ok(())
1369 1 : }),
1370 1 : discovered_new_wal: None,
1371 1 : });
1372 1 : state.wal_stream_candidates = HashMap::from([
1373 1 : (
1374 1 : connected_sk_id,
1375 1 : dummy_broker_sk_timeline(current_lsn.0, DUMMY_SAFEKEEPER_HOST, now),
1376 1 : ),
1377 1 : (
1378 1 : NodeId(1),
1379 1 : dummy_broker_sk_timeline(new_lsn.0, "advanced_by_lsn_safekeeper", now),
1380 1 : ),
1381 1 : ]);
1382 1 :
1383 1 : let over_threshcurrent_candidate = state.next_connection_candidate().expect(
1384 1 : "Expected one candidate selected out of multiple valid data options, but got none",
1385 1 : );
1386 1 :
1387 1 : assert_eq!(over_threshcurrent_candidate.safekeeper_id, NodeId(1));
1388 1 : assert_eq!(
1389 1 : over_threshcurrent_candidate.reason,
1390 1 : ReconnectReason::LaggingWal {
1391 1 : current_commit_lsn: current_lsn,
1392 1 : new_commit_lsn: new_lsn,
1393 1 : threshold: state.conf.max_lsn_wal_lag
1394 1 : },
1395 1 : "Should select bigger WAL safekeeper if it starts to lag enough"
1396 1 : );
1397 1 : assert_eq!(
1398 1 : over_threshcurrent_candidate.wal_source_connconf.host(),
1399 1 : &Host::Domain("advanced_by_lsn_safekeeper".to_owned())
1400 1 : );
1401 1 :
1402 1 : Ok(())
1403 1 : }
1404 :
1405 : #[tokio::test]
1406 1 : async fn timeout_connection_threshold_current_candidate() -> anyhow::Result<()> {
1407 1 : let harness =
1408 1 : TenantHarness::create("timeout_connection_threshold_current_candidate").await?;
1409 1 : let mut state = dummy_state(&harness).await;
1410 1 : let current_lsn = Lsn(100_000).align();
1411 1 : let now = Utc::now().naive_utc();
1412 1 :
1413 1 : let wal_connect_timeout = chrono::Duration::from_std(state.conf.wal_connect_timeout)?;
1414 1 : let time_over_threshold =
1415 1 : Utc::now().naive_utc() - wal_connect_timeout - wal_connect_timeout;
1416 1 :
1417 1 : let connection_status = WalConnectionStatus {
1418 1 : is_connected: true,
1419 1 : has_processed_wal: true,
1420 1 : latest_connection_update: time_over_threshold,
1421 1 : latest_wal_update: time_over_threshold,
1422 1 : commit_lsn: Some(current_lsn),
1423 1 : streaming_lsn: Some(current_lsn),
1424 1 : node: NodeId(1),
1425 1 : };
1426 1 :
1427 1 : state.wal_connection = Some(WalConnection {
1428 1 : started_at: now,
1429 1 : sk_id: NodeId(1),
1430 1 : availability_zone: None,
1431 1 : status: connection_status,
1432 1 : connection_task: state.spawn(move |sender, _| async move {
1433 1 : sender
1434 1 : .send(TaskStateUpdate::Progress(connection_status))
1435 1 : .ok();
1436 1 : Ok(())
1437 1 : }),
1438 1 : discovered_new_wal: None,
1439 1 : });
1440 1 : state.wal_stream_candidates = HashMap::from([(
1441 1 : NodeId(0),
1442 1 : dummy_broker_sk_timeline(current_lsn.0, DUMMY_SAFEKEEPER_HOST, now),
1443 1 : )]);
1444 1 :
1445 1 : let over_threshcurrent_candidate = state.next_connection_candidate().expect(
1446 1 : "Expected one candidate selected out of multiple valid data options, but got none",
1447 1 : );
1448 1 :
1449 1 : assert_eq!(over_threshcurrent_candidate.safekeeper_id, NodeId(0));
1450 1 : match over_threshcurrent_candidate.reason {
1451 1 : ReconnectReason::NoKeepAlives {
1452 1 : last_keep_alive,
1453 1 : threshold,
1454 1 : ..
1455 1 : } => {
1456 1 : assert_eq!(last_keep_alive, Some(time_over_threshold));
1457 1 : assert_eq!(threshold, state.conf.lagging_wal_timeout);
1458 1 : }
1459 1 : unexpected => panic!("Unexpected reason: {unexpected:?}"),
1460 1 : }
1461 1 : assert_eq!(
1462 1 : over_threshcurrent_candidate.wal_source_connconf.host(),
1463 1 : &Host::Domain(DUMMY_SAFEKEEPER_HOST.to_owned())
1464 1 : );
1465 1 :
1466 1 : Ok(())
1467 1 : }
1468 :
1469 : #[tokio::test]
1470 1 : async fn timeout_wal_over_threshold_current_candidate() -> anyhow::Result<()> {
1471 1 : let harness = TenantHarness::create("timeout_wal_over_threshold_current_candidate").await?;
1472 1 : let mut state = dummy_state(&harness).await;
1473 1 : let current_lsn = Lsn(100_000).align();
1474 1 : let new_lsn = Lsn(100_100).align();
1475 1 : let now = Utc::now().naive_utc();
1476 1 :
1477 1 : let lagging_wal_timeout = chrono::Duration::from_std(state.conf.lagging_wal_timeout)?;
1478 1 : let time_over_threshold =
1479 1 : Utc::now().naive_utc() - lagging_wal_timeout - lagging_wal_timeout;
1480 1 :
1481 1 : let connection_status = WalConnectionStatus {
1482 1 : is_connected: true,
1483 1 : has_processed_wal: true,
1484 1 : latest_connection_update: now,
1485 1 : latest_wal_update: time_over_threshold,
1486 1 : commit_lsn: Some(current_lsn),
1487 1 : streaming_lsn: Some(current_lsn),
1488 1 : node: NodeId(1),
1489 1 : };
1490 1 :
1491 1 : state.wal_connection = Some(WalConnection {
1492 1 : started_at: now,
1493 1 : sk_id: NodeId(1),
1494 1 : availability_zone: None,
1495 1 : status: connection_status,
1496 1 : connection_task: state.spawn(move |_, _| async move { Ok(()) }),
1497 1 : discovered_new_wal: Some(NewCommittedWAL {
1498 1 : discovered_at: time_over_threshold,
1499 1 : lsn: new_lsn,
1500 1 : }),
1501 1 : });
1502 1 : state.wal_stream_candidates = HashMap::from([(
1503 1 : NodeId(0),
1504 1 : dummy_broker_sk_timeline(new_lsn.0, DUMMY_SAFEKEEPER_HOST, now),
1505 1 : )]);
1506 1 :
1507 1 : let over_threshcurrent_candidate = state.next_connection_candidate().expect(
1508 1 : "Expected one candidate selected out of multiple valid data options, but got none",
1509 1 : );
1510 1 :
1511 1 : assert_eq!(over_threshcurrent_candidate.safekeeper_id, NodeId(0));
1512 1 : match over_threshcurrent_candidate.reason {
1513 1 : ReconnectReason::NoWalTimeout {
1514 1 : current_lsn,
1515 1 : current_commit_lsn,
1516 1 : candidate_commit_lsn,
1517 1 : last_wal_interaction,
1518 1 : threshold,
1519 1 : ..
1520 1 : } => {
1521 1 : assert_eq!(current_lsn, current_lsn);
1522 1 : assert_eq!(current_commit_lsn, current_lsn);
1523 1 : assert_eq!(candidate_commit_lsn, new_lsn);
1524 1 : assert_eq!(last_wal_interaction, Some(time_over_threshold));
1525 1 : assert_eq!(threshold, state.conf.lagging_wal_timeout);
1526 1 : }
1527 1 : unexpected => panic!("Unexpected reason: {unexpected:?}"),
1528 1 : }
1529 1 : assert_eq!(
1530 1 : over_threshcurrent_candidate.wal_source_connconf.host(),
1531 1 : &Host::Domain(DUMMY_SAFEKEEPER_HOST.to_owned())
1532 1 : );
1533 1 :
1534 1 : Ok(())
1535 1 : }
1536 :
1537 : const DUMMY_SAFEKEEPER_HOST: &str = "safekeeper_connstr";
1538 :
1539 8 : async fn dummy_state(harness: &TenantHarness) -> ConnectionManagerState {
1540 8 : let (tenant, ctx) = harness.load().await;
1541 8 : let timeline = tenant
1542 8 : .create_test_timeline(TIMELINE_ID, Lsn(0x8), crate::DEFAULT_PG_VERSION, &ctx)
1543 8 : .await
1544 8 : .expect("Failed to create an empty timeline for dummy wal connection manager");
1545 8 :
1546 8 : let protocol = PostgresClientProtocol::Interpreted {
1547 8 : format: utils::postgres_client::InterpretedFormat::Protobuf,
1548 8 : compression: Some(utils::postgres_client::Compression::Zstd { level: 1 }),
1549 8 : };
1550 8 :
1551 8 : ConnectionManagerState {
1552 8 : id: TenantTimelineId {
1553 8 : tenant_id: harness.tenant_shard_id.tenant_id,
1554 8 : timeline_id: TIMELINE_ID,
1555 8 : },
1556 8 : timeline,
1557 8 : cancel: CancellationToken::new(),
1558 8 : conf: WalReceiverConf {
1559 8 : protocol,
1560 8 : wal_connect_timeout: Duration::from_secs(1),
1561 8 : lagging_wal_timeout: Duration::from_secs(1),
1562 8 : max_lsn_wal_lag: NonZeroU64::new(1024 * 1024).unwrap(),
1563 8 : auth_token: None,
1564 8 : availability_zone: None,
1565 8 : ingest_batch_size: 1,
1566 8 : validate_wal_contiguity: false,
1567 8 : },
1568 8 : wal_connection: None,
1569 8 : wal_stream_candidates: HashMap::new(),
1570 8 : wal_connection_retries: HashMap::new(),
1571 8 : }
1572 8 : }
1573 :
1574 : #[tokio::test]
1575 1 : async fn switch_to_same_availability_zone() -> anyhow::Result<()> {
1576 1 : // Pageserver and one of safekeepers will be in the same availability zone
1577 1 : // and pageserver should prefer to connect to it.
1578 1 : let test_az = Some("test_az".to_owned());
1579 1 :
1580 1 : let harness = TenantHarness::create("switch_to_same_availability_zone").await?;
1581 1 : let mut state = dummy_state(&harness).await;
1582 1 : state.conf.availability_zone.clone_from(&test_az);
1583 1 : let current_lsn = Lsn(100_000).align();
1584 1 : let now = Utc::now().naive_utc();
1585 1 :
1586 1 : let connected_sk_id = NodeId(0);
1587 1 :
1588 1 : let connection_status = WalConnectionStatus {
1589 1 : is_connected: true,
1590 1 : has_processed_wal: true,
1591 1 : latest_connection_update: now,
1592 1 : latest_wal_update: now,
1593 1 : commit_lsn: Some(current_lsn),
1594 1 : streaming_lsn: Some(current_lsn),
1595 1 : node: connected_sk_id,
1596 1 : };
1597 1 :
1598 1 : state.wal_connection = Some(WalConnection {
1599 1 : started_at: now,
1600 1 : sk_id: connected_sk_id,
1601 1 : availability_zone: None,
1602 1 : status: connection_status,
1603 1 : connection_task: state.spawn(move |sender, _| async move {
1604 1 : sender
1605 1 : .send(TaskStateUpdate::Progress(connection_status))
1606 1 : .ok();
1607 1 : Ok(())
1608 1 : }),
1609 1 : discovered_new_wal: None,
1610 1 : });
1611 1 :
1612 1 : // We have another safekeeper with the same commit_lsn, and it have the same availability zone as
1613 1 : // the current pageserver.
1614 1 : let mut same_az_sk = dummy_broker_sk_timeline(current_lsn.0, "same_az", now);
1615 1 : same_az_sk.timeline.availability_zone.clone_from(&test_az);
1616 1 :
1617 1 : state.wal_stream_candidates = HashMap::from([
1618 1 : (
1619 1 : connected_sk_id,
1620 1 : dummy_broker_sk_timeline(current_lsn.0, DUMMY_SAFEKEEPER_HOST, now),
1621 1 : ),
1622 1 : (NodeId(1), same_az_sk),
1623 1 : ]);
1624 1 :
1625 1 : // We expect that pageserver will switch to the safekeeper in the same availability zone,
1626 1 : // even if it has the same commit_lsn.
1627 1 : let next_candidate = state.next_connection_candidate().expect(
1628 1 : "Expected one candidate selected out of multiple valid data options, but got none",
1629 1 : );
1630 1 :
1631 1 : assert_eq!(next_candidate.safekeeper_id, NodeId(1));
1632 1 : assert_eq!(
1633 1 : next_candidate.reason,
1634 1 : ReconnectReason::SwitchAvailabilityZone,
1635 1 : "Should switch to the safekeeper in the same availability zone, if it has the same commit_lsn"
1636 1 : );
1637 1 : assert_eq!(
1638 1 : next_candidate.wal_source_connconf.host(),
1639 1 : &Host::Domain("same_az".to_owned())
1640 1 : );
1641 1 :
1642 1 : Ok(())
1643 1 : }
1644 : }
|