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 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 51 : .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 57 : .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 27 : .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 27 : fn is_empty(&self) -> bool {
257 27 : self.tenants.is_empty()
258 27 : }
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 200 : fn new() -> Self {
366 200 : Self {
367 200 : tenants: HashMap::new(),
368 200 : }
369 200 : }
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 282 : fn do_push<T>(
389 282 : &self,
390 282 : queue: &tokio::sync::mpsc::UnboundedSender<T>,
391 282 : msg: T,
392 282 : ) -> Result<(), DeletionQueueError> {
393 282 : match queue.send(msg) {
394 282 : 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 282 : }
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 1407 : pub(crate) async fn update_remote_consistent_lsn(
423 1407 : &self,
424 1407 : tenant_shard_id: TenantShardId,
425 1407 : timeline_id: TimelineId,
426 1407 : current_generation: Generation,
427 1407 : lsn: Lsn,
428 1407 : result_slot: Arc<AtomicLsn>,
429 1407 : ) {
430 1407 : let mut locked = self
431 1407 : .lsn_table
432 1407 : .write()
433 1407 : .expect("Lock should never be poisoned");
434 1407 :
435 1407 : let tenant_entry = locked
436 1407 : .tenants
437 1407 : .entry(tenant_shard_id)
438 1407 : .or_insert(TenantLsnState {
439 1407 : timelines: HashMap::new(),
440 1407 : generation: current_generation,
441 1407 : });
442 1407 :
443 1407 : 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 1407 : }
449 :
450 1407 : tenant_entry.timelines.insert(
451 1407 : timeline_id,
452 1407 : PendingLsn {
453 1407 : projected: lsn,
454 1407 : result_slot,
455 1407 : },
456 1407 : );
457 1407 : }
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 250 : pub(crate) async fn push_layers(
467 250 : &self,
468 250 : tenant_shard_id: TenantShardId,
469 250 : timeline_id: TimelineId,
470 250 : current_generation: Generation,
471 250 : layers: Vec<(LayerName, LayerFileMetadata)>,
472 250 : ) -> Result<(), DeletionQueueError> {
473 250 : 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 250 : }
489 250 :
490 250 : self.push_layers_sync(tenant_shard_id, timeline_id, current_generation, layers)
491 250 : }
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 250 : pub(crate) fn push_layers_sync(
499 250 : &self,
500 250 : tenant_shard_id: TenantShardId,
501 250 : timeline_id: TimelineId,
502 250 : current_generation: Generation,
503 250 : layers: Vec<(LayerName, LayerFileMetadata)>,
504 250 : ) -> Result<(), DeletionQueueError> {
505 250 : metrics::DELETION_QUEUE
506 250 : .keys_submitted
507 250 : .inc_by(layers.len() as u64);
508 250 : self.do_push(
509 250 : &self.tx,
510 250 : ListWriterQueueMessage::Delete(DeletionOp {
511 250 : tenant_shard_id,
512 250 : timeline_id,
513 250 : layers,
514 250 : generation: current_generation,
515 250 : objects: Vec::new(),
516 250 : }),
517 250 : )
518 250 : }
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 8 : pub fn new<C>(
622 8 : remote_storage: GenericRemoteStorage,
623 8 : controller_upcall_client: Option<C>,
624 8 : conf: &'static PageServerConf,
625 8 : ) -> (Self, DeletionQueueWorkers<C>)
626 8 : where
627 8 : C: ControlPlaneGenerationsApi + Send + Sync,
628 8 : {
629 8 : // Unbounded channel: enables non-async functions to submit deletions. The actual length is
630 8 : // constrained by how promptly the ListWriter wakes up and drains it, which should be frequent
631 8 : // enough to avoid this taking pathologically large amount of memory.
632 8 : let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
633 8 :
634 8 : // Shallow channel: it carries DeletionLists which each contain up to thousands of deletions
635 8 : let (backend_tx, backend_rx) = tokio::sync::mpsc::channel(16);
636 8 :
637 8 : // Shallow channel: it carries lists of paths, and we expect the main queueing to
638 8 : // happen in the backend (persistent), not in this queue.
639 8 : let (executor_tx, executor_rx) = tokio::sync::mpsc::channel(16);
640 8 :
641 8 : let lsn_table = Arc::new(std::sync::RwLock::new(VisibleLsnUpdates::new()));
642 8 :
643 8 : // The deletion queue has an independent cancellation token to
644 8 : // the general pageserver shutdown token, because it stays alive a bit
645 8 : // longer to flush after Tenants have all been torn down.
646 8 : let cancel = CancellationToken::new();
647 8 :
648 8 : (
649 8 : Self {
650 8 : client: DeletionQueueClient {
651 8 : tx,
652 8 : executor_tx: executor_tx.clone(),
653 8 : lsn_table: lsn_table.clone(),
654 8 : },
655 8 : cancel: cancel.clone(),
656 8 : },
657 8 : DeletionQueueWorkers {
658 8 : frontend: ListWriter::new(conf, rx, backend_tx, cancel.clone()),
659 8 : backend: Validator::new(
660 8 : conf,
661 8 : backend_rx,
662 8 : executor_tx,
663 8 : controller_upcall_client,
664 8 : lsn_table.clone(),
665 8 : cancel.clone(),
666 8 : ),
667 8 : executor: Deleter::new(remote_storage, executor_rx, cancel.clone()),
668 8 : },
669 8 : )
670 8 : }
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 2 : async fn restart(&mut self) {
736 2 : let (deletion_queue, workers) = DeletionQueue::new(
737 2 : self.storage.clone(),
738 2 : Some(self.mock_control_plane.clone()),
739 2 : self.harness.conf,
740 2 : );
741 2 :
742 2 : tracing::debug!("Spawning worker for new queue queue");
743 2 : let worker_join = workers.spawn_with(&tokio::runtime::Handle::current());
744 2 :
745 2 : let old_worker_join = std::mem::replace(&mut self.worker_join, worker_join);
746 2 : let old_deletion_queue = std::mem::replace(&mut self.deletion_queue, deletion_queue);
747 2 :
748 2 : tracing::debug!("Joining worker from previous queue");
749 2 : old_deletion_queue.cancel.cancel();
750 2 : old_worker_join
751 2 : .await
752 2 : .expect("Failed to join workers for previous deletion queue");
753 2 : }
754 :
755 6 : fn set_latest_generation(&self, gen: Generation) {
756 6 : let tenant_shard_id = self.harness.tenant_shard_id;
757 6 : self.mock_control_plane
758 6 : .latest_generation
759 6 : .lock()
760 6 : .unwrap()
761 6 : .insert(tenant_shard_id, gen);
762 6 : }
763 :
764 : /// Returns remote layer file name, suitable for use in assert_remote_files
765 6 : fn write_remote_layer(
766 6 : &self,
767 6 : file_name: LayerName,
768 6 : gen: Generation,
769 6 : ) -> anyhow::Result<String> {
770 6 : let tenant_shard_id = self.harness.tenant_shard_id;
771 6 : let relative_remote_path = remote_timeline_path(&tenant_shard_id, &TIMELINE_ID);
772 6 : let remote_timeline_path = self.remote_fs_dir.join(relative_remote_path.get_path());
773 6 : std::fs::create_dir_all(&remote_timeline_path)?;
774 6 : let remote_layer_file_name = format!("{}{}", file_name, gen.get_suffix());
775 6 :
776 6 : let content: Vec<u8> = format!("placeholder contents of {file_name}").into();
777 6 :
778 6 : std::fs::write(
779 6 : remote_timeline_path.join(remote_layer_file_name.clone()),
780 6 : content,
781 6 : )?;
782 :
783 6 : Ok(remote_layer_file_name)
784 6 : }
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 6 : fn new() -> Self {
794 6 : Self {
795 6 : latest_generation: Arc::default(),
796 6 : }
797 6 : }
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 8 : async fn validate(
809 8 : &self,
810 8 : tenants: Vec<(TenantShardId, Generation)>,
811 8 : ) -> Result<HashMap<TenantShardId, bool>, RetryForeverError> {
812 8 : let mut result = HashMap::new();
813 8 :
814 8 : let latest_generation = self.latest_generation.lock().unwrap();
815 :
816 16 : for (tenant_shard_id, generation) in tenants {
817 8 : if let Some(latest) = latest_generation.get(&tenant_shard_id) {
818 8 : result.insert(tenant_shard_id, *latest == generation);
819 8 : }
820 : }
821 :
822 8 : Ok(result)
823 8 : }
824 : }
825 :
826 6 : async fn setup(test_name: &str) -> anyhow::Result<TestSetup> {
827 6 : let test_name = Box::leak(Box::new(format!("deletion_queue__{test_name}")));
828 6 : 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 6 : let remote_fs_dir = harness.conf.workdir.join("remote_fs");
834 6 : std::fs::create_dir_all(remote_fs_dir)?;
835 6 : let remote_fs_dir = harness.conf.workdir.join("remote_fs").canonicalize_utf8()?;
836 6 : let storage_config = RemoteStorageConfig {
837 6 : storage: RemoteStorageKind::LocalFs {
838 6 : local_path: remote_fs_dir.clone(),
839 6 : },
840 6 : timeout: RemoteStorageConfig::DEFAULT_TIMEOUT,
841 6 : };
842 6 : let storage = GenericRemoteStorage::from_config(&storage_config)
843 0 : .await
844 6 : .unwrap();
845 6 :
846 6 : let mock_control_plane = MockControlPlane::new();
847 6 :
848 6 : let (deletion_queue, worker) = DeletionQueue::new(
849 6 : storage.clone(),
850 6 : Some(mock_control_plane.clone()),
851 6 : harness.conf,
852 6 : );
853 6 :
854 6 : let worker_join = worker.spawn_with(&tokio::runtime::Handle::current());
855 6 :
856 6 : Ok(TestSetup {
857 6 : harness,
858 6 : remote_fs_dir,
859 6 : storage,
860 6 : mock_control_plane,
861 6 : deletion_queue,
862 6 : worker_join,
863 6 : })
864 6 : }
865 :
866 : // TODO: put this in a common location so that we can share with remote_timeline_client's tests
867 18 : fn assert_remote_files(expected: &[&str], remote_path: &Utf8Path) {
868 18 : let mut expected: Vec<String> = expected.iter().map(|x| String::from(*x)).collect();
869 18 : expected.sort();
870 18 :
871 18 : let mut found: Vec<String> = Vec::new();
872 18 : let dir = match std::fs::read_dir(remote_path) {
873 18 : Ok(d) => d,
874 0 : Err(e) => {
875 0 : if e.kind() == ErrorKind::NotFound {
876 0 : if expected.is_empty() {
877 : // We are asserting prefix is empty: it is expected that the dir is missing
878 0 : return;
879 : } else {
880 0 : assert_eq!(expected, Vec::<String>::new());
881 0 : unreachable!();
882 : }
883 : } else {
884 0 : panic!("Unexpected error listing {remote_path}: {e}");
885 : }
886 : }
887 : };
888 :
889 18 : for entry in dir.flatten() {
890 16 : let entry_name = entry.file_name();
891 16 : let fname = entry_name.to_str().unwrap();
892 16 : found.push(String::from(fname));
893 16 : }
894 18 : found.sort();
895 18 :
896 18 : assert_eq!(expected, found);
897 18 : }
898 :
899 10 : fn assert_local_files(expected: &[&str], directory: &Utf8Path) {
900 10 : let dir = match std::fs::read_dir(directory) {
901 8 : Ok(d) => d,
902 : Err(_) => {
903 2 : assert_eq!(expected, &Vec::<String>::new());
904 2 : return;
905 : }
906 : };
907 8 : let mut found = Vec::new();
908 18 : for dentry in dir {
909 10 : let dentry = dentry.unwrap();
910 10 : let file_name = dentry.file_name();
911 10 : let file_name_str = file_name.to_string_lossy();
912 10 : found.push(file_name_str.to_string());
913 10 : }
914 8 : found.sort();
915 8 : assert_eq!(expected, found);
916 10 : }
917 :
918 : #[tokio::test]
919 2 : async fn deletion_queue_smoke() -> anyhow::Result<()> {
920 2 : // Basic test that the deletion queue processes the deletions we pass into it
921 2 : let ctx = setup("deletion_queue_smoke")
922 2 : .await
923 2 : .expect("Failed test setup");
924 2 : let client = ctx.deletion_queue.new_client();
925 2 : client.recover(HashMap::new())?;
926 2 :
927 2 : let layer_file_name_1: LayerName = "000000000000000000000000000000000000-FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF__00000000016B59D8-00000000016B5A51".parse().unwrap();
928 2 : let tenant_shard_id = ctx.harness.tenant_shard_id;
929 2 :
930 2 : let content: Vec<u8> = "victim1 contents".into();
931 2 : let relative_remote_path = remote_timeline_path(&tenant_shard_id, &TIMELINE_ID);
932 2 : let remote_timeline_path = ctx.remote_fs_dir.join(relative_remote_path.get_path());
933 2 : let deletion_prefix = ctx.harness.conf.deletion_prefix();
934 2 :
935 2 : // Exercise the distinction between the generation of the layers
936 2 : // we delete, and the generation of the running Tenant.
937 2 : let layer_generation = Generation::new(0xdeadbeef);
938 2 : let now_generation = Generation::new(0xfeedbeef);
939 2 : let layer_metadata =
940 2 : LayerFileMetadata::new(0xf00, layer_generation, ShardIndex::unsharded());
941 2 :
942 2 : let remote_layer_file_name_1 =
943 2 : format!("{}{}", layer_file_name_1, layer_generation.get_suffix());
944 2 :
945 2 : // Set mock control plane state to valid for our generation
946 2 : ctx.set_latest_generation(now_generation);
947 2 :
948 2 : // Inject a victim file to remote storage
949 2 : info!("Writing");
950 2 : std::fs::create_dir_all(&remote_timeline_path)?;
951 2 : std::fs::write(
952 2 : remote_timeline_path.join(remote_layer_file_name_1.clone()),
953 2 : content,
954 2 : )?;
955 2 : assert_remote_files(&[&remote_layer_file_name_1], &remote_timeline_path);
956 2 :
957 2 : // File should still be there after we push it to the queue (we haven't pushed enough to flush anything)
958 2 : info!("Pushing");
959 2 : client
960 2 : .push_layers(
961 2 : tenant_shard_id,
962 2 : TIMELINE_ID,
963 2 : now_generation,
964 2 : [(layer_file_name_1.clone(), layer_metadata)].to_vec(),
965 2 : )
966 2 : .await?;
967 2 : assert_remote_files(&[&remote_layer_file_name_1], &remote_timeline_path);
968 2 :
969 2 : assert_local_files(&[], &deletion_prefix);
970 2 :
971 2 : // File should still be there after we write a deletion list (we haven't pushed enough to execute anything)
972 2 : info!("Flushing");
973 2 : client.flush().await?;
974 2 : assert_remote_files(&[&remote_layer_file_name_1], &remote_timeline_path);
975 2 : assert_local_files(&["0000000000000001-01.list"], &deletion_prefix);
976 2 :
977 2 : // File should go away when we execute
978 2 : info!("Flush-executing");
979 6 : client.flush_execute().await?;
980 2 : assert_remote_files(&[], &remote_timeline_path);
981 2 : assert_local_files(&["header-01"], &deletion_prefix);
982 2 :
983 2 : // Flushing on an empty queue should succeed immediately, and not write any lists
984 2 : info!("Flush-executing on empty");
985 6 : client.flush_execute().await?;
986 2 : assert_local_files(&["header-01"], &deletion_prefix);
987 2 :
988 2 : Ok(())
989 2 : }
990 :
991 : #[tokio::test]
992 2 : async fn deletion_queue_validation() -> anyhow::Result<()> {
993 2 : let ctx = setup("deletion_queue_validation")
994 2 : .await
995 2 : .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")
1055 2 : .await
1056 2 : .expect("Failed test setup");
1057 2 : let client = ctx.deletion_queue.new_client();
1058 2 : client.recover(HashMap::new())?;
1059 2 :
1060 2 : let tenant_shard_id = ctx.harness.tenant_shard_id;
1061 2 :
1062 2 : let relative_remote_path = remote_timeline_path(&tenant_shard_id, &TIMELINE_ID);
1063 2 : let remote_timeline_path = ctx.remote_fs_dir.join(relative_remote_path.get_path());
1064 2 : let deletion_prefix = ctx.harness.conf.deletion_prefix();
1065 2 :
1066 2 : let layer_generation = Generation::new(0xdeadbeef);
1067 2 : let now_generation = Generation::new(0xfeedbeef);
1068 2 : let layer_metadata =
1069 2 : LayerFileMetadata::new(0xf00, layer_generation, ShardIndex::unsharded());
1070 2 :
1071 2 : // Inject a deletion in the generation before generation_now: after restart,
1072 2 : // this deletion should _not_ get executed (only the immediately previous
1073 2 : // generation gets that treatment)
1074 2 : let remote_layer_file_name_historical =
1075 2 : ctx.write_remote_layer(EXAMPLE_LAYER_NAME, layer_generation)?;
1076 2 : client
1077 2 : .push_layers(
1078 2 : tenant_shard_id,
1079 2 : TIMELINE_ID,
1080 2 : now_generation.previous(),
1081 2 : [(EXAMPLE_LAYER_NAME.clone(), layer_metadata.clone())].to_vec(),
1082 2 : )
1083 2 : .await?;
1084 2 :
1085 2 : // Inject a deletion in the generation before generation_now: after restart,
1086 2 : // this deletion should get executed, because we execute deletions in the
1087 2 : // immediately previous generation on the same node.
1088 2 : let remote_layer_file_name_previous =
1089 2 : ctx.write_remote_layer(EXAMPLE_LAYER_NAME_ALT, layer_generation)?;
1090 2 : client
1091 2 : .push_layers(
1092 2 : tenant_shard_id,
1093 2 : TIMELINE_ID,
1094 2 : now_generation,
1095 2 : [(EXAMPLE_LAYER_NAME_ALT.clone(), layer_metadata.clone())].to_vec(),
1096 2 : )
1097 2 : .await?;
1098 2 :
1099 2 : client.flush().await?;
1100 2 : assert_remote_files(
1101 2 : &[
1102 2 : &remote_layer_file_name_historical,
1103 2 : &remote_layer_file_name_previous,
1104 2 : ],
1105 2 : &remote_timeline_path,
1106 2 : );
1107 2 :
1108 2 : // Different generatinos for the same tenant will cause two separate
1109 2 : // deletion lists to be emitted.
1110 2 : assert_local_files(
1111 2 : &["0000000000000001-01.list", "0000000000000002-01.list"],
1112 2 : &deletion_prefix,
1113 2 : );
1114 2 :
1115 2 : // Simulate a node restart: the latest generation advances
1116 2 : let now_generation = now_generation.next();
1117 2 : ctx.set_latest_generation(now_generation);
1118 2 :
1119 2 : // Restart the deletion queue
1120 2 : drop(client);
1121 2 : ctx.restart().await;
1122 2 : let client = ctx.deletion_queue.new_client();
1123 2 : client.recover(HashMap::from([(tenant_shard_id, now_generation)]))?;
1124 2 :
1125 2 : info!("Flush-executing");
1126 6 : client.flush_execute().await?;
1127 2 : // The deletion from immediately prior generation was executed, the one from
1128 2 : // an older generation was not.
1129 2 : assert_remote_files(&[&remote_layer_file_name_historical], &remote_timeline_path);
1130 2 : Ok(())
1131 2 : }
1132 : }
1133 :
1134 : /// A lightweight queue which can issue ordinary DeletionQueueClient objects, but doesn't do any persistence
1135 : /// or coalescing, and doesn't actually execute any deletions unless you call pump() to kick it.
1136 : #[cfg(test)]
1137 : pub(crate) mod mock {
1138 : use tracing::info;
1139 :
1140 : use super::*;
1141 : use std::sync::atomic::{AtomicUsize, Ordering};
1142 :
1143 : pub struct ConsumerState {
1144 : rx: tokio::sync::mpsc::UnboundedReceiver<ListWriterQueueMessage>,
1145 : executor_rx: tokio::sync::mpsc::Receiver<DeleterMessage>,
1146 : cancel: CancellationToken,
1147 : }
1148 :
1149 : impl ConsumerState {
1150 2 : async fn consume(&mut self, remote_storage: &GenericRemoteStorage) -> usize {
1151 2 : let mut executed = 0;
1152 2 :
1153 2 : info!("Executing all pending deletions");
1154 :
1155 : // Transform all executor messages to generic frontend messages
1156 2 : while let Ok(msg) = self.executor_rx.try_recv() {
1157 0 : match msg {
1158 0 : DeleterMessage::Delete(objects) => {
1159 0 : for path in objects {
1160 0 : match remote_storage.delete(&path, &self.cancel).await {
1161 : Ok(_) => {
1162 0 : debug!("Deleted {path}");
1163 : }
1164 0 : Err(e) => {
1165 0 : error!("Failed to delete {path}, leaking object! ({e})");
1166 : }
1167 : }
1168 0 : executed += 1;
1169 : }
1170 : }
1171 0 : DeleterMessage::Flush(flush_op) => {
1172 0 : flush_op.notify();
1173 0 : }
1174 : }
1175 : }
1176 :
1177 4 : while let Ok(msg) = self.rx.try_recv() {
1178 2 : match msg {
1179 2 : ListWriterQueueMessage::Delete(op) => {
1180 2 : let mut objects = op.objects;
1181 4 : for (layer, meta) in op.layers {
1182 2 : objects.push(remote_layer_path(
1183 2 : &op.tenant_shard_id.tenant_id,
1184 2 : &op.timeline_id,
1185 2 : meta.shard,
1186 2 : &layer,
1187 2 : meta.generation,
1188 2 : ));
1189 2 : }
1190 :
1191 4 : for path in objects {
1192 2 : info!("Executing deletion {path}");
1193 2 : match remote_storage.delete(&path, &self.cancel).await {
1194 : Ok(_) => {
1195 2 : debug!("Deleted {path}");
1196 : }
1197 0 : Err(e) => {
1198 0 : error!("Failed to delete {path}, leaking object! ({e})");
1199 : }
1200 : }
1201 2 : executed += 1;
1202 : }
1203 : }
1204 0 : ListWriterQueueMessage::Flush(op) => {
1205 0 : op.notify();
1206 0 : }
1207 0 : ListWriterQueueMessage::FlushExecute(op) => {
1208 0 : // We have already executed all prior deletions because mock does them inline
1209 0 : op.notify();
1210 0 : }
1211 0 : ListWriterQueueMessage::Recover(_) => {
1212 0 : // no-op in mock
1213 0 : }
1214 : }
1215 2 : info!("All pending deletions have been executed");
1216 : }
1217 :
1218 2 : executed
1219 2 : }
1220 : }
1221 :
1222 : pub struct MockDeletionQueue {
1223 : tx: tokio::sync::mpsc::UnboundedSender<ListWriterQueueMessage>,
1224 : executor_tx: tokio::sync::mpsc::Sender<DeleterMessage>,
1225 : executed: Arc<AtomicUsize>,
1226 : remote_storage: Option<GenericRemoteStorage>,
1227 : consumer: std::sync::Mutex<ConsumerState>,
1228 : lsn_table: Arc<std::sync::RwLock<VisibleLsnUpdates>>,
1229 : }
1230 :
1231 : impl MockDeletionQueue {
1232 192 : pub fn new(remote_storage: Option<GenericRemoteStorage>) -> Self {
1233 192 : let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
1234 192 : let (executor_tx, executor_rx) = tokio::sync::mpsc::channel(16384);
1235 192 :
1236 192 : let executed = Arc::new(AtomicUsize::new(0));
1237 192 :
1238 192 : Self {
1239 192 : tx,
1240 192 : executor_tx,
1241 192 : executed,
1242 192 : remote_storage,
1243 192 : consumer: std::sync::Mutex::new(ConsumerState {
1244 192 : rx,
1245 192 : executor_rx,
1246 192 : cancel: CancellationToken::new(),
1247 192 : }),
1248 192 : lsn_table: Arc::new(std::sync::RwLock::new(VisibleLsnUpdates::new())),
1249 192 : }
1250 192 : }
1251 :
1252 : #[allow(clippy::await_holding_lock)]
1253 2 : pub async fn pump(&self) {
1254 2 : if let Some(remote_storage) = &self.remote_storage {
1255 : // Permit holding mutex across await, because this is only ever
1256 : // called once at a time in tests.
1257 2 : let mut locked = self.consumer.lock().unwrap();
1258 2 : let count = locked.consume(remote_storage).await;
1259 2 : self.executed.fetch_add(count, Ordering::Relaxed);
1260 0 : }
1261 2 : }
1262 :
1263 202 : pub(crate) fn new_client(&self) -> DeletionQueueClient {
1264 202 : DeletionQueueClient {
1265 202 : tx: self.tx.clone(),
1266 202 : executor_tx: self.executor_tx.clone(),
1267 202 : lsn_table: self.lsn_table.clone(),
1268 202 : }
1269 202 : }
1270 : }
1271 :
1272 : /// Test round-trip serialization/deserialization, and test stability of the format
1273 : /// vs. a static expected string for the serialized version.
1274 : #[test]
1275 2 : fn deletion_list_serialization() -> anyhow::Result<()> {
1276 2 : let tenant_id = "ad6c1a56f5680419d3a16ff55d97ec3c"
1277 2 : .to_string()
1278 2 : .parse::<TenantShardId>()?;
1279 2 : let timeline_id = "be322c834ed9e709e63b5c9698691910"
1280 2 : .to_string()
1281 2 : .parse::<TimelineId>()?;
1282 2 : let generation = Generation::new(123);
1283 :
1284 2 : let object =
1285 2 : RemotePath::from_string(&format!("tenants/{tenant_id}/timelines/{timeline_id}/foo"))?;
1286 2 : let mut objects = [object].to_vec();
1287 2 :
1288 2 : let mut example = DeletionList::new(1);
1289 2 : example.push(&tenant_id, &timeline_id, generation, &mut objects);
1290 :
1291 2 : let encoded = serde_json::to_string(&example)?;
1292 :
1293 2 : let expected = "{\"version\":1,\"sequence\":1,\"tenants\":{\"ad6c1a56f5680419d3a16ff55d97ec3c\":{\"timelines\":{\"be322c834ed9e709e63b5c9698691910\":[\"foo\"]},\"generation\":123}},\"size\":1}".to_string();
1294 2 : assert_eq!(encoded, expected);
1295 :
1296 2 : let decoded = serde_json::from_str::<DeletionList>(&encoded)?;
1297 2 : assert_eq!(example, decoded);
1298 :
1299 2 : Ok(())
1300 2 : }
1301 : }
|