LCOV - code coverage report
Current view: top level - pageserver/src/tenant/timeline - walreceiver.rs (source / functions) Coverage Total Hit
Test: a2f0f8a80fbf1089336086fa360ce27fa555cb1a.info Lines: 20.7 % 111 23
Test Date: 2024-11-20 17:59:39 Functions: 50.0 % 20 10

            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              : }
      60              : 
      61              : pub struct WalReceiver {
      62              :     manager_status: Arc<std::sync::RwLock<Option<ConnectionManagerStatus>>>,
      63              :     /// All task spawned by [`WalReceiver::start`] and its children are sensitive to this token.
      64              :     /// It's a child token of [`Timeline`] so that timeline shutdown can cancel WalReceiver tasks early for `freeze_and_flush=true`.
      65              :     cancel: CancellationToken,
      66              : }
      67              : 
      68              : impl WalReceiver {
      69            0 :     pub fn start(
      70            0 :         timeline: Arc<Timeline>,
      71            0 :         conf: WalReceiverConf,
      72            0 :         mut broker_client: BrokerClientChannel,
      73            0 :         ctx: &RequestContext,
      74            0 :     ) -> Self {
      75            0 :         let tenant_shard_id = timeline.tenant_shard_id;
      76            0 :         let timeline_id = timeline.timeline_id;
      77            0 :         let walreceiver_ctx =
      78            0 :             ctx.detached_child(TaskKind::WalReceiverManager, DownloadBehavior::Error);
      79            0 :         let loop_status = Arc::new(std::sync::RwLock::new(None));
      80            0 :         let manager_status = Arc::clone(&loop_status);
      81            0 :         let cancel = timeline.cancel.child_token();
      82            0 :         WALRECEIVER_RUNTIME.spawn({
      83            0 :             let cancel = cancel.clone();
      84            0 :             async move {
      85            0 :                 debug_assert_current_span_has_tenant_and_timeline_id();
      86              :                 // acquire timeline gate so we know the task doesn't outlive the Timeline
      87            0 :                 let Ok(_guard) = timeline.gate.enter() else {
      88            0 :                     debug!("WAL receiver manager could not enter the gate timeline gate, it's closed already");
      89            0 :                     return;
      90              :                 };
      91            0 :                 debug!("WAL receiver manager started, connecting to broker");
      92            0 :                 let mut connection_manager_state = ConnectionManagerState::new(
      93            0 :                     timeline,
      94            0 :                     conf,
      95            0 :                     cancel.clone(),
      96            0 :                 );
      97            0 :                 while !cancel.is_cancelled() {
      98            0 :                     let loop_step_result = connection_manager_loop_step(
      99            0 :                         &mut broker_client,
     100            0 :                         &mut connection_manager_state,
     101            0 :                         &walreceiver_ctx,
     102            0 :                         &cancel,
     103            0 :                         &loop_status,
     104            0 :                     ).await;
     105            0 :                     match loop_step_result {
     106            0 :                         Ok(()) => continue,
     107            0 :                         Err(_cancelled) => {
     108            0 :                             trace!("Connection manager loop ended, shutting down");
     109            0 :                             break;
     110              :                         }
     111              :                     }
     112              :                 }
     113            0 :                 connection_manager_state.shutdown().await;
     114            0 :                 *loop_status.write().unwrap() = None;
     115            0 :                 debug!("task exits");
     116            0 :             }
     117            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))
     118              :         });
     119              : 
     120            0 :         Self {
     121            0 :             manager_status,
     122            0 :             cancel,
     123            0 :         }
     124            0 :     }
     125              : 
     126            0 :     #[instrument(skip_all, level = tracing::Level::DEBUG)]
     127              :     pub fn cancel(&self) {
     128              :         debug_assert_current_span_has_tenant_and_timeline_id();
     129              :         debug!("cancelling walreceiver tasks");
     130              :         self.cancel.cancel();
     131              :     }
     132              : 
     133            0 :     pub(crate) fn status(&self) -> Option<ConnectionManagerStatus> {
     134            0 :         self.manager_status.read().unwrap().clone()
     135            0 :     }
     136              : }
     137              : 
     138              : /// A handle of an asynchronous task.
     139              : /// The task has a channel that it can use to communicate its lifecycle events in a certain form, see [`TaskEvent`]
     140              : /// and a cancellation token that it can listen to for earlier interrupts.
     141              : ///
     142              : /// 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.
     143              : /// That may lead to certain events not being observed by the listener.
     144              : #[derive(Debug)]
     145              : struct TaskHandle<E> {
     146              :     join_handle: Option<tokio::task::JoinHandle<anyhow::Result<()>>>,
     147              :     events_receiver: watch::Receiver<TaskStateUpdate<E>>,
     148              :     cancellation: CancellationToken,
     149              : }
     150              : 
     151              : enum TaskEvent<E> {
     152              :     Update(TaskStateUpdate<E>),
     153              :     End(anyhow::Result<()>),
     154              : }
     155              : 
     156              : #[derive(Debug, Clone)]
     157              : enum TaskStateUpdate<E> {
     158              :     Started,
     159              :     Progress(E),
     160              : }
     161              : 
     162              : impl<E: Clone> TaskHandle<E> {
     163              :     /// Initializes the task, starting it immediately after the creation.
     164              :     ///
     165              :     /// The second argument to `task` is a child token of `cancel_parent` ([`CancellationToken::child_token`]).
     166              :     /// It being a child token enables us to provide a [`Self::shutdown`] method.
     167           10 :     fn spawn<Fut>(
     168           10 :         cancel_parent: &CancellationToken,
     169           10 :         task: impl FnOnce(watch::Sender<TaskStateUpdate<E>>, CancellationToken) -> Fut + Send + 'static,
     170           10 :     ) -> Self
     171           10 :     where
     172           10 :         Fut: Future<Output = anyhow::Result<()>> + Send,
     173           10 :         E: Send + Sync + 'static,
     174           10 :     {
     175           10 :         let cancellation = cancel_parent.child_token();
     176           10 :         let (events_sender, events_receiver) = watch::channel(TaskStateUpdate::Started);
     177           10 : 
     178           10 :         let cancellation_clone = cancellation.clone();
     179           10 :         let join_handle = WALRECEIVER_RUNTIME.spawn(async move {
     180           10 :             events_sender.send(TaskStateUpdate::Started).ok();
     181           10 :             task(events_sender, cancellation_clone).await
     182              :             // events_sender is dropped at some point during the .await above.
     183              :             // But the task is still running on WALRECEIVER_RUNTIME.
     184              :             // That is the window when `!jh.is_finished()`
     185              :             // is true inside `fn next_task_event()` below.
     186           10 :         });
     187           10 : 
     188           10 :         TaskHandle {
     189           10 :             join_handle: Some(join_handle),
     190           10 :             events_receiver,
     191           10 :             cancellation,
     192           10 :         }
     193           10 :     }
     194              : 
     195              :     /// # Cancel-Safety
     196              :     ///
     197              :     /// Cancellation-safe.
     198            0 :     async fn next_task_event(&mut self) -> TaskEvent<E> {
     199            0 :         match self.events_receiver.changed().await {
     200            0 :             Ok(()) => TaskEvent::Update((self.events_receiver.borrow()).clone()),
     201            0 :             Err(_task_channel_part_dropped) => {
     202            0 :                 TaskEvent::End(match self.join_handle.as_mut() {
     203            0 :                     Some(jh) => {
     204            0 :                         if !jh.is_finished() {
     205              :                             // See: https://github.com/neondatabase/neon/issues/2885
     206            0 :                             trace!("sender is dropped while join handle is still alive");
     207            0 :                         }
     208              : 
     209            0 :                         let res = match jh.await {
     210            0 :                             Ok(res) => res,
     211            0 :                             Err(je) if je.is_cancelled() => unreachable!("not used"),
     212            0 :                             Err(je) if je.is_panic() => {
     213            0 :                                 // already logged
     214            0 :                                 Ok(())
     215              :                             }
     216            0 :                             Err(je) => Err(anyhow::Error::new(je).context("join walreceiver task")),
     217              :                         };
     218              : 
     219              :                         // For cancellation-safety, drop join_handle only after successful .await.
     220            0 :                         self.join_handle = None;
     221            0 : 
     222            0 :                         res
     223              :                     }
     224              :                     None => {
     225              :                         // Another option is to have an enum, join handle or result and give away the reference to it
     226            0 :                         Err(anyhow::anyhow!("Task was joined more than once"))
     227              :                     }
     228              :                 })
     229              :             }
     230              :         }
     231            0 :     }
     232              : 
     233              :     /// Aborts current task, waiting for it to finish.
     234            0 :     async fn shutdown(self) {
     235            0 :         if let Some(jh) = self.join_handle {
     236            0 :             self.cancellation.cancel();
     237            0 :             match jh.await {
     238            0 :                 Ok(Ok(())) => debug!("Shutdown success"),
     239            0 :                 Ok(Err(e)) => error!("Shutdown task error: {e:?}"),
     240            0 :                 Err(je) if je.is_cancelled() => unreachable!("not used"),
     241            0 :                 Err(je) if je.is_panic() => {
     242            0 :                     // already logged
     243            0 :                 }
     244            0 :                 Err(je) => {
     245            0 :                     error!("Shutdown task join error: {je}")
     246              :                 }
     247              :             }
     248            0 :         }
     249            0 :     }
     250              : }
        

Generated by: LCOV version 2.1-beta