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

Generated by: LCOV version 2.1-beta