LCOV - code coverage report
Current view: top level - pageserver/src - deletion_queue.rs (source / functions) Coverage Total Hit
Test: 5187d4b6d9cfe1c429baf0147b0578521d04e1ed.info Lines: 87.3 % 821 717
Test Date: 2024-06-26 21:48:01 Functions: 56.5 % 131 74

            Line data    Source code
       1              : mod deleter;
       2              : mod list_writer;
       3              : mod validator;
       4              : 
       5              : use std::collections::HashMap;
       6              : use std::sync::Arc;
       7              : use std::time::Duration;
       8              : 
       9              : use crate::control_plane_client::ControlPlaneGenerationsApi;
      10              : use crate::metrics;
      11              : use crate::tenant::remote_timeline_client::remote_layer_path;
      12              : use crate::tenant::remote_timeline_client::remote_timeline_path;
      13              : use crate::tenant::remote_timeline_client::LayerFileMetadata;
      14              : use crate::virtual_file::MaybeFatalIo;
      15              : use crate::virtual_file::VirtualFile;
      16              : use anyhow::Context;
      17              : use camino::Utf8PathBuf;
      18              : use pageserver_api::shard::TenantShardId;
      19              : use remote_storage::{GenericRemoteStorage, RemotePath};
      20              : use serde::Deserialize;
      21              : use serde::Serialize;
      22              : use thiserror::Error;
      23              : use tokio_util::sync::CancellationToken;
      24              : use tracing::Instrument;
      25              : use tracing::{debug, error};
      26              : use utils::crashsafe::path_with_suffix_extension;
      27              : use utils::generation::Generation;
      28              : use utils::id::TimelineId;
      29              : use utils::lsn::AtomicLsn;
      30              : use utils::lsn::Lsn;
      31              : 
      32              : use self::deleter::Deleter;
      33              : use self::list_writer::DeletionOp;
      34              : use self::list_writer::ListWriter;
      35              : use self::list_writer::RecoverOp;
      36              : use self::validator::Validator;
      37              : use deleter::DeleterMessage;
      38              : use list_writer::ListWriterQueueMessage;
      39              : use validator::ValidatorQueueMessage;
      40              : 
      41              : use crate::{config::PageServerConf, tenant::storage_layer::LayerName};
      42              : 
      43              : // TODO: configurable for how long to wait before executing deletions
      44              : 
      45              : /// We aggregate object deletions from many tenants in one place, for several reasons:
      46              : /// - Coalesce deletions into fewer DeleteObjects calls
      47              : /// - Enable Tenant/Timeline lifetimes to be shorter than the time it takes
      48              : ///   to flush any outstanding deletions.
      49              : /// - Globally control throughput of deletions, as these are a low priority task: do
      50              : ///   not compete with the same S3 clients/connections used for higher priority uploads.
      51              : /// - Enable gating deletions on validation of a tenant's generation number, to make
      52              : ///   it safe to multi-attach tenants (see docs/rfcs/025-generation-numbers.md)
      53              : ///
      54              : /// There are two kinds of deletion: deferred and immediate.  A deferred deletion
      55              : /// may be intentionally delayed to protect passive readers of S3 data, and is
      56              : /// subject to a generation number validation step.  An immediate deletion is
      57              : /// ready to execute immediately, and is only queued up so that it can be coalesced
      58              : /// with other deletions in flight.
      59              : ///
      60              : /// Deferred deletions pass through three steps:
      61              : /// - ListWriter: accumulate deletion requests from Timelines, and batch them up into
      62              : ///   DeletionLists, which are persisted to disk.
      63              : /// - Validator: accumulate deletion lists, and validate them en-masse prior to passing
      64              : ///   the keys in the list onward for actual deletion.  Also validate remote_consistent_lsn
      65              : ///   updates for running timelines.
      66              : /// - Deleter: accumulate object keys that the validator has validated, and execute them in
      67              : ///   batches of 1000 keys via DeleteObjects.
      68              : ///
      69              : /// Non-deferred deletions, such as during timeline deletion, bypass the first
      70              : /// two stages and are passed straight into the Deleter.
      71              : ///
      72              : /// Internally, each stage is joined by a channel to the next.  On disk, there is only
      73              : /// one queue (of DeletionLists), which is written by the frontend and consumed
      74              : /// by the backend.
      75              : #[derive(Clone)]
      76              : pub struct DeletionQueue {
      77              :     client: DeletionQueueClient,
      78              : 
      79              :     // Parent cancellation token for the tokens passed into background workers
      80              :     cancel: CancellationToken,
      81              : }
      82              : 
      83              : /// Opaque wrapper around individual worker tasks, to avoid making the
      84              : /// worker objects themselves public
      85              : pub struct DeletionQueueWorkers<C>
      86              : where
      87              :     C: ControlPlaneGenerationsApi + Send + Sync,
      88              : {
      89              :     frontend: ListWriter,
      90              :     backend: Validator<C>,
      91              :     executor: Deleter,
      92              : }
      93              : 
      94              : impl<C> DeletionQueueWorkers<C>
      95              : where
      96              :     C: ControlPlaneGenerationsApi + Send + Sync + 'static,
      97              : {
      98            8 :     pub fn spawn_with(mut self, runtime: &tokio::runtime::Handle) -> tokio::task::JoinHandle<()> {
      99            8 :         let jh_frontend = runtime.spawn(async move {
     100            8 :             self.frontend
     101            8 :                 .background()
     102            8 :                 .instrument(tracing::info_span!(parent:None, "deletion frontend"))
     103           52 :                 .await
     104            8 :         });
     105            8 :         let jh_backend = runtime.spawn(async move {
     106            8 :             self.backend
     107            8 :                 .background()
     108            8 :                 .instrument(tracing::info_span!(parent:None, "deletion backend"))
     109           58 :                 .await
     110            8 :         });
     111            8 :         let jh_executor = runtime.spawn(async move {
     112            8 :             self.executor
     113            8 :                 .background()
     114            8 :                 .instrument(tracing::info_span!(parent:None, "deletion executor"))
     115           28 :                 .await
     116            8 :         });
     117            8 : 
     118            8 :         runtime.spawn({
     119            8 :             async move {
     120            8 :                 jh_frontend.await.expect("error joining frontend worker");
     121            2 :                 jh_backend.await.expect("error joining backend worker");
     122            2 :                 drop(jh_executor.await.expect("error joining executor worker"));
     123            8 :             }
     124            8 :         })
     125            8 :     }
     126              : }
     127              : 
     128              : /// A FlushOp is just a oneshot channel, where we send the transmit side down
     129              : /// another channel, and the receive side will receive a message when the channel
     130              : /// we're flushing has reached the FlushOp we sent into it.
     131              : ///
     132              : /// The only extra behavior beyond the channel is that the notify() method does not
     133              : /// return an error when the receive side has been dropped, because in this use case
     134              : /// it is harmless (the code that initiated the flush no longer cares about the result).
     135              : #[derive(Debug)]
     136              : struct FlushOp {
     137              :     tx: tokio::sync::oneshot::Sender<()>,
     138              : }
     139              : 
     140              : impl FlushOp {
     141           42 :     fn new() -> (Self, tokio::sync::oneshot::Receiver<()>) {
     142           42 :         let (tx, rx) = tokio::sync::oneshot::channel::<()>();
     143           42 :         (Self { tx }, rx)
     144           42 :     }
     145              : 
     146           42 :     fn notify(self) {
     147           42 :         if self.tx.send(()).is_err() {
     148              :             // oneshot channel closed. This is legal: a client could be destroyed while waiting for a flush.
     149            0 :             debug!("deletion queue flush from dropped client");
     150           42 :         };
     151           42 :     }
     152              : }
     153              : 
     154              : #[derive(Clone, Debug)]
     155              : pub struct DeletionQueueClient {
     156              :     tx: tokio::sync::mpsc::UnboundedSender<ListWriterQueueMessage>,
     157              :     executor_tx: tokio::sync::mpsc::Sender<DeleterMessage>,
     158              : 
     159              :     lsn_table: Arc<std::sync::RwLock<VisibleLsnUpdates>>,
     160              : }
     161              : 
     162           18 : #[derive(Debug, Serialize, Deserialize, PartialEq, Eq)]
     163              : struct TenantDeletionList {
     164              :     /// For each Timeline, a list of key fragments to append to the timeline remote path
     165              :     /// when reconstructing a full key
     166              :     timelines: HashMap<TimelineId, Vec<String>>,
     167              : 
     168              :     /// The generation in which this deletion was emitted: note that this may not be the
     169              :     /// same as the generation of any layers being deleted.  The generation of the layer
     170              :     /// has already been absorbed into the keys in `objects`
     171              :     generation: Generation,
     172              : }
     173              : 
     174              : impl TenantDeletionList {
     175           10 :     pub(crate) fn len(&self) -> usize {
     176           10 :         self.timelines.values().map(|v| v.len()).sum()
     177           10 :     }
     178              : }
     179              : 
     180              : /// Files ending with this suffix will be ignored and erased
     181              : /// during recovery as startup.
     182              : const TEMP_SUFFIX: &str = "tmp";
     183              : 
     184           30 : #[derive(Debug, Serialize, Deserialize, PartialEq, Eq)]
     185              : struct DeletionList {
     186              :     /// Serialization version, for future use
     187              :     version: u8,
     188              : 
     189              :     /// Used for constructing a unique key for each deletion list we write out.
     190              :     sequence: u64,
     191              : 
     192              :     /// To avoid repeating tenant/timeline IDs in every key, we store keys in
     193              :     /// nested HashMaps by TenantTimelineID.  Each Tenant only appears once
     194              :     /// with one unique generation ID: if someone tries to push a second generation
     195              :     /// ID for the same tenant, we will start a new DeletionList.
     196              :     tenants: HashMap<TenantShardId, TenantDeletionList>,
     197              : 
     198              :     /// Avoid having to walk `tenants` to calculate the number of keys in
     199              :     /// the nested deletion lists
     200              :     size: usize,
     201              : 
     202              :     /// Set to true when the list has undergone validation with the control
     203              :     /// plane and the remaining contents of `tenants` are valid.  A list may
     204              :     /// also be implicitly marked valid by DeletionHeader.validated_sequence
     205              :     /// advancing to >= DeletionList.sequence
     206              :     #[serde(default)]
     207              :     #[serde(skip_serializing_if = "std::ops::Not::not")]
     208              :     validated: bool,
     209              : }
     210              : 
     211            0 : #[derive(Debug, Serialize, Deserialize)]
     212              : struct DeletionHeader {
     213              :     /// Serialization version, for future use
     214              :     version: u8,
     215              : 
     216              :     /// The highest sequence number (inclusive) that has been validated.  All deletion
     217              :     /// lists on disk with a sequence <= this value are safe to execute.
     218              :     validated_sequence: u64,
     219              : }
     220              : 
     221              : impl DeletionHeader {
     222              :     const VERSION_LATEST: u8 = 1;
     223              : 
     224            8 :     fn new(validated_sequence: u64) -> Self {
     225            8 :         Self {
     226            8 :             version: Self::VERSION_LATEST,
     227            8 :             validated_sequence,
     228            8 :         }
     229            8 :     }
     230              : 
     231            8 :     async fn save(&self, conf: &'static PageServerConf) -> anyhow::Result<()> {
     232            8 :         debug!("Saving deletion list header {:?}", self);
     233            8 :         let header_bytes = serde_json::to_vec(self).context("serialize deletion header")?;
     234            8 :         let header_path = conf.deletion_header_path();
     235            8 :         let temp_path = path_with_suffix_extension(&header_path, TEMP_SUFFIX);
     236            8 :         VirtualFile::crashsafe_overwrite(header_path, temp_path, header_bytes)
     237            8 :             .await
     238            8 :             .maybe_fatal_err("save deletion header")?;
     239              : 
     240            8 :         Ok(())
     241            8 :     }
     242              : }
     243              : 
     244              : impl DeletionList {
     245              :     const VERSION_LATEST: u8 = 1;
     246           20 :     fn new(sequence: u64) -> Self {
     247           20 :         Self {
     248           20 :             version: Self::VERSION_LATEST,
     249           20 :             sequence,
     250           20 :             tenants: HashMap::new(),
     251           20 :             size: 0,
     252           20 :             validated: false,
     253           20 :         }
     254           20 :     }
     255              : 
     256           28 :     fn is_empty(&self) -> bool {
     257           28 :         self.tenants.is_empty()
     258           28 :     }
     259              : 
     260           60 :     fn len(&self) -> usize {
     261           60 :         self.size
     262           60 :     }
     263              : 
     264              :     /// Returns true if the push was accepted, false if the caller must start a new
     265              :     /// deletion list.
     266           14 :     fn push(
     267           14 :         &mut self,
     268           14 :         tenant: &TenantShardId,
     269           14 :         timeline: &TimelineId,
     270           14 :         generation: Generation,
     271           14 :         objects: &mut Vec<RemotePath>,
     272           14 :     ) -> bool {
     273           14 :         if objects.is_empty() {
     274              :             // Avoid inserting an empty TimelineDeletionList: this preserves the property
     275              :             // that if we have no keys, then self.objects is empty (used in Self::is_empty)
     276            0 :             return true;
     277           14 :         }
     278           14 : 
     279           14 :         let tenant_entry = self
     280           14 :             .tenants
     281           14 :             .entry(*tenant)
     282           14 :             .or_insert_with(|| TenantDeletionList {
     283           12 :                 timelines: HashMap::new(),
     284           12 :                 generation,
     285           14 :             });
     286           14 : 
     287           14 :         if tenant_entry.generation != generation {
     288              :             // Only one generation per tenant per list: signal to
     289              :             // caller to start a new list.
     290            2 :             return false;
     291           12 :         }
     292           12 : 
     293           12 :         let timeline_entry = tenant_entry.timelines.entry(*timeline).or_default();
     294           12 : 
     295           12 :         let timeline_remote_path = remote_timeline_path(tenant, timeline);
     296           12 : 
     297           12 :         self.size += objects.len();
     298           12 :         timeline_entry.extend(objects.drain(..).map(|p| {
     299           12 :             p.strip_prefix(&timeline_remote_path)
     300           12 :                 .expect("Timeline paths always start with the timeline prefix")
     301           12 :                 .to_string()
     302           12 :         }));
     303           12 :         true
     304           14 :     }
     305              : 
     306           10 :     fn into_remote_paths(self) -> Vec<RemotePath> {
     307           10 :         let mut result = Vec::new();
     308           10 :         for (tenant, tenant_deletions) in self.tenants.into_iter() {
     309            6 :             for (timeline, timeline_layers) in tenant_deletions.timelines.into_iter() {
     310            6 :                 let timeline_remote_path = remote_timeline_path(&tenant, &timeline);
     311            6 :                 result.extend(
     312            6 :                     timeline_layers
     313            6 :                         .into_iter()
     314            6 :                         .map(|l| timeline_remote_path.join(Utf8PathBuf::from(l))),
     315            6 :                 );
     316            6 :             }
     317              :         }
     318              : 
     319           10 :         result
     320           10 :     }
     321              : 
     322           14 :     async fn save(&self, conf: &'static PageServerConf) -> anyhow::Result<()> {
     323           14 :         let path = conf.deletion_list_path(self.sequence);
     324           14 :         let temp_path = path_with_suffix_extension(&path, TEMP_SUFFIX);
     325           14 : 
     326           14 :         let bytes = serde_json::to_vec(self).expect("Failed to serialize deletion list");
     327           14 : 
     328           14 :         VirtualFile::crashsafe_overwrite(path, temp_path, bytes)
     329           14 :             .await
     330           14 :             .maybe_fatal_err("save deletion list")
     331           14 :             .map_err(Into::into)
     332           14 :     }
     333              : }
     334              : 
     335              : impl std::fmt::Display for DeletionList {
     336            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     337            0 :         write!(
     338            0 :             f,
     339            0 :             "DeletionList<seq={}, tenants={}, keys={}>",
     340            0 :             self.sequence,
     341            0 :             self.tenants.len(),
     342            0 :             self.size
     343            0 :         )
     344            0 :     }
     345              : }
     346              : 
     347              : struct PendingLsn {
     348              :     projected: Lsn,
     349              :     result_slot: Arc<AtomicLsn>,
     350              : }
     351              : 
     352              : struct TenantLsnState {
     353              :     timelines: HashMap<TimelineId, PendingLsn>,
     354              : 
     355              :     // In what generation was the most recent update proposed?
     356              :     generation: Generation,
     357              : }
     358              : 
     359              : #[derive(Default)]
     360              : struct VisibleLsnUpdates {
     361              :     tenants: HashMap<TenantShardId, TenantLsnState>,
     362              : }
     363              : 
     364              : impl VisibleLsnUpdates {
     365          169 :     fn new() -> Self {
     366          169 :         Self {
     367          169 :             tenants: HashMap::new(),
     368          169 :         }
     369          169 :     }
     370              : }
     371              : 
     372              : impl std::fmt::Debug for VisibleLsnUpdates {
     373            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     374            0 :         write!(f, "VisibleLsnUpdates({} tenants)", self.tenants.len())
     375            0 :     }
     376              : }
     377              : 
     378            0 : #[derive(Error, Debug)]
     379              : pub enum DeletionQueueError {
     380              :     #[error("Deletion queue unavailable during shutdown")]
     381              :     ShuttingDown,
     382              : }
     383              : 
     384              : impl DeletionQueueClient {
     385              :     /// This is cancel-safe.  If you drop the future before it completes, the message
     386              :     /// is not pushed, although in the context of the deletion queue it doesn't matter: once
     387              :     /// we decide to do a deletion the decision is always final.
     388          262 :     fn do_push<T>(
     389          262 :         &self,
     390          262 :         queue: &tokio::sync::mpsc::UnboundedSender<T>,
     391          262 :         msg: T,
     392          262 :     ) -> Result<(), DeletionQueueError> {
     393          262 :         match queue.send(msg) {
     394          262 :             Ok(_) => Ok(()),
     395            0 :             Err(e) => {
     396            0 :                 // This shouldn't happen, we should shut down all tenants before
     397            0 :                 // we shut down the global delete queue.  If we encounter a bug like this,
     398            0 :                 // we may leak objects as deletions won't be processed.
     399            0 :                 error!("Deletion queue closed while pushing, shutting down? ({e})");
     400            0 :                 Err(DeletionQueueError::ShuttingDown)
     401              :             }
     402              :         }
     403          262 :     }
     404              : 
     405            8 :     pub(crate) fn recover(
     406            8 :         &self,
     407            8 :         attached_tenants: HashMap<TenantShardId, Generation>,
     408            8 :     ) -> Result<(), DeletionQueueError> {
     409            8 :         self.do_push(
     410            8 :             &self.tx,
     411            8 :             ListWriterQueueMessage::Recover(RecoverOp { attached_tenants }),
     412            8 :         )
     413            8 :     }
     414              : 
     415              :     /// When a Timeline wishes to update the remote_consistent_lsn that it exposes to the outside
     416              :     /// world, it must validate its generation number before doing so.  Rather than do this synchronously,
     417              :     /// we allow the timeline to publish updates at will via this API, and then read back what LSN was most
     418              :     /// recently validated separately.
     419              :     ///
     420              :     /// In this function we publish the LSN to the `projected` field of the timeline's entry in the VisibleLsnUpdates.  The
     421              :     /// backend will later wake up and notice that the tenant's generation requires validation.
     422         1351 :     pub(crate) async fn update_remote_consistent_lsn(
     423         1351 :         &self,
     424         1351 :         tenant_shard_id: TenantShardId,
     425         1351 :         timeline_id: TimelineId,
     426         1351 :         current_generation: Generation,
     427         1351 :         lsn: Lsn,
     428         1351 :         result_slot: Arc<AtomicLsn>,
     429         1351 :     ) {
     430         1351 :         let mut locked = self
     431         1351 :             .lsn_table
     432         1351 :             .write()
     433         1351 :             .expect("Lock should never be poisoned");
     434         1351 : 
     435         1351 :         let tenant_entry = locked
     436         1351 :             .tenants
     437         1351 :             .entry(tenant_shard_id)
     438         1351 :             .or_insert(TenantLsnState {
     439         1351 :                 timelines: HashMap::new(),
     440         1351 :                 generation: current_generation,
     441         1351 :             });
     442         1351 : 
     443         1351 :         if tenant_entry.generation != current_generation {
     444            0 :             // Generation might have changed if we were detached and then re-attached: in this case,
     445            0 :             // state from the previous generation cannot be trusted.
     446            0 :             tenant_entry.timelines.clear();
     447            0 :             tenant_entry.generation = current_generation;
     448         1351 :         }
     449              : 
     450         1351 :         tenant_entry.timelines.insert(
     451         1351 :             timeline_id,
     452         1351 :             PendingLsn {
     453         1351 :                 projected: lsn,
     454         1351 :                 result_slot,
     455         1351 :             },
     456         1351 :         );
     457         1351 :     }
     458              : 
     459              :     /// Submit a list of layers for deletion: this function will return before the deletion is
     460              :     /// persistent, but it may be executed at any time after this function enters: do not push
     461              :     /// layers until you're sure they can be deleted safely (i.e. remote metadata no longer
     462              :     /// references them).
     463              :     ///
     464              :     /// The `current_generation` is the generation of this pageserver's current attachment.  The
     465              :     /// generations in `layers` are the generations in which those layers were written.
     466          230 :     pub(crate) async fn push_layers(
     467          230 :         &self,
     468          230 :         tenant_shard_id: TenantShardId,
     469          230 :         timeline_id: TimelineId,
     470          230 :         current_generation: Generation,
     471          230 :         layers: Vec<(LayerName, LayerFileMetadata)>,
     472          230 :     ) -> Result<(), DeletionQueueError> {
     473          230 :         if current_generation.is_none() {
     474            0 :             debug!("Enqueuing deletions in legacy mode, skipping queue");
     475              : 
     476            0 :             let mut layer_paths = Vec::new();
     477            0 :             for (layer, meta) in layers {
     478            0 :                 layer_paths.push(remote_layer_path(
     479            0 :                     &tenant_shard_id.tenant_id,
     480            0 :                     &timeline_id,
     481            0 :                     meta.shard,
     482            0 :                     &layer,
     483            0 :                     meta.generation,
     484            0 :                 ));
     485            0 :             }
     486            0 :             self.push_immediate(layer_paths).await?;
     487            0 :             return self.flush_immediate().await;
     488          230 :         }
     489          230 : 
     490          230 :         self.push_layers_sync(tenant_shard_id, timeline_id, current_generation, layers)
     491          230 :     }
     492              : 
     493              :     /// When a Tenant has a generation, push_layers is always synchronous because
     494              :     /// the ListValidator channel is an unbounded channel.
     495              :     ///
     496              :     /// This can be merged into push_layers when we remove the Generation-less mode
     497              :     /// support (`<https://github.com/neondatabase/neon/issues/5395>`)
     498          230 :     pub(crate) fn push_layers_sync(
     499          230 :         &self,
     500          230 :         tenant_shard_id: TenantShardId,
     501          230 :         timeline_id: TimelineId,
     502          230 :         current_generation: Generation,
     503          230 :         layers: Vec<(LayerName, LayerFileMetadata)>,
     504          230 :     ) -> Result<(), DeletionQueueError> {
     505          230 :         metrics::DELETION_QUEUE
     506          230 :             .keys_submitted
     507          230 :             .inc_by(layers.len() as u64);
     508          230 :         self.do_push(
     509          230 :             &self.tx,
     510          230 :             ListWriterQueueMessage::Delete(DeletionOp {
     511          230 :                 tenant_shard_id,
     512          230 :                 timeline_id,
     513          230 :                 layers,
     514          230 :                 generation: current_generation,
     515          230 :                 objects: Vec::new(),
     516          230 :             }),
     517          230 :         )
     518          230 :     }
     519              : 
     520              :     /// This is cancel-safe.  If you drop the future the flush may still happen in the background.
     521           24 :     async fn do_flush<T>(
     522           24 :         &self,
     523           24 :         queue: &tokio::sync::mpsc::UnboundedSender<T>,
     524           24 :         msg: T,
     525           24 :         rx: tokio::sync::oneshot::Receiver<()>,
     526           24 :     ) -> Result<(), DeletionQueueError> {
     527           24 :         self.do_push(queue, msg)?;
     528           24 :         if rx.await.is_err() {
     529              :             // This shouldn't happen if tenants are shut down before deletion queue.  If we
     530              :             // encounter a bug like this, then a flusher will incorrectly believe it has flushed
     531              :             // when it hasn't, possibly leading to leaking objects.
     532            0 :             error!("Deletion queue dropped flush op while client was still waiting");
     533            0 :             Err(DeletionQueueError::ShuttingDown)
     534              :         } else {
     535           24 :             Ok(())
     536              :         }
     537           24 :     }
     538              : 
     539              :     /// Wait until all previous deletions are persistent (either executed, or written to a DeletionList)
     540              :     ///
     541              :     /// This is cancel-safe.  If you drop the future the flush may still happen in the background.
     542           14 :     pub async fn flush(&self) -> Result<(), DeletionQueueError> {
     543           14 :         let (flush_op, rx) = FlushOp::new();
     544           14 :         self.do_flush(&self.tx, ListWriterQueueMessage::Flush(flush_op), rx)
     545           14 :             .await
     546           14 :     }
     547              : 
     548              :     /// Issue a flush without waiting for it to complete.  This is useful on advisory flushes where
     549              :     /// the caller wants to avoid the risk of waiting for lots of enqueued work, such as on tenant
     550              :     /// detach where flushing is nice but not necessary.
     551              :     ///
     552              :     /// This function provides no guarantees of work being done.
     553            0 :     pub fn flush_advisory(&self) {
     554            0 :         let (flush_op, _) = FlushOp::new();
     555            0 : 
     556            0 :         // Transmit the flush message, ignoring any result (such as a closed channel during shutdown).
     557            0 :         drop(self.tx.send(ListWriterQueueMessage::FlushExecute(flush_op)));
     558            0 :     }
     559              : 
     560              :     // Wait until all previous deletions are executed
     561           10 :     pub(crate) async fn flush_execute(&self) -> Result<(), DeletionQueueError> {
     562           10 :         debug!("flush_execute: flushing to deletion lists...");
     563              :         // Flush any buffered work to deletion lists
     564           10 :         self.flush().await?;
     565              : 
     566              :         // Flush the backend into the executor of deletion lists
     567           10 :         let (flush_op, rx) = FlushOp::new();
     568           10 :         debug!("flush_execute: flushing backend...");
     569           10 :         self.do_flush(&self.tx, ListWriterQueueMessage::FlushExecute(flush_op), rx)
     570           10 :             .await?;
     571           10 :         debug!("flush_execute: finished flushing backend...");
     572              : 
     573              :         // Flush any immediate-mode deletions (the above backend flush will only flush
     574              :         // the executor if deletions had flowed through the backend)
     575           10 :         debug!("flush_execute: flushing execution...");
     576           10 :         self.flush_immediate().await?;
     577           10 :         debug!("flush_execute: finished flushing execution...");
     578           10 :         Ok(())
     579           10 :     }
     580              : 
     581              :     /// This interface bypasses the persistent deletion queue, and any validation
     582              :     /// that this pageserver is still elegible to execute the deletions.  It is for
     583              :     /// use in timeline deletions, where the control plane is telling us we may
     584              :     /// delete everything in the timeline.
     585              :     ///
     586              :     /// DO NOT USE THIS FROM GC OR COMPACTION CODE.  Use the regular `push_layers`.
     587            0 :     pub(crate) async fn push_immediate(
     588            0 :         &self,
     589            0 :         objects: Vec<RemotePath>,
     590            0 :     ) -> Result<(), DeletionQueueError> {
     591            0 :         metrics::DELETION_QUEUE
     592            0 :             .keys_submitted
     593            0 :             .inc_by(objects.len() as u64);
     594            0 :         self.executor_tx
     595            0 :             .send(DeleterMessage::Delete(objects))
     596            0 :             .await
     597            0 :             .map_err(|_| DeletionQueueError::ShuttingDown)
     598            0 :     }
     599              : 
     600              :     /// Companion to push_immediate.  When this returns Ok, all prior objects sent
     601              :     /// into push_immediate have been deleted from remote storage.
     602           10 :     pub(crate) async fn flush_immediate(&self) -> Result<(), DeletionQueueError> {
     603           10 :         let (flush_op, rx) = FlushOp::new();
     604           10 :         self.executor_tx
     605           10 :             .send(DeleterMessage::Flush(flush_op))
     606            0 :             .await
     607           10 :             .map_err(|_| DeletionQueueError::ShuttingDown)?;
     608              : 
     609           10 :         rx.await.map_err(|_| DeletionQueueError::ShuttingDown)
     610           10 :     }
     611              : }
     612              : 
     613              : impl DeletionQueue {
     614            8 :     pub fn new_client(&self) -> DeletionQueueClient {
     615            8 :         self.client.clone()
     616            8 :     }
     617              : 
     618              :     /// Caller may use the returned object to construct clients with new_client.
     619              :     /// Caller should tokio::spawn the background() members of the two worker objects returned:
     620              :     /// we don't spawn those inside new() so that the caller can use their runtime/spans of choice.
     621              :     ///
     622              :     /// If remote_storage is None, then the returned workers will also be None.
     623            8 :     pub fn new<C>(
     624            8 :         remote_storage: GenericRemoteStorage,
     625            8 :         control_plane_client: Option<C>,
     626            8 :         conf: &'static PageServerConf,
     627            8 :     ) -> (Self, Option<DeletionQueueWorkers<C>>)
     628            8 :     where
     629            8 :         C: ControlPlaneGenerationsApi + Send + Sync,
     630            8 :     {
     631            8 :         // Unbounded channel: enables non-async functions to submit deletions.  The actual length is
     632            8 :         // constrained by how promptly the ListWriter wakes up and drains it, which should be frequent
     633            8 :         // enough to avoid this taking pathologically large amount of memory.
     634            8 :         let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
     635            8 : 
     636            8 :         // Shallow channel: it carries DeletionLists which each contain up to thousands of deletions
     637            8 :         let (backend_tx, backend_rx) = tokio::sync::mpsc::channel(16);
     638            8 : 
     639            8 :         // Shallow channel: it carries lists of paths, and we expect the main queueing to
     640            8 :         // happen in the backend (persistent), not in this queue.
     641            8 :         let (executor_tx, executor_rx) = tokio::sync::mpsc::channel(16);
     642            8 : 
     643            8 :         let lsn_table = Arc::new(std::sync::RwLock::new(VisibleLsnUpdates::new()));
     644            8 : 
     645            8 :         // The deletion queue has an independent cancellation token to
     646            8 :         // the general pageserver shutdown token, because it stays alive a bit
     647            8 :         // longer to flush after Tenants have all been torn down.
     648            8 :         let cancel = CancellationToken::new();
     649            8 : 
     650            8 :         (
     651            8 :             Self {
     652            8 :                 client: DeletionQueueClient {
     653            8 :                     tx,
     654            8 :                     executor_tx: executor_tx.clone(),
     655            8 :                     lsn_table: lsn_table.clone(),
     656            8 :                 },
     657            8 :                 cancel: cancel.clone(),
     658            8 :             },
     659            8 :             Some(DeletionQueueWorkers {
     660            8 :                 frontend: ListWriter::new(conf, rx, backend_tx, cancel.clone()),
     661            8 :                 backend: Validator::new(
     662            8 :                     conf,
     663            8 :                     backend_rx,
     664            8 :                     executor_tx,
     665            8 :                     control_plane_client,
     666            8 :                     lsn_table.clone(),
     667            8 :                     cancel.clone(),
     668            8 :                 ),
     669            8 :                 executor: Deleter::new(remote_storage, executor_rx, cancel.clone()),
     670            8 :             }),
     671            8 :         )
     672            8 :     }
     673              : 
     674            0 :     pub async fn shutdown(&mut self, timeout: Duration) {
     675            0 :         match tokio::time::timeout(timeout, self.client.flush()).await {
     676              :             Ok(Ok(())) => {
     677            0 :                 tracing::info!("Deletion queue flushed successfully on shutdown")
     678              :             }
     679              :             Ok(Err(DeletionQueueError::ShuttingDown)) => {
     680              :                 // This is not harmful for correctness, but is unexpected: the deletion
     681              :                 // queue's workers should stay alive as long as there are any client handles instantiated.
     682            0 :                 tracing::warn!("Deletion queue stopped prematurely");
     683              :             }
     684            0 :             Err(_timeout) => {
     685            0 :                 tracing::warn!("Timed out flushing deletion queue on shutdown")
     686              :             }
     687              :         }
     688              : 
     689              :         // We only cancel _after_ flushing: otherwise we would be shutting down the
     690              :         // components that do the flush.
     691            0 :         self.cancel.cancel();
     692            0 :     }
     693              : }
     694              : 
     695              : #[cfg(test)]
     696              : mod test {
     697              :     use camino::Utf8Path;
     698              :     use hex_literal::hex;
     699              :     use pageserver_api::{shard::ShardIndex, upcall_api::ReAttachResponseTenant};
     700              :     use std::{io::ErrorKind, time::Duration};
     701              :     use tracing::info;
     702              : 
     703              :     use remote_storage::{RemoteStorageConfig, RemoteStorageKind};
     704              :     use tokio::task::JoinHandle;
     705              : 
     706              :     use crate::{
     707              :         control_plane_client::RetryForeverError,
     708              :         repository::Key,
     709              :         tenant::{harness::TenantHarness, storage_layer::DeltaLayerName},
     710              :     };
     711              : 
     712              :     use super::*;
     713              :     pub const TIMELINE_ID: TimelineId =
     714              :         TimelineId::from_array(hex!("11223344556677881122334455667788"));
     715              : 
     716              :     pub const EXAMPLE_LAYER_NAME: LayerName = LayerName::Delta(DeltaLayerName {
     717              :         key_range: Key::from_i128(0x0)..Key::from_i128(0xFFFFFFFFFFFFFFFF),
     718              :         lsn_range: Lsn(0x00000000016B59D8)..Lsn(0x00000000016B5A51),
     719              :     });
     720              : 
     721              :     // When you need a second layer in a test.
     722              :     pub const EXAMPLE_LAYER_NAME_ALT: LayerName = LayerName::Delta(DeltaLayerName {
     723              :         key_range: Key::from_i128(0x0)..Key::from_i128(0xFFFFFFFFFFFFFFFF),
     724              :         lsn_range: Lsn(0x00000000016B5A51)..Lsn(0x00000000016B5A61),
     725              :     });
     726              : 
     727              :     struct TestSetup {
     728              :         harness: TenantHarness,
     729              :         remote_fs_dir: Utf8PathBuf,
     730              :         storage: GenericRemoteStorage,
     731              :         mock_control_plane: MockControlPlane,
     732              :         deletion_queue: DeletionQueue,
     733              :         worker_join: JoinHandle<()>,
     734              :     }
     735              : 
     736              :     impl TestSetup {
     737              :         /// Simulate a pageserver restart by destroying and recreating the deletion queue
     738            2 :         async fn restart(&mut self) {
     739            2 :             let (deletion_queue, workers) = DeletionQueue::new(
     740            2 :                 self.storage.clone(),
     741            2 :                 Some(self.mock_control_plane.clone()),
     742            2 :                 self.harness.conf,
     743            2 :             );
     744            2 : 
     745            2 :             tracing::debug!("Spawning worker for new queue queue");
     746            2 :             let worker_join = workers
     747            2 :                 .unwrap()
     748            2 :                 .spawn_with(&tokio::runtime::Handle::current());
     749            2 : 
     750            2 :             let old_worker_join = std::mem::replace(&mut self.worker_join, worker_join);
     751            2 :             let old_deletion_queue = std::mem::replace(&mut self.deletion_queue, deletion_queue);
     752            2 : 
     753            2 :             tracing::debug!("Joining worker from previous queue");
     754            2 :             old_deletion_queue.cancel.cancel();
     755            2 :             old_worker_join
     756            2 :                 .await
     757            2 :                 .expect("Failed to join workers for previous deletion queue");
     758            2 :         }
     759              : 
     760            6 :         fn set_latest_generation(&self, gen: Generation) {
     761            6 :             let tenant_shard_id = self.harness.tenant_shard_id;
     762            6 :             self.mock_control_plane
     763            6 :                 .latest_generation
     764            6 :                 .lock()
     765            6 :                 .unwrap()
     766            6 :                 .insert(tenant_shard_id, gen);
     767            6 :         }
     768              : 
     769              :         /// Returns remote layer file name, suitable for use in assert_remote_files
     770            6 :         fn write_remote_layer(
     771            6 :             &self,
     772            6 :             file_name: LayerName,
     773            6 :             gen: Generation,
     774            6 :         ) -> anyhow::Result<String> {
     775            6 :             let tenant_shard_id = self.harness.tenant_shard_id;
     776            6 :             let relative_remote_path = remote_timeline_path(&tenant_shard_id, &TIMELINE_ID);
     777            6 :             let remote_timeline_path = self.remote_fs_dir.join(relative_remote_path.get_path());
     778            6 :             std::fs::create_dir_all(&remote_timeline_path)?;
     779            6 :             let remote_layer_file_name = format!("{}{}", file_name, gen.get_suffix());
     780            6 : 
     781            6 :             let content: Vec<u8> = format!("placeholder contents of {file_name}").into();
     782            6 : 
     783            6 :             std::fs::write(
     784            6 :                 remote_timeline_path.join(remote_layer_file_name.clone()),
     785            6 :                 content,
     786            6 :             )?;
     787              : 
     788            6 :             Ok(remote_layer_file_name)
     789            6 :         }
     790              :     }
     791              : 
     792              :     #[derive(Debug, Clone)]
     793              :     struct MockControlPlane {
     794              :         pub latest_generation: std::sync::Arc<std::sync::Mutex<HashMap<TenantShardId, Generation>>>,
     795              :     }
     796              : 
     797              :     impl MockControlPlane {
     798            6 :         fn new() -> Self {
     799            6 :             Self {
     800            6 :                 latest_generation: Arc::default(),
     801            6 :             }
     802            6 :         }
     803              :     }
     804              : 
     805              :     impl ControlPlaneGenerationsApi for MockControlPlane {
     806            0 :         async fn re_attach(
     807            0 :             &self,
     808            0 :             _conf: &PageServerConf,
     809            0 :         ) -> Result<HashMap<TenantShardId, ReAttachResponseTenant>, RetryForeverError> {
     810            0 :             unimplemented!()
     811              :         }
     812              : 
     813            8 :         async fn validate(
     814            8 :             &self,
     815            8 :             tenants: Vec<(TenantShardId, Generation)>,
     816            8 :         ) -> Result<HashMap<TenantShardId, bool>, RetryForeverError> {
     817            8 :             let mut result = HashMap::new();
     818            8 : 
     819            8 :             let latest_generation = self.latest_generation.lock().unwrap();
     820              : 
     821           16 :             for (tenant_shard_id, generation) in tenants {
     822            8 :                 if let Some(latest) = latest_generation.get(&tenant_shard_id) {
     823            8 :                     result.insert(tenant_shard_id, *latest == generation);
     824            8 :                 }
     825              :             }
     826              : 
     827            8 :             Ok(result)
     828            8 :         }
     829              :     }
     830              : 
     831            6 :     fn setup(test_name: &str) -> anyhow::Result<TestSetup> {
     832            6 :         let test_name = Box::leak(Box::new(format!("deletion_queue__{test_name}")));
     833            6 :         let harness = TenantHarness::create(test_name)?;
     834              : 
     835              :         // We do not load() the harness: we only need its config and remote_storage
     836              : 
     837              :         // Set up a GenericRemoteStorage targetting a directory
     838            6 :         let remote_fs_dir = harness.conf.workdir.join("remote_fs");
     839            6 :         std::fs::create_dir_all(remote_fs_dir)?;
     840            6 :         let remote_fs_dir = harness.conf.workdir.join("remote_fs").canonicalize_utf8()?;
     841            6 :         let storage_config = RemoteStorageConfig {
     842            6 :             storage: RemoteStorageKind::LocalFs {
     843            6 :                 local_path: remote_fs_dir.clone(),
     844            6 :             },
     845            6 :             timeout: RemoteStorageConfig::DEFAULT_TIMEOUT,
     846            6 :         };
     847            6 :         let storage = GenericRemoteStorage::from_config(&storage_config).unwrap();
     848            6 : 
     849            6 :         let mock_control_plane = MockControlPlane::new();
     850            6 : 
     851            6 :         let (deletion_queue, worker) = DeletionQueue::new(
     852            6 :             storage.clone(),
     853            6 :             Some(mock_control_plane.clone()),
     854            6 :             harness.conf,
     855            6 :         );
     856            6 : 
     857            6 :         let worker = worker.unwrap();
     858            6 :         let worker_join = worker.spawn_with(&tokio::runtime::Handle::current());
     859            6 : 
     860            6 :         Ok(TestSetup {
     861            6 :             harness,
     862            6 :             remote_fs_dir,
     863            6 :             storage,
     864            6 :             mock_control_plane,
     865            6 :             deletion_queue,
     866            6 :             worker_join,
     867            6 :         })
     868            6 :     }
     869              : 
     870              :     // TODO: put this in a common location so that we can share with remote_timeline_client's tests
     871           18 :     fn assert_remote_files(expected: &[&str], remote_path: &Utf8Path) {
     872           18 :         let mut expected: Vec<String> = expected.iter().map(|x| String::from(*x)).collect();
     873           18 :         expected.sort();
     874           18 : 
     875           18 :         let mut found: Vec<String> = Vec::new();
     876           18 :         let dir = match std::fs::read_dir(remote_path) {
     877           18 :             Ok(d) => d,
     878            0 :             Err(e) => {
     879            0 :                 if e.kind() == ErrorKind::NotFound {
     880            0 :                     if expected.is_empty() {
     881              :                         // We are asserting prefix is empty: it is expected that the dir is missing
     882            0 :                         return;
     883              :                     } else {
     884            0 :                         assert_eq!(expected, Vec::<String>::new());
     885            0 :                         unreachable!();
     886              :                     }
     887              :                 } else {
     888            0 :                     panic!("Unexpected error listing {remote_path}: {e}");
     889              :                 }
     890              :             }
     891              :         };
     892              : 
     893           18 :         for entry in dir.flatten() {
     894           16 :             let entry_name = entry.file_name();
     895           16 :             let fname = entry_name.to_str().unwrap();
     896           16 :             found.push(String::from(fname));
     897           16 :         }
     898           18 :         found.sort();
     899           18 : 
     900           18 :         assert_eq!(expected, found);
     901           18 :     }
     902              : 
     903           10 :     fn assert_local_files(expected: &[&str], directory: &Utf8Path) {
     904           10 :         let dir = match std::fs::read_dir(directory) {
     905            8 :             Ok(d) => d,
     906              :             Err(_) => {
     907            2 :                 assert_eq!(expected, &Vec::<String>::new());
     908            2 :                 return;
     909              :             }
     910              :         };
     911            8 :         let mut found = Vec::new();
     912           18 :         for dentry in dir {
     913           10 :             let dentry = dentry.unwrap();
     914           10 :             let file_name = dentry.file_name();
     915           10 :             let file_name_str = file_name.to_string_lossy();
     916           10 :             found.push(file_name_str.to_string());
     917           10 :         }
     918            8 :         found.sort();
     919            8 :         assert_eq!(expected, found);
     920           10 :     }
     921              : 
     922              :     #[tokio::test]
     923            2 :     async fn deletion_queue_smoke() -> anyhow::Result<()> {
     924            2 :         // Basic test that the deletion queue processes the deletions we pass into it
     925            2 :         let ctx = setup("deletion_queue_smoke").expect("Failed test setup");
     926            2 :         let client = ctx.deletion_queue.new_client();
     927            2 :         client.recover(HashMap::new())?;
     928            2 : 
     929            2 :         let layer_file_name_1: LayerName = "000000000000000000000000000000000000-FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF__00000000016B59D8-00000000016B5A51".parse().unwrap();
     930            2 :         let tenant_shard_id = ctx.harness.tenant_shard_id;
     931            2 : 
     932            2 :         let content: Vec<u8> = "victim1 contents".into();
     933            2 :         let relative_remote_path = remote_timeline_path(&tenant_shard_id, &TIMELINE_ID);
     934            2 :         let remote_timeline_path = ctx.remote_fs_dir.join(relative_remote_path.get_path());
     935            2 :         let deletion_prefix = ctx.harness.conf.deletion_prefix();
     936            2 : 
     937            2 :         // Exercise the distinction between the generation of the layers
     938            2 :         // we delete, and the generation of the running Tenant.
     939            2 :         let layer_generation = Generation::new(0xdeadbeef);
     940            2 :         let now_generation = Generation::new(0xfeedbeef);
     941            2 :         let layer_metadata =
     942            2 :             LayerFileMetadata::new(0xf00, layer_generation, ShardIndex::unsharded());
     943            2 : 
     944            2 :         let remote_layer_file_name_1 =
     945            2 :             format!("{}{}", layer_file_name_1, layer_generation.get_suffix());
     946            2 : 
     947            2 :         // Set mock control plane state to valid for our generation
     948            2 :         ctx.set_latest_generation(now_generation);
     949            2 : 
     950            2 :         // Inject a victim file to remote storage
     951            2 :         info!("Writing");
     952            2 :         std::fs::create_dir_all(&remote_timeline_path)?;
     953            2 :         std::fs::write(
     954            2 :             remote_timeline_path.join(remote_layer_file_name_1.clone()),
     955            2 :             content,
     956            2 :         )?;
     957            2 :         assert_remote_files(&[&remote_layer_file_name_1], &remote_timeline_path);
     958            2 : 
     959            2 :         // File should still be there after we push it to the queue (we haven't pushed enough to flush anything)
     960            2 :         info!("Pushing");
     961            2 :         client
     962            2 :             .push_layers(
     963            2 :                 tenant_shard_id,
     964            2 :                 TIMELINE_ID,
     965            2 :                 now_generation,
     966            2 :                 [(layer_file_name_1.clone(), layer_metadata)].to_vec(),
     967            2 :             )
     968            2 :             .await?;
     969            2 :         assert_remote_files(&[&remote_layer_file_name_1], &remote_timeline_path);
     970            2 : 
     971            2 :         assert_local_files(&[], &deletion_prefix);
     972            2 : 
     973            2 :         // File should still be there after we write a deletion list (we haven't pushed enough to execute anything)
     974            2 :         info!("Flushing");
     975            2 :         client.flush().await?;
     976            2 :         assert_remote_files(&[&remote_layer_file_name_1], &remote_timeline_path);
     977            2 :         assert_local_files(&["0000000000000001-01.list"], &deletion_prefix);
     978            2 : 
     979            2 :         // File should go away when we execute
     980            2 :         info!("Flush-executing");
     981            6 :         client.flush_execute().await?;
     982            2 :         assert_remote_files(&[], &remote_timeline_path);
     983            2 :         assert_local_files(&["header-01"], &deletion_prefix);
     984            2 : 
     985            2 :         // Flushing on an empty queue should succeed immediately, and not write any lists
     986            2 :         info!("Flush-executing on empty");
     987            6 :         client.flush_execute().await?;
     988            2 :         assert_local_files(&["header-01"], &deletion_prefix);
     989            2 : 
     990            2 :         Ok(())
     991            2 :     }
     992              : 
     993              :     #[tokio::test]
     994            2 :     async fn deletion_queue_validation() -> anyhow::Result<()> {
     995            2 :         let ctx = setup("deletion_queue_validation").expect("Failed test setup");
     996            2 :         let client = ctx.deletion_queue.new_client();
     997            2 :         client.recover(HashMap::new())?;
     998            2 : 
     999            2 :         // Generation that the control plane thinks is current
    1000            2 :         let latest_generation = Generation::new(0xdeadbeef);
    1001            2 :         // Generation that our DeletionQueue thinks the tenant is running with
    1002            2 :         let stale_generation = latest_generation.previous();
    1003            2 :         // Generation that our example layer file was written with
    1004            2 :         let layer_generation = stale_generation.previous();
    1005            2 :         let layer_metadata =
    1006            2 :             LayerFileMetadata::new(0xf00, layer_generation, ShardIndex::unsharded());
    1007            2 : 
    1008            2 :         ctx.set_latest_generation(latest_generation);
    1009            2 : 
    1010            2 :         let tenant_shard_id = ctx.harness.tenant_shard_id;
    1011            2 :         let relative_remote_path = remote_timeline_path(&tenant_shard_id, &TIMELINE_ID);
    1012            2 :         let remote_timeline_path = ctx.remote_fs_dir.join(relative_remote_path.get_path());
    1013            2 : 
    1014            2 :         // Initial state: a remote layer exists
    1015            2 :         let remote_layer_name = ctx.write_remote_layer(EXAMPLE_LAYER_NAME, layer_generation)?;
    1016            2 :         assert_remote_files(&[&remote_layer_name], &remote_timeline_path);
    1017            2 : 
    1018            2 :         tracing::debug!("Pushing...");
    1019            2 :         client
    1020            2 :             .push_layers(
    1021            2 :                 tenant_shard_id,
    1022            2 :                 TIMELINE_ID,
    1023            2 :                 stale_generation,
    1024            2 :                 [(EXAMPLE_LAYER_NAME.clone(), layer_metadata.clone())].to_vec(),
    1025            2 :             )
    1026            2 :             .await?;
    1027            2 : 
    1028            2 :         // We enqueued the operation in a stale generation: it should have failed validation
    1029            2 :         tracing::debug!("Flushing...");
    1030            6 :         tokio::time::timeout(Duration::from_secs(5), client.flush_execute()).await??;
    1031            2 :         assert_remote_files(&[&remote_layer_name], &remote_timeline_path);
    1032            2 : 
    1033            2 :         tracing::debug!("Pushing...");
    1034            2 :         client
    1035            2 :             .push_layers(
    1036            2 :                 tenant_shard_id,
    1037            2 :                 TIMELINE_ID,
    1038            2 :                 latest_generation,
    1039            2 :                 [(EXAMPLE_LAYER_NAME.clone(), layer_metadata.clone())].to_vec(),
    1040            2 :             )
    1041            2 :             .await?;
    1042            2 : 
    1043            2 :         // We enqueued the operation in a fresh generation: it should have passed validation
    1044            2 :         tracing::debug!("Flushing...");
    1045            6 :         tokio::time::timeout(Duration::from_secs(5), client.flush_execute()).await??;
    1046            2 :         assert_remote_files(&[], &remote_timeline_path);
    1047            2 : 
    1048            2 :         Ok(())
    1049            2 :     }
    1050              : 
    1051              :     #[tokio::test]
    1052            2 :     async fn deletion_queue_recovery() -> anyhow::Result<()> {
    1053            2 :         // Basic test that the deletion queue processes the deletions we pass into it
    1054            2 :         let mut ctx = setup("deletion_queue_recovery").expect("Failed test setup");
    1055            2 :         let client = ctx.deletion_queue.new_client();
    1056            2 :         client.recover(HashMap::new())?;
    1057            2 : 
    1058            2 :         let tenant_shard_id = ctx.harness.tenant_shard_id;
    1059            2 : 
    1060            2 :         let relative_remote_path = remote_timeline_path(&tenant_shard_id, &TIMELINE_ID);
    1061            2 :         let remote_timeline_path = ctx.remote_fs_dir.join(relative_remote_path.get_path());
    1062            2 :         let deletion_prefix = ctx.harness.conf.deletion_prefix();
    1063            2 : 
    1064            2 :         let layer_generation = Generation::new(0xdeadbeef);
    1065            2 :         let now_generation = Generation::new(0xfeedbeef);
    1066            2 :         let layer_metadata =
    1067            2 :             LayerFileMetadata::new(0xf00, layer_generation, ShardIndex::unsharded());
    1068            2 : 
    1069            2 :         // Inject a deletion in the generation before generation_now: after restart,
    1070            2 :         // this deletion should _not_ get executed (only the immediately previous
    1071            2 :         // generation gets that treatment)
    1072            2 :         let remote_layer_file_name_historical =
    1073            2 :             ctx.write_remote_layer(EXAMPLE_LAYER_NAME, layer_generation)?;
    1074            2 :         client
    1075            2 :             .push_layers(
    1076            2 :                 tenant_shard_id,
    1077            2 :                 TIMELINE_ID,
    1078            2 :                 now_generation.previous(),
    1079            2 :                 [(EXAMPLE_LAYER_NAME.clone(), layer_metadata.clone())].to_vec(),
    1080            2 :             )
    1081            2 :             .await?;
    1082            2 : 
    1083            2 :         // Inject a deletion in the generation before generation_now: after restart,
    1084            2 :         // this deletion should get executed, because we execute deletions in the
    1085            2 :         // immediately previous generation on the same node.
    1086            2 :         let remote_layer_file_name_previous =
    1087            2 :             ctx.write_remote_layer(EXAMPLE_LAYER_NAME_ALT, layer_generation)?;
    1088            2 :         client
    1089            2 :             .push_layers(
    1090            2 :                 tenant_shard_id,
    1091            2 :                 TIMELINE_ID,
    1092            2 :                 now_generation,
    1093            2 :                 [(EXAMPLE_LAYER_NAME_ALT.clone(), layer_metadata.clone())].to_vec(),
    1094            2 :             )
    1095            2 :             .await?;
    1096            2 : 
    1097            2 :         client.flush().await?;
    1098            2 :         assert_remote_files(
    1099            2 :             &[
    1100            2 :                 &remote_layer_file_name_historical,
    1101            2 :                 &remote_layer_file_name_previous,
    1102            2 :             ],
    1103            2 :             &remote_timeline_path,
    1104            2 :         );
    1105            2 : 
    1106            2 :         // Different generatinos for the same tenant will cause two separate
    1107            2 :         // deletion lists to be emitted.
    1108            2 :         assert_local_files(
    1109            2 :             &["0000000000000001-01.list", "0000000000000002-01.list"],
    1110            2 :             &deletion_prefix,
    1111            2 :         );
    1112            2 : 
    1113            2 :         // Simulate a node restart: the latest generation advances
    1114            2 :         let now_generation = now_generation.next();
    1115            2 :         ctx.set_latest_generation(now_generation);
    1116            2 : 
    1117            2 :         // Restart the deletion queue
    1118            2 :         drop(client);
    1119            2 :         ctx.restart().await;
    1120            2 :         let client = ctx.deletion_queue.new_client();
    1121            2 :         client.recover(HashMap::from([(tenant_shard_id, now_generation)]))?;
    1122            2 : 
    1123            2 :         info!("Flush-executing");
    1124            6 :         client.flush_execute().await?;
    1125            2 :         // The deletion from immediately prior generation was executed, the one from
    1126            2 :         // an older generation was not.
    1127            2 :         assert_remote_files(&[&remote_layer_file_name_historical], &remote_timeline_path);
    1128            2 :         Ok(())
    1129            2 :     }
    1130              : }
    1131              : 
    1132              : /// A lightweight queue which can issue ordinary DeletionQueueClient objects, but doesn't do any persistence
    1133              : /// or coalescing, and doesn't actually execute any deletions unless you call pump() to kick it.
    1134              : #[cfg(test)]
    1135              : pub(crate) mod mock {
    1136              :     use tracing::info;
    1137              : 
    1138              :     use super::*;
    1139              :     use std::sync::atomic::{AtomicUsize, Ordering};
    1140              : 
    1141              :     pub struct ConsumerState {
    1142              :         rx: tokio::sync::mpsc::UnboundedReceiver<ListWriterQueueMessage>,
    1143              :         executor_rx: tokio::sync::mpsc::Receiver<DeleterMessage>,
    1144              :         cancel: CancellationToken,
    1145              :     }
    1146              : 
    1147              :     impl ConsumerState {
    1148            2 :         async fn consume(&mut self, remote_storage: &GenericRemoteStorage) -> usize {
    1149            2 :             let mut executed = 0;
    1150            2 : 
    1151            2 :             info!("Executing all pending deletions");
    1152              : 
    1153              :             // Transform all executor messages to generic frontend messages
    1154            2 :             while let Ok(msg) = self.executor_rx.try_recv() {
    1155            0 :                 match msg {
    1156            0 :                     DeleterMessage::Delete(objects) => {
    1157            0 :                         for path in objects {
    1158            0 :                             match remote_storage.delete(&path, &self.cancel).await {
    1159              :                                 Ok(_) => {
    1160            0 :                                     debug!("Deleted {path}");
    1161              :                                 }
    1162            0 :                                 Err(e) => {
    1163            0 :                                     error!("Failed to delete {path}, leaking object! ({e})");
    1164              :                                 }
    1165              :                             }
    1166            0 :                             executed += 1;
    1167              :                         }
    1168              :                     }
    1169            0 :                     DeleterMessage::Flush(flush_op) => {
    1170            0 :                         flush_op.notify();
    1171            0 :                     }
    1172              :                 }
    1173              :             }
    1174              : 
    1175            4 :             while let Ok(msg) = self.rx.try_recv() {
    1176            2 :                 match msg {
    1177            2 :                     ListWriterQueueMessage::Delete(op) => {
    1178            2 :                         let mut objects = op.objects;
    1179            4 :                         for (layer, meta) in op.layers {
    1180            2 :                             objects.push(remote_layer_path(
    1181            2 :                                 &op.tenant_shard_id.tenant_id,
    1182            2 :                                 &op.timeline_id,
    1183            2 :                                 meta.shard,
    1184            2 :                                 &layer,
    1185            2 :                                 meta.generation,
    1186            2 :                             ));
    1187            2 :                         }
    1188              : 
    1189            4 :                         for path in objects {
    1190            2 :                             info!("Executing deletion {path}");
    1191            2 :                             match remote_storage.delete(&path, &self.cancel).await {
    1192              :                                 Ok(_) => {
    1193            2 :                                     debug!("Deleted {path}");
    1194              :                                 }
    1195            0 :                                 Err(e) => {
    1196            0 :                                     error!("Failed to delete {path}, leaking object! ({e})");
    1197              :                                 }
    1198              :                             }
    1199            2 :                             executed += 1;
    1200              :                         }
    1201              :                     }
    1202            0 :                     ListWriterQueueMessage::Flush(op) => {
    1203            0 :                         op.notify();
    1204            0 :                     }
    1205            0 :                     ListWriterQueueMessage::FlushExecute(op) => {
    1206            0 :                         // We have already executed all prior deletions because mock does them inline
    1207            0 :                         op.notify();
    1208            0 :                     }
    1209            0 :                     ListWriterQueueMessage::Recover(_) => {
    1210            0 :                         // no-op in mock
    1211            0 :                     }
    1212              :                 }
    1213            2 :                 info!("All pending deletions have been executed");
    1214              :             }
    1215              : 
    1216            2 :             executed
    1217            2 :         }
    1218              :     }
    1219              : 
    1220              :     pub struct MockDeletionQueue {
    1221              :         tx: tokio::sync::mpsc::UnboundedSender<ListWriterQueueMessage>,
    1222              :         executor_tx: tokio::sync::mpsc::Sender<DeleterMessage>,
    1223              :         executed: Arc<AtomicUsize>,
    1224              :         remote_storage: Option<GenericRemoteStorage>,
    1225              :         consumer: std::sync::Mutex<ConsumerState>,
    1226              :         lsn_table: Arc<std::sync::RwLock<VisibleLsnUpdates>>,
    1227              :     }
    1228              : 
    1229              :     impl MockDeletionQueue {
    1230          161 :         pub fn new(remote_storage: Option<GenericRemoteStorage>) -> Self {
    1231          161 :             let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
    1232          161 :             let (executor_tx, executor_rx) = tokio::sync::mpsc::channel(16384);
    1233          161 : 
    1234          161 :             let executed = Arc::new(AtomicUsize::new(0));
    1235          161 : 
    1236          161 :             Self {
    1237          161 :                 tx,
    1238          161 :                 executor_tx,
    1239          161 :                 executed,
    1240          161 :                 remote_storage,
    1241          161 :                 consumer: std::sync::Mutex::new(ConsumerState {
    1242          161 :                     rx,
    1243          161 :                     executor_rx,
    1244          161 :                     cancel: CancellationToken::new(),
    1245          161 :                 }),
    1246          161 :                 lsn_table: Arc::new(std::sync::RwLock::new(VisibleLsnUpdates::new())),
    1247          161 :             }
    1248          161 :         }
    1249              : 
    1250              :         #[allow(clippy::await_holding_lock)]
    1251            2 :         pub async fn pump(&self) {
    1252            2 :             if let Some(remote_storage) = &self.remote_storage {
    1253              :                 // Permit holding mutex across await, because this is only ever
    1254              :                 // called once at a time in tests.
    1255            2 :                 let mut locked = self.consumer.lock().unwrap();
    1256            2 :                 let count = locked.consume(remote_storage).await;
    1257            2 :                 self.executed.fetch_add(count, Ordering::Relaxed);
    1258            0 :             }
    1259            2 :         }
    1260              : 
    1261          171 :         pub(crate) fn new_client(&self) -> DeletionQueueClient {
    1262          171 :             DeletionQueueClient {
    1263          171 :                 tx: self.tx.clone(),
    1264          171 :                 executor_tx: self.executor_tx.clone(),
    1265          171 :                 lsn_table: self.lsn_table.clone(),
    1266          171 :             }
    1267          171 :         }
    1268              :     }
    1269              : 
    1270              :     /// Test round-trip serialization/deserialization, and test stability of the format
    1271              :     /// vs. a static expected string for the serialized version.
    1272              :     #[test]
    1273            2 :     fn deletion_list_serialization() -> anyhow::Result<()> {
    1274            2 :         let tenant_id = "ad6c1a56f5680419d3a16ff55d97ec3c"
    1275            2 :             .to_string()
    1276            2 :             .parse::<TenantShardId>()?;
    1277            2 :         let timeline_id = "be322c834ed9e709e63b5c9698691910"
    1278            2 :             .to_string()
    1279            2 :             .parse::<TimelineId>()?;
    1280            2 :         let generation = Generation::new(123);
    1281              : 
    1282            2 :         let object =
    1283            2 :             RemotePath::from_string(&format!("tenants/{tenant_id}/timelines/{timeline_id}/foo"))?;
    1284            2 :         let mut objects = [object].to_vec();
    1285            2 : 
    1286            2 :         let mut example = DeletionList::new(1);
    1287            2 :         example.push(&tenant_id, &timeline_id, generation, &mut objects);
    1288              : 
    1289            2 :         let encoded = serde_json::to_string(&example)?;
    1290              : 
    1291            2 :         let expected = "{\"version\":1,\"sequence\":1,\"tenants\":{\"ad6c1a56f5680419d3a16ff55d97ec3c\":{\"timelines\":{\"be322c834ed9e709e63b5c9698691910\":[\"foo\"]},\"generation\":123}},\"size\":1}".to_string();
    1292            2 :         assert_eq!(encoded, expected);
    1293              : 
    1294            2 :         let decoded = serde_json::from_str::<DeletionList>(&encoded)?;
    1295            2 :         assert_eq!(example, decoded);
    1296              : 
    1297            2 :         Ok(())
    1298            2 :     }
    1299              : }
        

Generated by: LCOV version 2.1-beta