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