Line data Source code
1 : //! WAL receiver manages an open connection to safekeeper, to get the WAL it streams into.
2 : //! To do so, a current implementation needs to do the following:
3 : //!
4 : //! * acknowledge the timelines that it needs to stream WAL into.
5 : //! Pageserver is able to dynamically (un)load tenants on attach and detach,
6 : //! hence WAL receiver needs to react on such events.
7 : //!
8 : //! * get a broker subscription, stream data from it to determine that a timeline needs WAL streaming.
9 : //! For that, it watches specific keys in storage_broker and pulls the relevant data periodically.
10 : //! The data is produced by safekeepers, that push it periodically and pull it to synchronize between each other.
11 : //! Without this data, no WAL streaming is possible currently.
12 : //!
13 : //! Only one active WAL streaming connection is allowed at a time.
14 : //! The connection is supposed to be updated periodically, based on safekeeper timeline data.
15 : //!
16 : //! * handle the actual connection and WAL streaming
17 : //!
18 : //! Handling happens dynamically, by portions of WAL being processed and registered in the server.
19 : //! Along with the registration, certain metadata is written to show WAL streaming progress and rely on that when considering safekeepers for connection.
20 : //!
21 : //! The current module contains high-level primitives used in the submodules; general synchronization, timeline acknowledgement and shutdown logic.
22 :
23 : mod connection_manager;
24 : mod walreceiver_connection;
25 :
26 : use crate::context::{DownloadBehavior, RequestContext};
27 : use crate::task_mgr::{TaskKind, WALRECEIVER_RUNTIME};
28 : use crate::tenant::debug_assert_current_span_has_tenant_and_timeline_id;
29 : use crate::tenant::timeline::walreceiver::connection_manager::{
30 : connection_manager_loop_step, ConnectionManagerState,
31 : };
32 :
33 : use std::future::Future;
34 : use std::num::NonZeroU64;
35 : use std::sync::Arc;
36 : use std::time::Duration;
37 : use storage_broker::BrokerClientChannel;
38 : use tokio::sync::watch;
39 : use tokio_util::sync::CancellationToken;
40 : use tracing::*;
41 : use utils::postgres_client::PostgresClientProtocol;
42 :
43 : use self::connection_manager::ConnectionManagerStatus;
44 :
45 : use super::Timeline;
46 :
47 : #[derive(Clone)]
48 : pub struct WalReceiverConf {
49 : pub protocol: PostgresClientProtocol,
50 : /// The timeout on the connection to safekeeper for WAL streaming.
51 : pub wal_connect_timeout: Duration,
52 : /// The timeout to use to determine when the current connection is "stale" and reconnect to the other one.
53 : pub lagging_wal_timeout: Duration,
54 : /// The Lsn lag to use to determine when the current connection is lagging to much behind and reconnect to the other one.
55 : pub max_lsn_wal_lag: NonZeroU64,
56 : pub auth_token: Option<Arc<String>>,
57 : pub availability_zone: Option<String>,
58 : pub ingest_batch_size: u64,
59 : pub validate_wal_contiguity: bool,
60 : }
61 :
62 : pub struct WalReceiver {
63 : manager_status: Arc<std::sync::RwLock<Option<ConnectionManagerStatus>>>,
64 : /// All task spawned by [`WalReceiver::start`] and its children are sensitive to this token.
65 : /// It's a child token of [`Timeline`] so that timeline shutdown can cancel WalReceiver tasks early for `freeze_and_flush=true`.
66 : cancel: CancellationToken,
67 : }
68 :
69 : impl WalReceiver {
70 0 : pub fn start(
71 0 : timeline: Arc<Timeline>,
72 0 : conf: WalReceiverConf,
73 0 : mut broker_client: BrokerClientChannel,
74 0 : ctx: &RequestContext,
75 0 : ) -> Self {
76 0 : let tenant_shard_id = timeline.tenant_shard_id;
77 0 : let timeline_id = timeline.timeline_id;
78 0 : let walreceiver_ctx =
79 0 : ctx.detached_child(TaskKind::WalReceiverManager, DownloadBehavior::Error);
80 0 : let loop_status = Arc::new(std::sync::RwLock::new(None));
81 0 : let manager_status = Arc::clone(&loop_status);
82 0 : let cancel = timeline.cancel.child_token();
83 0 : WALRECEIVER_RUNTIME.spawn({
84 0 : let cancel = cancel.clone();
85 0 : async move {
86 0 : debug_assert_current_span_has_tenant_and_timeline_id();
87 : // acquire timeline gate so we know the task doesn't outlive the Timeline
88 0 : let Ok(_guard) = timeline.gate.enter() else {
89 0 : debug!("WAL receiver manager could not enter the gate timeline gate, it's closed already");
90 0 : return;
91 : };
92 0 : debug!("WAL receiver manager started, connecting to broker");
93 0 : let mut connection_manager_state = ConnectionManagerState::new(
94 0 : timeline,
95 0 : conf,
96 0 : cancel.clone(),
97 0 : );
98 0 : while !cancel.is_cancelled() {
99 0 : let loop_step_result = connection_manager_loop_step(
100 0 : &mut broker_client,
101 0 : &mut connection_manager_state,
102 0 : &walreceiver_ctx,
103 0 : &cancel,
104 0 : &loop_status,
105 0 : ).await;
106 0 : match loop_step_result {
107 0 : Ok(()) => continue,
108 0 : Err(_cancelled) => {
109 0 : trace!("Connection manager loop ended, shutting down");
110 0 : break;
111 : }
112 : }
113 : }
114 0 : connection_manager_state.shutdown().await;
115 0 : *loop_status.write().unwrap() = None;
116 0 : debug!("task exits");
117 0 : }
118 0 : .instrument(info_span!(parent: None, "wal_connection_manager", tenant_id = %tenant_shard_id.tenant_id, shard_id = %tenant_shard_id.shard_slug(), timeline_id = %timeline_id))
119 : });
120 :
121 0 : Self {
122 0 : manager_status,
123 0 : cancel,
124 0 : }
125 0 : }
126 :
127 : #[instrument(skip_all, level = tracing::Level::DEBUG)]
128 : pub fn cancel(&self) {
129 : debug_assert_current_span_has_tenant_and_timeline_id();
130 : debug!("cancelling walreceiver tasks");
131 : self.cancel.cancel();
132 : }
133 :
134 0 : pub(crate) fn status(&self) -> Option<ConnectionManagerStatus> {
135 0 : self.manager_status.read().unwrap().clone()
136 0 : }
137 : }
138 :
139 : /// A handle of an asynchronous task.
140 : /// The task has a channel that it can use to communicate its lifecycle events in a certain form, see [`TaskEvent`]
141 : /// and a cancellation token that it can listen to for earlier interrupts.
142 : ///
143 : /// Note that the communication happens via the `watch` channel, that does not accumulate the events, replacing the old one with the never one on submission.
144 : /// That may lead to certain events not being observed by the listener.
145 : #[derive(Debug)]
146 : struct TaskHandle<E> {
147 : join_handle: Option<tokio::task::JoinHandle<anyhow::Result<()>>>,
148 : events_receiver: watch::Receiver<TaskStateUpdate<E>>,
149 : cancellation: CancellationToken,
150 : }
151 :
152 : enum TaskEvent<E> {
153 : Update(TaskStateUpdate<E>),
154 : End(anyhow::Result<()>),
155 : }
156 :
157 : #[derive(Debug, Clone)]
158 : enum TaskStateUpdate<E> {
159 : Started,
160 : Progress(E),
161 : }
162 :
163 : impl<E: Clone> TaskHandle<E> {
164 : /// Initializes the task, starting it immediately after the creation.
165 : ///
166 : /// The second argument to `task` is a child token of `cancel_parent` ([`CancellationToken::child_token`]).
167 : /// It being a child token enables us to provide a [`Self::shutdown`] method.
168 20 : fn spawn<Fut>(
169 20 : cancel_parent: &CancellationToken,
170 20 : task: impl FnOnce(watch::Sender<TaskStateUpdate<E>>, CancellationToken) -> Fut + Send + 'static,
171 20 : ) -> Self
172 20 : where
173 20 : Fut: Future<Output = anyhow::Result<()>> + Send,
174 20 : E: Send + Sync + 'static,
175 20 : {
176 20 : let cancellation = cancel_parent.child_token();
177 20 : let (events_sender, events_receiver) = watch::channel(TaskStateUpdate::Started);
178 20 :
179 20 : let cancellation_clone = cancellation.clone();
180 20 : let join_handle = WALRECEIVER_RUNTIME.spawn(async move {
181 20 : events_sender.send(TaskStateUpdate::Started).ok();
182 20 : task(events_sender, cancellation_clone).await
183 : // events_sender is dropped at some point during the .await above.
184 : // But the task is still running on WALRECEIVER_RUNTIME.
185 : // That is the window when `!jh.is_finished()`
186 : // is true inside `fn next_task_event()` below.
187 20 : });
188 20 :
189 20 : TaskHandle {
190 20 : join_handle: Some(join_handle),
191 20 : events_receiver,
192 20 : cancellation,
193 20 : }
194 20 : }
195 :
196 : /// # Cancel-Safety
197 : ///
198 : /// Cancellation-safe.
199 0 : async fn next_task_event(&mut self) -> TaskEvent<E> {
200 0 : match self.events_receiver.changed().await {
201 0 : Ok(()) => TaskEvent::Update((self.events_receiver.borrow()).clone()),
202 0 : Err(_task_channel_part_dropped) => {
203 0 : TaskEvent::End(match self.join_handle.as_mut() {
204 0 : Some(jh) => {
205 0 : if !jh.is_finished() {
206 : // See: https://github.com/neondatabase/neon/issues/2885
207 0 : trace!("sender is dropped while join handle is still alive");
208 0 : }
209 :
210 0 : let res = match jh.await {
211 0 : Ok(res) => res,
212 0 : Err(je) if je.is_cancelled() => unreachable!("not used"),
213 0 : Err(je) if je.is_panic() => {
214 0 : // already logged
215 0 : Ok(())
216 : }
217 0 : Err(je) => Err(anyhow::Error::new(je).context("join walreceiver task")),
218 : };
219 :
220 : // For cancellation-safety, drop join_handle only after successful .await.
221 0 : self.join_handle = None;
222 0 :
223 0 : res
224 : }
225 : None => {
226 : // Another option is to have an enum, join handle or result and give away the reference to it
227 0 : Err(anyhow::anyhow!("Task was joined more than once"))
228 : }
229 : })
230 : }
231 : }
232 0 : }
233 :
234 : /// Aborts current task, waiting for it to finish.
235 0 : async fn shutdown(self) {
236 0 : if let Some(jh) = self.join_handle {
237 0 : self.cancellation.cancel();
238 0 : match jh.await {
239 0 : Ok(Ok(())) => debug!("Shutdown success"),
240 0 : Ok(Err(e)) => error!("Shutdown task error: {e:?}"),
241 0 : Err(je) if je.is_cancelled() => unreachable!("not used"),
242 0 : Err(je) if je.is_panic() => {
243 0 : // already logged
244 0 : }
245 0 : Err(je) => {
246 0 : error!("Shutdown task join error: {je}")
247 : }
248 : }
249 0 : }
250 0 : }
251 : }
|