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::controller_upcall_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 16 : pub fn spawn_with(mut self, runtime: &tokio::runtime::Handle) -> tokio::task::JoinHandle<()> {
99 16 : let jh_frontend = runtime.spawn(async move {
100 16 : self.frontend
101 16 : .background()
102 16 : .instrument(tracing::info_span!(parent:None, "deletion frontend"))
103 16 : .await
104 16 : });
105 16 : let jh_backend = runtime.spawn(async move {
106 16 : self.backend
107 16 : .background()
108 16 : .instrument(tracing::info_span!(parent:None, "deletion backend"))
109 16 : .await
110 16 : });
111 16 : let jh_executor = runtime.spawn(async move {
112 16 : self.executor
113 16 : .background()
114 16 : .instrument(tracing::info_span!(parent:None, "deletion executor"))
115 16 : .await
116 16 : });
117 16 :
118 16 : runtime.spawn({
119 16 : async move {
120 16 : jh_frontend.await.expect("error joining frontend worker");
121 4 : jh_backend.await.expect("error joining backend worker");
122 4 : drop(jh_executor.await.expect("error joining executor worker"));
123 16 : }
124 16 : })
125 16 : }
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 84 : fn new() -> (Self, tokio::sync::oneshot::Receiver<()>) {
142 84 : let (tx, rx) = tokio::sync::oneshot::channel::<()>();
143 84 : (Self { tx }, rx)
144 84 : }
145 :
146 88 : fn notify(self) {
147 88 : 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 88 : };
151 88 : }
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 24 : #[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 20 : pub(crate) fn len(&self) -> usize {
176 20 : self.timelines.values().map(|v| v.len()).sum()
177 20 : }
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 48 : #[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 16 : fn new(validated_sequence: u64) -> Self {
225 16 : Self {
226 16 : version: Self::VERSION_LATEST,
227 16 : validated_sequence,
228 16 : }
229 16 : }
230 :
231 16 : async fn save(&self, conf: &'static PageServerConf) -> anyhow::Result<()> {
232 16 : debug!("Saving deletion list header {:?}", self);
233 16 : let header_bytes = serde_json::to_vec(self).context("serialize deletion header")?;
234 16 : let header_path = conf.deletion_header_path();
235 16 : let temp_path = path_with_suffix_extension(&header_path, TEMP_SUFFIX);
236 16 : VirtualFile::crashsafe_overwrite(header_path, temp_path, header_bytes)
237 16 : .await
238 16 : .maybe_fatal_err("save deletion header")?;
239 :
240 16 : Ok(())
241 16 : }
242 : }
243 :
244 : impl DeletionList {
245 : const VERSION_LATEST: u8 = 1;
246 40 : fn new(sequence: u64) -> Self {
247 40 : Self {
248 40 : version: Self::VERSION_LATEST,
249 40 : sequence,
250 40 : tenants: HashMap::new(),
251 40 : size: 0,
252 40 : validated: false,
253 40 : }
254 40 : }
255 :
256 54 : fn is_empty(&self) -> bool {
257 54 : self.tenants.is_empty()
258 54 : }
259 :
260 120 : fn len(&self) -> usize {
261 120 : self.size
262 120 : }
263 :
264 : /// Returns true if the push was accepted, false if the caller must start a new
265 : /// deletion list.
266 28 : fn push(
267 28 : &mut self,
268 28 : tenant: &TenantShardId,
269 28 : timeline: &TimelineId,
270 28 : generation: Generation,
271 28 : objects: &mut Vec<RemotePath>,
272 28 : ) -> bool {
273 28 : 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 28 : }
278 28 :
279 28 : let tenant_entry = self
280 28 : .tenants
281 28 : .entry(*tenant)
282 28 : .or_insert_with(|| TenantDeletionList {
283 24 : timelines: HashMap::new(),
284 24 : generation,
285 28 : });
286 28 :
287 28 : if tenant_entry.generation != generation {
288 : // Only one generation per tenant per list: signal to
289 : // caller to start a new list.
290 4 : return false;
291 24 : }
292 24 :
293 24 : let timeline_entry = tenant_entry.timelines.entry(*timeline).or_default();
294 24 :
295 24 : let timeline_remote_path = remote_timeline_path(tenant, timeline);
296 24 :
297 24 : self.size += objects.len();
298 24 : timeline_entry.extend(objects.drain(..).map(|p| {
299 24 : p.strip_prefix(&timeline_remote_path)
300 24 : .expect("Timeline paths always start with the timeline prefix")
301 24 : .to_string()
302 24 : }));
303 24 : true
304 28 : }
305 :
306 20 : fn into_remote_paths(self) -> Vec<RemotePath> {
307 20 : let mut result = Vec::new();
308 20 : for (tenant, tenant_deletions) in self.tenants.into_iter() {
309 12 : for (timeline, timeline_layers) in tenant_deletions.timelines.into_iter() {
310 12 : let timeline_remote_path = remote_timeline_path(&tenant, &timeline);
311 12 : result.extend(
312 12 : timeline_layers
313 12 : .into_iter()
314 12 : .map(|l| timeline_remote_path.join(Utf8PathBuf::from(l))),
315 12 : );
316 12 : }
317 : }
318 :
319 20 : result
320 20 : }
321 :
322 28 : async fn save(&self, conf: &'static PageServerConf) -> anyhow::Result<()> {
323 28 : let path = conf.deletion_list_path(self.sequence);
324 28 : let temp_path = path_with_suffix_extension(&path, TEMP_SUFFIX);
325 28 :
326 28 : let bytes = serde_json::to_vec(self).expect("Failed to serialize deletion list");
327 28 :
328 28 : VirtualFile::crashsafe_overwrite(path, temp_path, bytes)
329 28 : .await
330 28 : .maybe_fatal_err("save deletion list")
331 28 : .map_err(Into::into)
332 28 : }
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 456 : fn new() -> Self {
366 456 : Self {
367 456 : tenants: HashMap::new(),
368 456 : }
369 456 : }
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 : #[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 755 : fn do_push<T>(
389 755 : &self,
390 755 : queue: &tokio::sync::mpsc::UnboundedSender<T>,
391 755 : msg: T,
392 755 : ) -> Result<(), DeletionQueueError> {
393 755 : match queue.send(msg) {
394 755 : 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 755 : }
404 :
405 16 : pub(crate) fn recover(
406 16 : &self,
407 16 : attached_tenants: HashMap<TenantShardId, Generation>,
408 16 : ) -> Result<(), DeletionQueueError> {
409 16 : self.do_push(
410 16 : &self.tx,
411 16 : ListWriterQueueMessage::Recover(RecoverOp { attached_tenants }),
412 16 : )
413 16 : }
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 2962 : pub(crate) async fn update_remote_consistent_lsn(
423 2962 : &self,
424 2962 : tenant_shard_id: TenantShardId,
425 2962 : timeline_id: TimelineId,
426 2962 : current_generation: Generation,
427 2962 : lsn: Lsn,
428 2962 : result_slot: Arc<AtomicLsn>,
429 2962 : ) {
430 2962 : let mut locked = self
431 2962 : .lsn_table
432 2962 : .write()
433 2962 : .expect("Lock should never be poisoned");
434 2962 :
435 2962 : let tenant_entry = locked
436 2962 : .tenants
437 2962 : .entry(tenant_shard_id)
438 2962 : .or_insert(TenantLsnState {
439 2962 : timelines: HashMap::new(),
440 2962 : generation: current_generation,
441 2962 : });
442 2962 :
443 2962 : 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 2962 : }
449 :
450 2962 : tenant_entry.timelines.insert(
451 2962 : timeline_id,
452 2962 : PendingLsn {
453 2962 : projected: lsn,
454 2962 : result_slot,
455 2962 : },
456 2962 : );
457 2962 : }
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 691 : pub(crate) async fn push_layers(
467 691 : &self,
468 691 : tenant_shard_id: TenantShardId,
469 691 : timeline_id: TimelineId,
470 691 : current_generation: Generation,
471 691 : layers: Vec<(LayerName, LayerFileMetadata)>,
472 691 : ) -> Result<(), DeletionQueueError> {
473 691 : 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 691 : }
489 691 :
490 691 : self.push_layers_sync(tenant_shard_id, timeline_id, current_generation, layers)
491 691 : }
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 691 : pub(crate) fn push_layers_sync(
499 691 : &self,
500 691 : tenant_shard_id: TenantShardId,
501 691 : timeline_id: TimelineId,
502 691 : current_generation: Generation,
503 691 : layers: Vec<(LayerName, LayerFileMetadata)>,
504 691 : ) -> Result<(), DeletionQueueError> {
505 691 : metrics::DELETION_QUEUE
506 691 : .keys_submitted
507 691 : .inc_by(layers.len() as u64);
508 691 : self.do_push(
509 691 : &self.tx,
510 691 : ListWriterQueueMessage::Delete(DeletionOp {
511 691 : tenant_shard_id,
512 691 : timeline_id,
513 691 : layers,
514 691 : generation: current_generation,
515 691 : objects: Vec::new(),
516 691 : }),
517 691 : )
518 691 : }
519 :
520 : /// This is cancel-safe. If you drop the future the flush may still happen in the background.
521 48 : async fn do_flush<T>(
522 48 : &self,
523 48 : queue: &tokio::sync::mpsc::UnboundedSender<T>,
524 48 : msg: T,
525 48 : rx: tokio::sync::oneshot::Receiver<()>,
526 48 : ) -> Result<(), DeletionQueueError> {
527 48 : self.do_push(queue, msg)?;
528 48 : 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 48 : Ok(())
536 : }
537 48 : }
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 28 : pub async fn flush(&self) -> Result<(), DeletionQueueError> {
543 28 : let (flush_op, rx) = FlushOp::new();
544 28 : self.do_flush(&self.tx, ListWriterQueueMessage::Flush(flush_op), rx)
545 28 : .await
546 28 : }
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 20 : pub(crate) async fn flush_execute(&self) -> Result<(), DeletionQueueError> {
562 20 : debug!("flush_execute: flushing to deletion lists...");
563 : // Flush any buffered work to deletion lists
564 20 : self.flush().await?;
565 :
566 : // Flush the backend into the executor of deletion lists
567 20 : let (flush_op, rx) = FlushOp::new();
568 20 : debug!("flush_execute: flushing backend...");
569 20 : self.do_flush(&self.tx, ListWriterQueueMessage::FlushExecute(flush_op), rx)
570 20 : .await?;
571 20 : 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 20 : debug!("flush_execute: flushing execution...");
576 20 : self.flush_immediate().await?;
577 20 : debug!("flush_execute: finished flushing execution...");
578 20 : Ok(())
579 20 : }
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 20 : pub(crate) async fn flush_immediate(&self) -> Result<(), DeletionQueueError> {
603 20 : let (flush_op, rx) = FlushOp::new();
604 20 : self.executor_tx
605 20 : .send(DeleterMessage::Flush(flush_op))
606 20 : .await
607 20 : .map_err(|_| DeletionQueueError::ShuttingDown)?;
608 :
609 20 : rx.await.map_err(|_| DeletionQueueError::ShuttingDown)
610 20 : }
611 : }
612 :
613 : impl DeletionQueue {
614 16 : pub fn new_client(&self) -> DeletionQueueClient {
615 16 : self.client.clone()
616 16 : }
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 16 : pub fn new<C>(
622 16 : remote_storage: GenericRemoteStorage,
623 16 : controller_upcall_client: Option<C>,
624 16 : conf: &'static PageServerConf,
625 16 : ) -> (Self, DeletionQueueWorkers<C>)
626 16 : where
627 16 : C: ControlPlaneGenerationsApi + Send + Sync,
628 16 : {
629 16 : // Unbounded channel: enables non-async functions to submit deletions. The actual length is
630 16 : // constrained by how promptly the ListWriter wakes up and drains it, which should be frequent
631 16 : // enough to avoid this taking pathologically large amount of memory.
632 16 : let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
633 16 :
634 16 : // Shallow channel: it carries DeletionLists which each contain up to thousands of deletions
635 16 : let (backend_tx, backend_rx) = tokio::sync::mpsc::channel(16);
636 16 :
637 16 : // Shallow channel: it carries lists of paths, and we expect the main queueing to
638 16 : // happen in the backend (persistent), not in this queue.
639 16 : let (executor_tx, executor_rx) = tokio::sync::mpsc::channel(16);
640 16 :
641 16 : let lsn_table = Arc::new(std::sync::RwLock::new(VisibleLsnUpdates::new()));
642 16 :
643 16 : // The deletion queue has an independent cancellation token to
644 16 : // the general pageserver shutdown token, because it stays alive a bit
645 16 : // longer to flush after Tenants have all been torn down.
646 16 : let cancel = CancellationToken::new();
647 16 :
648 16 : (
649 16 : Self {
650 16 : client: DeletionQueueClient {
651 16 : tx,
652 16 : executor_tx: executor_tx.clone(),
653 16 : lsn_table: lsn_table.clone(),
654 16 : },
655 16 : cancel: cancel.clone(),
656 16 : },
657 16 : DeletionQueueWorkers {
658 16 : frontend: ListWriter::new(conf, rx, backend_tx, cancel.clone()),
659 16 : backend: Validator::new(
660 16 : conf,
661 16 : backend_rx,
662 16 : executor_tx,
663 16 : controller_upcall_client,
664 16 : lsn_table.clone(),
665 16 : cancel.clone(),
666 16 : ),
667 16 : executor: Deleter::new(remote_storage, executor_rx, cancel.clone()),
668 16 : },
669 16 : )
670 16 : }
671 :
672 0 : pub async fn shutdown(&mut self, timeout: Duration) {
673 0 : match tokio::time::timeout(timeout, self.client.flush()).await {
674 : Ok(Ok(())) => {
675 0 : tracing::info!("Deletion queue flushed successfully on shutdown")
676 : }
677 : Ok(Err(DeletionQueueError::ShuttingDown)) => {
678 : // This is not harmful for correctness, but is unexpected: the deletion
679 : // queue's workers should stay alive as long as there are any client handles instantiated.
680 0 : tracing::warn!("Deletion queue stopped prematurely");
681 : }
682 0 : Err(_timeout) => {
683 0 : tracing::warn!("Timed out flushing deletion queue on shutdown")
684 : }
685 : }
686 :
687 : // We only cancel _after_ flushing: otherwise we would be shutting down the
688 : // components that do the flush.
689 0 : self.cancel.cancel();
690 0 : }
691 : }
692 :
693 : #[cfg(test)]
694 : mod test {
695 : use camino::Utf8Path;
696 : use hex_literal::hex;
697 : use pageserver_api::{key::Key, shard::ShardIndex, upcall_api::ReAttachResponseTenant};
698 : use std::{io::ErrorKind, time::Duration};
699 : use tracing::info;
700 :
701 : use remote_storage::{RemoteStorageConfig, RemoteStorageKind};
702 : use tokio::task::JoinHandle;
703 :
704 : use crate::{
705 : controller_upcall_client::RetryForeverError,
706 : tenant::{harness::TenantHarness, storage_layer::DeltaLayerName},
707 : };
708 :
709 : use super::*;
710 : pub const TIMELINE_ID: TimelineId =
711 : TimelineId::from_array(hex!("11223344556677881122334455667788"));
712 :
713 : pub const EXAMPLE_LAYER_NAME: LayerName = LayerName::Delta(DeltaLayerName {
714 : key_range: Key::from_i128(0x0)..Key::from_i128(0xFFFFFFFFFFFFFFFF),
715 : lsn_range: Lsn(0x00000000016B59D8)..Lsn(0x00000000016B5A51),
716 : });
717 :
718 : // When you need a second layer in a test.
719 : pub const EXAMPLE_LAYER_NAME_ALT: LayerName = LayerName::Delta(DeltaLayerName {
720 : key_range: Key::from_i128(0x0)..Key::from_i128(0xFFFFFFFFFFFFFFFF),
721 : lsn_range: Lsn(0x00000000016B5A51)..Lsn(0x00000000016B5A61),
722 : });
723 :
724 : struct TestSetup {
725 : harness: TenantHarness,
726 : remote_fs_dir: Utf8PathBuf,
727 : storage: GenericRemoteStorage,
728 : mock_control_plane: MockControlPlane,
729 : deletion_queue: DeletionQueue,
730 : worker_join: JoinHandle<()>,
731 : }
732 :
733 : impl TestSetup {
734 : /// Simulate a pageserver restart by destroying and recreating the deletion queue
735 4 : async fn restart(&mut self) {
736 4 : let (deletion_queue, workers) = DeletionQueue::new(
737 4 : self.storage.clone(),
738 4 : Some(self.mock_control_plane.clone()),
739 4 : self.harness.conf,
740 4 : );
741 4 :
742 4 : tracing::debug!("Spawning worker for new queue queue");
743 4 : let worker_join = workers.spawn_with(&tokio::runtime::Handle::current());
744 4 :
745 4 : let old_worker_join = std::mem::replace(&mut self.worker_join, worker_join);
746 4 : let old_deletion_queue = std::mem::replace(&mut self.deletion_queue, deletion_queue);
747 4 :
748 4 : tracing::debug!("Joining worker from previous queue");
749 4 : old_deletion_queue.cancel.cancel();
750 4 : old_worker_join
751 4 : .await
752 4 : .expect("Failed to join workers for previous deletion queue");
753 4 : }
754 :
755 12 : fn set_latest_generation(&self, gen: Generation) {
756 12 : let tenant_shard_id = self.harness.tenant_shard_id;
757 12 : self.mock_control_plane
758 12 : .latest_generation
759 12 : .lock()
760 12 : .unwrap()
761 12 : .insert(tenant_shard_id, gen);
762 12 : }
763 :
764 : /// Returns remote layer file name, suitable for use in assert_remote_files
765 12 : fn write_remote_layer(
766 12 : &self,
767 12 : file_name: LayerName,
768 12 : gen: Generation,
769 12 : ) -> anyhow::Result<String> {
770 12 : let tenant_shard_id = self.harness.tenant_shard_id;
771 12 : let relative_remote_path = remote_timeline_path(&tenant_shard_id, &TIMELINE_ID);
772 12 : let remote_timeline_path = self.remote_fs_dir.join(relative_remote_path.get_path());
773 12 : std::fs::create_dir_all(&remote_timeline_path)?;
774 12 : let remote_layer_file_name = format!("{}{}", file_name, gen.get_suffix());
775 12 :
776 12 : let content: Vec<u8> = format!("placeholder contents of {file_name}").into();
777 12 :
778 12 : std::fs::write(
779 12 : remote_timeline_path.join(remote_layer_file_name.clone()),
780 12 : content,
781 12 : )?;
782 :
783 12 : Ok(remote_layer_file_name)
784 12 : }
785 : }
786 :
787 : #[derive(Debug, Clone)]
788 : struct MockControlPlane {
789 : pub latest_generation: std::sync::Arc<std::sync::Mutex<HashMap<TenantShardId, Generation>>>,
790 : }
791 :
792 : impl MockControlPlane {
793 12 : fn new() -> Self {
794 12 : Self {
795 12 : latest_generation: Arc::default(),
796 12 : }
797 12 : }
798 : }
799 :
800 : impl ControlPlaneGenerationsApi for MockControlPlane {
801 0 : async fn re_attach(
802 0 : &self,
803 0 : _conf: &PageServerConf,
804 0 : ) -> Result<HashMap<TenantShardId, ReAttachResponseTenant>, RetryForeverError> {
805 0 : unimplemented!()
806 : }
807 :
808 16 : async fn validate(
809 16 : &self,
810 16 : tenants: Vec<(TenantShardId, Generation)>,
811 16 : ) -> Result<HashMap<TenantShardId, bool>, RetryForeverError> {
812 16 : let mut result = HashMap::new();
813 16 :
814 16 : let latest_generation = self.latest_generation.lock().unwrap();
815 :
816 32 : for (tenant_shard_id, generation) in tenants {
817 16 : if let Some(latest) = latest_generation.get(&tenant_shard_id) {
818 16 : result.insert(tenant_shard_id, *latest == generation);
819 16 : }
820 : }
821 :
822 16 : Ok(result)
823 16 : }
824 : }
825 :
826 12 : async fn setup(test_name: &str) -> anyhow::Result<TestSetup> {
827 12 : let test_name = Box::leak(Box::new(format!("deletion_queue__{test_name}")));
828 12 : let harness = TenantHarness::create(test_name).await?;
829 :
830 : // We do not load() the harness: we only need its config and remote_storage
831 :
832 : // Set up a GenericRemoteStorage targetting a directory
833 12 : let remote_fs_dir = harness.conf.workdir.join("remote_fs");
834 12 : std::fs::create_dir_all(remote_fs_dir)?;
835 12 : let remote_fs_dir = harness.conf.workdir.join("remote_fs").canonicalize_utf8()?;
836 12 : let storage_config = RemoteStorageConfig {
837 12 : storage: RemoteStorageKind::LocalFs {
838 12 : local_path: remote_fs_dir.clone(),
839 12 : },
840 12 : timeout: RemoteStorageConfig::DEFAULT_TIMEOUT,
841 12 : small_timeout: RemoteStorageConfig::DEFAULT_SMALL_TIMEOUT,
842 12 : };
843 12 : let storage = GenericRemoteStorage::from_config(&storage_config)
844 12 : .await
845 12 : .unwrap();
846 12 :
847 12 : let mock_control_plane = MockControlPlane::new();
848 12 :
849 12 : let (deletion_queue, worker) = DeletionQueue::new(
850 12 : storage.clone(),
851 12 : Some(mock_control_plane.clone()),
852 12 : harness.conf,
853 12 : );
854 12 :
855 12 : let worker_join = worker.spawn_with(&tokio::runtime::Handle::current());
856 12 :
857 12 : Ok(TestSetup {
858 12 : harness,
859 12 : remote_fs_dir,
860 12 : storage,
861 12 : mock_control_plane,
862 12 : deletion_queue,
863 12 : worker_join,
864 12 : })
865 12 : }
866 :
867 : // TODO: put this in a common location so that we can share with remote_timeline_client's tests
868 36 : fn assert_remote_files(expected: &[&str], remote_path: &Utf8Path) {
869 36 : let mut expected: Vec<String> = expected.iter().map(|x| String::from(*x)).collect();
870 36 : expected.sort();
871 36 :
872 36 : let mut found: Vec<String> = Vec::new();
873 36 : let dir = match std::fs::read_dir(remote_path) {
874 36 : Ok(d) => d,
875 0 : Err(e) => {
876 0 : if e.kind() == ErrorKind::NotFound {
877 0 : if expected.is_empty() {
878 : // We are asserting prefix is empty: it is expected that the dir is missing
879 0 : return;
880 : } else {
881 0 : assert_eq!(expected, Vec::<String>::new());
882 0 : unreachable!();
883 : }
884 : } else {
885 0 : panic!("Unexpected error listing {remote_path}: {e}");
886 : }
887 : }
888 : };
889 :
890 36 : for entry in dir.flatten() {
891 32 : let entry_name = entry.file_name();
892 32 : let fname = entry_name.to_str().unwrap();
893 32 : found.push(String::from(fname));
894 32 : }
895 36 : found.sort();
896 36 :
897 36 : assert_eq!(expected, found);
898 36 : }
899 :
900 20 : fn assert_local_files(expected: &[&str], directory: &Utf8Path) {
901 20 : let dir = match std::fs::read_dir(directory) {
902 16 : Ok(d) => d,
903 : Err(_) => {
904 4 : assert_eq!(expected, &Vec::<String>::new());
905 4 : return;
906 : }
907 : };
908 16 : let mut found = Vec::new();
909 36 : for dentry in dir {
910 20 : let dentry = dentry.unwrap();
911 20 : let file_name = dentry.file_name();
912 20 : let file_name_str = file_name.to_string_lossy();
913 20 : found.push(file_name_str.to_string());
914 20 : }
915 16 : found.sort();
916 16 : assert_eq!(expected, found);
917 20 : }
918 :
919 : #[tokio::test]
920 4 : async fn deletion_queue_smoke() -> anyhow::Result<()> {
921 4 : // Basic test that the deletion queue processes the deletions we pass into it
922 4 : let ctx = setup("deletion_queue_smoke")
923 4 : .await
924 4 : .expect("Failed test setup");
925 4 : let client = ctx.deletion_queue.new_client();
926 4 : client.recover(HashMap::new())?;
927 4 :
928 4 : let layer_file_name_1: LayerName = "000000000000000000000000000000000000-FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF__00000000016B59D8-00000000016B5A51".parse().unwrap();
929 4 : let tenant_shard_id = ctx.harness.tenant_shard_id;
930 4 :
931 4 : let content: Vec<u8> = "victim1 contents".into();
932 4 : let relative_remote_path = remote_timeline_path(&tenant_shard_id, &TIMELINE_ID);
933 4 : let remote_timeline_path = ctx.remote_fs_dir.join(relative_remote_path.get_path());
934 4 : let deletion_prefix = ctx.harness.conf.deletion_prefix();
935 4 :
936 4 : // Exercise the distinction between the generation of the layers
937 4 : // we delete, and the generation of the running Tenant.
938 4 : let layer_generation = Generation::new(0xdeadbeef);
939 4 : let now_generation = Generation::new(0xfeedbeef);
940 4 : let layer_metadata =
941 4 : LayerFileMetadata::new(0xf00, layer_generation, ShardIndex::unsharded());
942 4 :
943 4 : let remote_layer_file_name_1 =
944 4 : format!("{}{}", layer_file_name_1, layer_generation.get_suffix());
945 4 :
946 4 : // Set mock control plane state to valid for our generation
947 4 : ctx.set_latest_generation(now_generation);
948 4 :
949 4 : // Inject a victim file to remote storage
950 4 : info!("Writing");
951 4 : std::fs::create_dir_all(&remote_timeline_path)?;
952 4 : std::fs::write(
953 4 : remote_timeline_path.join(remote_layer_file_name_1.clone()),
954 4 : content,
955 4 : )?;
956 4 : assert_remote_files(&[&remote_layer_file_name_1], &remote_timeline_path);
957 4 :
958 4 : // File should still be there after we push it to the queue (we haven't pushed enough to flush anything)
959 4 : info!("Pushing");
960 4 : client
961 4 : .push_layers(
962 4 : tenant_shard_id,
963 4 : TIMELINE_ID,
964 4 : now_generation,
965 4 : [(layer_file_name_1.clone(), layer_metadata)].to_vec(),
966 4 : )
967 4 : .await?;
968 4 : assert_remote_files(&[&remote_layer_file_name_1], &remote_timeline_path);
969 4 :
970 4 : assert_local_files(&[], &deletion_prefix);
971 4 :
972 4 : // File should still be there after we write a deletion list (we haven't pushed enough to execute anything)
973 4 : info!("Flushing");
974 4 : client.flush().await?;
975 4 : assert_remote_files(&[&remote_layer_file_name_1], &remote_timeline_path);
976 4 : assert_local_files(&["0000000000000001-01.list"], &deletion_prefix);
977 4 :
978 4 : // File should go away when we execute
979 4 : info!("Flush-executing");
980 4 : client.flush_execute().await?;
981 4 : assert_remote_files(&[], &remote_timeline_path);
982 4 : assert_local_files(&["header-01"], &deletion_prefix);
983 4 :
984 4 : // Flushing on an empty queue should succeed immediately, and not write any lists
985 4 : info!("Flush-executing on empty");
986 4 : client.flush_execute().await?;
987 4 : assert_local_files(&["header-01"], &deletion_prefix);
988 4 :
989 4 : Ok(())
990 4 : }
991 :
992 : #[tokio::test]
993 4 : async fn deletion_queue_validation() -> anyhow::Result<()> {
994 4 : let ctx = setup("deletion_queue_validation")
995 4 : .await
996 4 : .expect("Failed test setup");
997 4 : let client = ctx.deletion_queue.new_client();
998 4 : client.recover(HashMap::new())?;
999 4 :
1000 4 : // Generation that the control plane thinks is current
1001 4 : let latest_generation = Generation::new(0xdeadbeef);
1002 4 : // Generation that our DeletionQueue thinks the tenant is running with
1003 4 : let stale_generation = latest_generation.previous();
1004 4 : // Generation that our example layer file was written with
1005 4 : let layer_generation = stale_generation.previous();
1006 4 : let layer_metadata =
1007 4 : LayerFileMetadata::new(0xf00, layer_generation, ShardIndex::unsharded());
1008 4 :
1009 4 : ctx.set_latest_generation(latest_generation);
1010 4 :
1011 4 : let tenant_shard_id = ctx.harness.tenant_shard_id;
1012 4 : let relative_remote_path = remote_timeline_path(&tenant_shard_id, &TIMELINE_ID);
1013 4 : let remote_timeline_path = ctx.remote_fs_dir.join(relative_remote_path.get_path());
1014 4 :
1015 4 : // Initial state: a remote layer exists
1016 4 : let remote_layer_name = ctx.write_remote_layer(EXAMPLE_LAYER_NAME, layer_generation)?;
1017 4 : assert_remote_files(&[&remote_layer_name], &remote_timeline_path);
1018 4 :
1019 4 : tracing::debug!("Pushing...");
1020 4 : client
1021 4 : .push_layers(
1022 4 : tenant_shard_id,
1023 4 : TIMELINE_ID,
1024 4 : stale_generation,
1025 4 : [(EXAMPLE_LAYER_NAME.clone(), layer_metadata.clone())].to_vec(),
1026 4 : )
1027 4 : .await?;
1028 4 :
1029 4 : // We enqueued the operation in a stale generation: it should have failed validation
1030 4 : tracing::debug!("Flushing...");
1031 4 : tokio::time::timeout(Duration::from_secs(5), client.flush_execute()).await??;
1032 4 : assert_remote_files(&[&remote_layer_name], &remote_timeline_path);
1033 4 :
1034 4 : tracing::debug!("Pushing...");
1035 4 : client
1036 4 : .push_layers(
1037 4 : tenant_shard_id,
1038 4 : TIMELINE_ID,
1039 4 : latest_generation,
1040 4 : [(EXAMPLE_LAYER_NAME.clone(), layer_metadata.clone())].to_vec(),
1041 4 : )
1042 4 : .await?;
1043 4 :
1044 4 : // We enqueued the operation in a fresh generation: it should have passed validation
1045 4 : tracing::debug!("Flushing...");
1046 4 : tokio::time::timeout(Duration::from_secs(5), client.flush_execute()).await??;
1047 4 : assert_remote_files(&[], &remote_timeline_path);
1048 4 :
1049 4 : Ok(())
1050 4 : }
1051 :
1052 : #[tokio::test]
1053 4 : async fn deletion_queue_recovery() -> anyhow::Result<()> {
1054 4 : // Basic test that the deletion queue processes the deletions we pass into it
1055 4 : let mut ctx = setup("deletion_queue_recovery")
1056 4 : .await
1057 4 : .expect("Failed test setup");
1058 4 : let client = ctx.deletion_queue.new_client();
1059 4 : client.recover(HashMap::new())?;
1060 4 :
1061 4 : let tenant_shard_id = ctx.harness.tenant_shard_id;
1062 4 :
1063 4 : let relative_remote_path = remote_timeline_path(&tenant_shard_id, &TIMELINE_ID);
1064 4 : let remote_timeline_path = ctx.remote_fs_dir.join(relative_remote_path.get_path());
1065 4 : let deletion_prefix = ctx.harness.conf.deletion_prefix();
1066 4 :
1067 4 : let layer_generation = Generation::new(0xdeadbeef);
1068 4 : let now_generation = Generation::new(0xfeedbeef);
1069 4 : let layer_metadata =
1070 4 : LayerFileMetadata::new(0xf00, layer_generation, ShardIndex::unsharded());
1071 4 :
1072 4 : // Inject a deletion in the generation before generation_now: after restart,
1073 4 : // this deletion should _not_ get executed (only the immediately previous
1074 4 : // generation gets that treatment)
1075 4 : let remote_layer_file_name_historical =
1076 4 : ctx.write_remote_layer(EXAMPLE_LAYER_NAME, layer_generation)?;
1077 4 : client
1078 4 : .push_layers(
1079 4 : tenant_shard_id,
1080 4 : TIMELINE_ID,
1081 4 : now_generation.previous(),
1082 4 : [(EXAMPLE_LAYER_NAME.clone(), layer_metadata.clone())].to_vec(),
1083 4 : )
1084 4 : .await?;
1085 4 :
1086 4 : // Inject a deletion in the generation before generation_now: after restart,
1087 4 : // this deletion should get executed, because we execute deletions in the
1088 4 : // immediately previous generation on the same node.
1089 4 : let remote_layer_file_name_previous =
1090 4 : ctx.write_remote_layer(EXAMPLE_LAYER_NAME_ALT, layer_generation)?;
1091 4 : client
1092 4 : .push_layers(
1093 4 : tenant_shard_id,
1094 4 : TIMELINE_ID,
1095 4 : now_generation,
1096 4 : [(EXAMPLE_LAYER_NAME_ALT.clone(), layer_metadata.clone())].to_vec(),
1097 4 : )
1098 4 : .await?;
1099 4 :
1100 4 : client.flush().await?;
1101 4 : assert_remote_files(
1102 4 : &[
1103 4 : &remote_layer_file_name_historical,
1104 4 : &remote_layer_file_name_previous,
1105 4 : ],
1106 4 : &remote_timeline_path,
1107 4 : );
1108 4 :
1109 4 : // Different generatinos for the same tenant will cause two separate
1110 4 : // deletion lists to be emitted.
1111 4 : assert_local_files(
1112 4 : &["0000000000000001-01.list", "0000000000000002-01.list"],
1113 4 : &deletion_prefix,
1114 4 : );
1115 4 :
1116 4 : // Simulate a node restart: the latest generation advances
1117 4 : let now_generation = now_generation.next();
1118 4 : ctx.set_latest_generation(now_generation);
1119 4 :
1120 4 : // Restart the deletion queue
1121 4 : drop(client);
1122 4 : ctx.restart().await;
1123 4 : let client = ctx.deletion_queue.new_client();
1124 4 : client.recover(HashMap::from([(tenant_shard_id, now_generation)]))?;
1125 4 :
1126 4 : info!("Flush-executing");
1127 4 : client.flush_execute().await?;
1128 4 : // The deletion from immediately prior generation was executed, the one from
1129 4 : // an older generation was not.
1130 4 : assert_remote_files(&[&remote_layer_file_name_historical], &remote_timeline_path);
1131 4 : Ok(())
1132 4 : }
1133 : }
1134 :
1135 : /// A lightweight queue which can issue ordinary DeletionQueueClient objects, but doesn't do any persistence
1136 : /// or coalescing, and doesn't actually execute any deletions unless you call pump() to kick it.
1137 : #[cfg(test)]
1138 : pub(crate) mod mock {
1139 : use tracing::info;
1140 :
1141 : use super::*;
1142 : use std::sync::atomic::{AtomicUsize, Ordering};
1143 :
1144 : pub struct ConsumerState {
1145 : rx: tokio::sync::mpsc::UnboundedReceiver<ListWriterQueueMessage>,
1146 : executor_rx: tokio::sync::mpsc::Receiver<DeleterMessage>,
1147 : cancel: CancellationToken,
1148 : executed: Arc<AtomicUsize>,
1149 : }
1150 :
1151 : impl ConsumerState {
1152 440 : async fn consume(&mut self, remote_storage: &GenericRemoteStorage) {
1153 440 : info!("Executing all pending deletions");
1154 :
1155 : // Transform all executor messages to generic frontend messages
1156 1015 : loop {
1157 1015 : use either::Either;
1158 1015 : let msg = tokio::select! {
1159 1015 : left = self.executor_rx.recv() => Either::Left(left),
1160 1015 : right = self.rx.recv() => Either::Right(right),
1161 : };
1162 4 : match msg {
1163 0 : Either::Left(None) => break,
1164 0 : Either::Right(None) => break,
1165 0 : Either::Left(Some(DeleterMessage::Delete(objects))) => {
1166 0 : for path in objects {
1167 0 : match remote_storage.delete(&path, &self.cancel).await {
1168 : Ok(_) => {
1169 0 : debug!("Deleted {path}");
1170 : }
1171 0 : Err(e) => {
1172 0 : error!("Failed to delete {path}, leaking object! ({e})");
1173 : }
1174 : }
1175 0 : self.executed.fetch_add(1, Ordering::Relaxed);
1176 : }
1177 : }
1178 4 : Either::Left(Some(DeleterMessage::Flush(flush_op))) => {
1179 4 : flush_op.notify();
1180 4 : }
1181 582 : Either::Right(Some(ListWriterQueueMessage::Delete(op))) => {
1182 582 : let mut objects = op.objects;
1183 1164 : for (layer, meta) in op.layers {
1184 582 : objects.push(remote_layer_path(
1185 582 : &op.tenant_shard_id.tenant_id,
1186 582 : &op.timeline_id,
1187 582 : meta.shard,
1188 582 : &layer,
1189 582 : meta.generation,
1190 582 : ));
1191 582 : }
1192 :
1193 1153 : for path in objects {
1194 582 : info!("Executing deletion {path}");
1195 582 : match remote_storage.delete(&path, &self.cancel).await {
1196 : Ok(_) => {
1197 571 : debug!("Deleted {path}");
1198 : }
1199 0 : Err(e) => {
1200 0 : error!("Failed to delete {path}, leaking object! ({e})");
1201 : }
1202 : }
1203 571 : self.executed.fetch_add(1, Ordering::Relaxed);
1204 : }
1205 : }
1206 0 : Either::Right(Some(ListWriterQueueMessage::Flush(op))) => {
1207 0 : op.notify();
1208 0 : }
1209 0 : Either::Right(Some(ListWriterQueueMessage::FlushExecute(op))) => {
1210 0 : // We have already executed all prior deletions because mock does them inline
1211 0 : op.notify();
1212 0 : }
1213 0 : Either::Right(Some(ListWriterQueueMessage::Recover(_))) => {
1214 0 : // no-op in mock
1215 0 : }
1216 : }
1217 : }
1218 0 : }
1219 : }
1220 :
1221 : pub struct MockDeletionQueue {
1222 : tx: tokio::sync::mpsc::UnboundedSender<ListWriterQueueMessage>,
1223 : executor_tx: tokio::sync::mpsc::Sender<DeleterMessage>,
1224 : lsn_table: Arc<std::sync::RwLock<VisibleLsnUpdates>>,
1225 : }
1226 :
1227 : impl MockDeletionQueue {
1228 440 : pub fn new(remote_storage: Option<GenericRemoteStorage>) -> Self {
1229 440 : let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
1230 440 : let (executor_tx, executor_rx) = tokio::sync::mpsc::channel(16384);
1231 440 :
1232 440 : let executed = Arc::new(AtomicUsize::new(0));
1233 440 :
1234 440 : let mut consumer = ConsumerState {
1235 440 : rx,
1236 440 : executor_rx,
1237 440 : cancel: CancellationToken::new(),
1238 440 : executed: executed.clone(),
1239 440 : };
1240 440 :
1241 440 : tokio::spawn(async move {
1242 440 : if let Some(remote_storage) = &remote_storage {
1243 440 : consumer.consume(remote_storage).await;
1244 0 : }
1245 440 : });
1246 440 :
1247 440 : Self {
1248 440 : tx,
1249 440 : executor_tx,
1250 440 : lsn_table: Arc::new(std::sync::RwLock::new(VisibleLsnUpdates::new())),
1251 440 : }
1252 440 : }
1253 :
1254 : #[allow(clippy::await_holding_lock)]
1255 4 : pub async fn pump(&self) {
1256 4 : let (tx, rx) = tokio::sync::oneshot::channel();
1257 4 : self.executor_tx
1258 4 : .send(DeleterMessage::Flush(FlushOp { tx }))
1259 4 : .await
1260 4 : .expect("Failed to send flush message");
1261 4 : rx.await.ok();
1262 4 : }
1263 :
1264 460 : pub(crate) fn new_client(&self) -> DeletionQueueClient {
1265 460 : DeletionQueueClient {
1266 460 : tx: self.tx.clone(),
1267 460 : executor_tx: self.executor_tx.clone(),
1268 460 : lsn_table: self.lsn_table.clone(),
1269 460 : }
1270 460 : }
1271 : }
1272 :
1273 : /// Test round-trip serialization/deserialization, and test stability of the format
1274 : /// vs. a static expected string for the serialized version.
1275 : #[test]
1276 4 : fn deletion_list_serialization() -> anyhow::Result<()> {
1277 4 : let tenant_id = "ad6c1a56f5680419d3a16ff55d97ec3c"
1278 4 : .to_string()
1279 4 : .parse::<TenantShardId>()?;
1280 4 : let timeline_id = "be322c834ed9e709e63b5c9698691910"
1281 4 : .to_string()
1282 4 : .parse::<TimelineId>()?;
1283 4 : let generation = Generation::new(123);
1284 :
1285 4 : let object =
1286 4 : RemotePath::from_string(&format!("tenants/{tenant_id}/timelines/{timeline_id}/foo"))?;
1287 4 : let mut objects = [object].to_vec();
1288 4 :
1289 4 : let mut example = DeletionList::new(1);
1290 4 : example.push(&tenant_id, &timeline_id, generation, &mut objects);
1291 :
1292 4 : let encoded = serde_json::to_string(&example)?;
1293 :
1294 4 : let expected = "{\"version\":1,\"sequence\":1,\"tenants\":{\"ad6c1a56f5680419d3a16ff55d97ec3c\":{\"timelines\":{\"be322c834ed9e709e63b5c9698691910\":[\"foo\"]},\"generation\":123}},\"size\":1}".to_string();
1295 4 : assert_eq!(encoded, expected);
1296 :
1297 4 : let decoded = serde_json::from_str::<DeletionList>(&encoded)?;
1298 4 : assert_eq!(example, decoded);
1299 :
1300 4 : Ok(())
1301 4 : }
1302 : }
|