Line data Source code
1 : use std::sync::Arc;
2 :
3 : use anyhow::Context;
4 : use camino::{Utf8Path, Utf8PathBuf};
5 : use pageserver_api::{models::TenantState, shard::TenantShardId};
6 : use remote_storage::{GenericRemoteStorage, RemotePath, TimeoutOrCancel};
7 : use tokio::sync::OwnedMutexGuard;
8 : use tokio_util::sync::CancellationToken;
9 : use tracing::{error, instrument, Instrument};
10 :
11 : use utils::{backoff, completion, crashsafe, fs_ext, id::TimelineId};
12 :
13 : use crate::{
14 : config::PageServerConf,
15 : context::RequestContext,
16 : task_mgr::{self, TaskKind},
17 : tenant::{
18 : mgr::{TenantSlot, TenantsMapRemoveResult},
19 : timeline::ShutdownMode,
20 : },
21 : };
22 :
23 : use super::{
24 : mgr::{GetTenantError, TenantSlotError, TenantSlotUpsertError, TenantsMap},
25 : remote_timeline_client::{FAILED_REMOTE_OP_RETRIES, FAILED_UPLOAD_WARN_THRESHOLD},
26 : span,
27 : timeline::delete::DeleteTimelineFlow,
28 : tree_sort_timelines, DeleteTimelineError, Tenant, TenantPreload,
29 : };
30 :
31 0 : #[derive(Debug, thiserror::Error)]
32 : pub(crate) enum DeleteTenantError {
33 : #[error("GetTenant {0}")]
34 : Get(#[from] GetTenantError),
35 :
36 : #[error("Tenant not attached")]
37 : NotAttached,
38 :
39 : #[error("Invalid state {0}. Expected Active or Broken")]
40 : InvalidState(TenantState),
41 :
42 : #[error("Tenant deletion is already in progress")]
43 : AlreadyInProgress,
44 :
45 : #[error("Tenant map slot error {0}")]
46 : SlotError(#[from] TenantSlotError),
47 :
48 : #[error("Tenant map slot upsert error {0}")]
49 : SlotUpsertError(#[from] TenantSlotUpsertError),
50 :
51 : #[error("Timeline {0}")]
52 : Timeline(#[from] DeleteTimelineError),
53 :
54 : #[error("Cancelled")]
55 : Cancelled,
56 :
57 : #[error(transparent)]
58 : Other(#[from] anyhow::Error),
59 : }
60 :
61 : type DeletionGuard = tokio::sync::OwnedMutexGuard<DeleteTenantFlow>;
62 :
63 0 : fn remote_tenant_delete_mark_path(
64 0 : conf: &PageServerConf,
65 0 : tenant_shard_id: &TenantShardId,
66 0 : ) -> anyhow::Result<RemotePath> {
67 0 : let tenant_remote_path = conf
68 0 : .tenant_path(tenant_shard_id)
69 0 : .strip_prefix(&conf.workdir)
70 0 : .context("Failed to strip workdir prefix")
71 0 : .and_then(RemotePath::new)
72 0 : .context("tenant path")?;
73 0 : Ok(tenant_remote_path.join(Utf8Path::new("timelines/deleted")))
74 0 : }
75 :
76 0 : async fn create_remote_delete_mark(
77 0 : conf: &PageServerConf,
78 0 : remote_storage: &GenericRemoteStorage,
79 0 : tenant_shard_id: &TenantShardId,
80 0 : cancel: &CancellationToken,
81 0 : ) -> Result<(), DeleteTenantError> {
82 0 : let remote_mark_path = remote_tenant_delete_mark_path(conf, tenant_shard_id)?;
83 :
84 0 : let data: &[u8] = &[];
85 0 : backoff::retry(
86 0 : || async {
87 0 : let data = bytes::Bytes::from_static(data);
88 0 : let stream = futures::stream::once(futures::future::ready(Ok(data)));
89 0 : remote_storage
90 0 : .upload(stream, 0, &remote_mark_path, None, cancel)
91 0 : .await
92 0 : },
93 0 : TimeoutOrCancel::caused_by_cancel,
94 0 : FAILED_UPLOAD_WARN_THRESHOLD,
95 0 : FAILED_REMOTE_OP_RETRIES,
96 0 : "mark_upload",
97 0 : cancel,
98 0 : )
99 0 : .await
100 0 : .ok_or_else(|| anyhow::Error::new(TimeoutOrCancel::Cancel))
101 0 : .and_then(|x| x)
102 0 : .context("mark_upload")?;
103 :
104 0 : Ok(())
105 0 : }
106 :
107 0 : async fn create_local_delete_mark(
108 0 : conf: &PageServerConf,
109 0 : tenant_shard_id: &TenantShardId,
110 0 : ) -> Result<(), DeleteTenantError> {
111 0 : let marker_path = conf.tenant_deleted_mark_file_path(tenant_shard_id);
112 0 :
113 0 : // Note: we're ok to replace existing file.
114 0 : let _ = std::fs::OpenOptions::new()
115 0 : .write(true)
116 0 : .create(true)
117 0 : .truncate(true)
118 0 : .open(&marker_path)
119 0 : .with_context(|| format!("could not create delete marker file {marker_path:?}"))?;
120 :
121 0 : crashsafe::fsync_file_and_parent(&marker_path).context("sync_mark")?;
122 :
123 0 : Ok(())
124 0 : }
125 :
126 0 : async fn schedule_ordered_timeline_deletions(
127 0 : tenant: &Arc<Tenant>,
128 0 : ) -> Result<Vec<(Arc<tokio::sync::Mutex<DeleteTimelineFlow>>, TimelineId)>, DeleteTenantError> {
129 0 : // Tenant is stopping at this point. We know it will be deleted.
130 0 : // No new timelines should be created.
131 0 : // Tree sort timelines to delete from leafs to the root.
132 0 : // NOTE: by calling clone we release the mutex which creates a possibility for a race: pending deletion
133 0 : // can complete and remove timeline from the map in between our call to clone
134 0 : // and `DeleteTimelineFlow::run`, so `run` wont find timeline in `timelines` map.
135 0 : // timelines.lock is currently synchronous so we cant hold it across await point.
136 0 : // So just ignore NotFound error if we get it from `run`.
137 0 : // Beware: in case it becomes async and we try to hold it here, `run` also locks it, which can create a deadlock.
138 0 : let timelines = tenant.timelines.lock().unwrap().clone();
139 0 : let sorted =
140 0 : tree_sort_timelines(timelines, |t| t.get_ancestor_timeline_id()).context("tree sort")?;
141 :
142 0 : let mut already_running_deletions = vec![];
143 :
144 0 : for (timeline_id, _) in sorted.into_iter().rev() {
145 0 : let span = tracing::info_span!("timeline_delete", %timeline_id);
146 0 : let res = DeleteTimelineFlow::run(tenant, timeline_id, true)
147 0 : .instrument(span)
148 0 : .await;
149 0 : if let Err(e) = res {
150 0 : match e {
151 : DeleteTimelineError::NotFound => {
152 : // Timeline deletion finished after call to clone above but before call
153 : // to `DeleteTimelineFlow::run` and removed timeline from the map.
154 0 : continue;
155 : }
156 0 : DeleteTimelineError::AlreadyInProgress(guard) => {
157 0 : already_running_deletions.push((guard, timeline_id));
158 0 : continue;
159 : }
160 0 : e => return Err(DeleteTenantError::Timeline(e)),
161 : }
162 0 : }
163 : }
164 :
165 0 : Ok(already_running_deletions)
166 0 : }
167 :
168 0 : async fn ensure_timelines_dir_empty(timelines_path: &Utf8Path) -> Result<(), DeleteTenantError> {
169 0 : // Assert timelines dir is empty.
170 0 : if !fs_ext::is_directory_empty(timelines_path).await? {
171 : // Display first 10 items in directory
172 0 : let list = fs_ext::list_dir(timelines_path).await.context("list_dir")?;
173 0 : let list = &list.into_iter().take(10).collect::<Vec<_>>();
174 0 : return Err(DeleteTenantError::Other(anyhow::anyhow!(
175 0 : "Timelines directory is not empty after all timelines deletion: {list:?}"
176 0 : )));
177 0 : }
178 0 :
179 0 : Ok(())
180 0 : }
181 :
182 0 : async fn remove_tenant_remote_delete_mark(
183 0 : conf: &PageServerConf,
184 0 : remote_storage: Option<&GenericRemoteStorage>,
185 0 : tenant_shard_id: &TenantShardId,
186 0 : cancel: &CancellationToken,
187 0 : ) -> Result<(), DeleteTenantError> {
188 0 : if let Some(remote_storage) = remote_storage {
189 0 : let path = remote_tenant_delete_mark_path(conf, tenant_shard_id)?;
190 0 : backoff::retry(
191 0 : || async { remote_storage.delete(&path, cancel).await },
192 0 : TimeoutOrCancel::caused_by_cancel,
193 0 : FAILED_UPLOAD_WARN_THRESHOLD,
194 0 : FAILED_REMOTE_OP_RETRIES,
195 0 : "remove_tenant_remote_delete_mark",
196 0 : cancel,
197 0 : )
198 0 : .await
199 0 : .ok_or_else(|| anyhow::Error::new(TimeoutOrCancel::Cancel))
200 0 : .and_then(|x| x)
201 0 : .context("remove_tenant_remote_delete_mark")?;
202 0 : }
203 0 : Ok(())
204 0 : }
205 :
206 : // Cleanup fs traces: tenant config, timelines dir local delete mark, tenant dir
207 0 : async fn cleanup_remaining_fs_traces(
208 0 : conf: &PageServerConf,
209 0 : tenant_shard_id: &TenantShardId,
210 0 : ) -> Result<(), DeleteTenantError> {
211 0 : let rm = |p: Utf8PathBuf, is_dir: bool| async move {
212 0 : if is_dir {
213 0 : tokio::fs::remove_dir(&p).await
214 0 : } else {
215 0 : tokio::fs::remove_file(&p).await
216 0 : }
217 0 : .or_else(fs_ext::ignore_not_found)
218 0 : .with_context(|| format!("failed to delete {p}"))
219 0 : };
220 :
221 0 : rm(conf.tenant_config_path(tenant_shard_id), false).await?;
222 0 : rm(conf.tenant_location_config_path(tenant_shard_id), false).await?;
223 :
224 0 : fail::fail_point!("tenant-delete-before-remove-timelines-dir", |_| {
225 0 : Err(anyhow::anyhow!(
226 0 : "failpoint: tenant-delete-before-remove-timelines-dir"
227 0 : ))?
228 0 : });
229 :
230 0 : rm(conf.timelines_path(tenant_shard_id), true).await?;
231 :
232 0 : fail::fail_point!("tenant-delete-before-remove-deleted-mark", |_| {
233 0 : Err(anyhow::anyhow!(
234 0 : "failpoint: tenant-delete-before-remove-deleted-mark"
235 0 : ))?
236 0 : });
237 :
238 : // Make sure previous deletions are ordered before mark removal.
239 : // Otherwise there is no guarantee that they reach the disk before mark deletion.
240 : // So its possible for mark to reach disk first and for other deletions
241 : // to be reordered later and thus missed if a crash occurs.
242 : // Note that we dont need to sync after mark file is removed
243 : // because we can tolerate the case when mark file reappears on startup.
244 0 : let tenant_path = &conf.tenant_path(tenant_shard_id);
245 0 : if tenant_path.exists() {
246 0 : crashsafe::fsync_async(&conf.tenant_path(tenant_shard_id))
247 0 : .await
248 0 : .context("fsync_pre_mark_remove")?;
249 0 : }
250 :
251 0 : rm(conf.tenant_deleted_mark_file_path(tenant_shard_id), false).await?;
252 :
253 0 : rm(conf.tenant_heatmap_path(tenant_shard_id), false).await?;
254 :
255 0 : fail::fail_point!("tenant-delete-before-remove-tenant-dir", |_| {
256 0 : Err(anyhow::anyhow!(
257 0 : "failpoint: tenant-delete-before-remove-tenant-dir"
258 0 : ))?
259 0 : });
260 :
261 0 : rm(conf.tenant_path(tenant_shard_id), true).await?;
262 :
263 0 : Ok(())
264 0 : }
265 :
266 : /// Orchestrates tenant shut down of all tasks, removes its in-memory structures,
267 : /// and deletes its data from both disk and s3.
268 : /// The sequence of steps:
269 : /// 1. Upload remote deletion mark.
270 : /// 2. Create local mark file.
271 : /// 3. Shutdown tasks
272 : /// 4. Run ordered timeline deletions
273 : /// 5. Wait for timeline deletion operations that were scheduled before tenant deletion was requested
274 : /// 6. Remove remote mark
275 : /// 7. Cleanup remaining fs traces, tenant dir, config, timelines dir, local delete mark
276 : /// It is resumable from any step in case a crash/restart occurs.
277 : /// There are two entrypoints to the process:
278 : /// 1. [`DeleteTenantFlow::run`] this is the main one called by a management api handler.
279 : /// 2. [`DeleteTenantFlow::resume_from_attach`] is called when deletion is resumed tenant is found to be deleted during attach process.
280 : /// Note the only other place that messes around timeline delete mark is the `Tenant::spawn_load` function.
281 : #[derive(Default)]
282 : pub enum DeleteTenantFlow {
283 : #[default]
284 : NotStarted,
285 : InProgress,
286 : Finished,
287 : }
288 :
289 : impl DeleteTenantFlow {
290 : // These steps are run in the context of management api request handler.
291 : // Long running steps are continued to run in the background.
292 : // NB: If this fails half-way through, and is retried, the retry will go through
293 : // all the same steps again. Make sure the code here is idempotent, and don't
294 : // error out if some of the shutdown tasks have already been completed!
295 : // NOTE: static needed for background part.
296 : // We assume that calling code sets up the span with tenant_id.
297 0 : #[instrument(skip_all)]
298 : pub(crate) async fn run(
299 : conf: &'static PageServerConf,
300 : remote_storage: Option<GenericRemoteStorage>,
301 : tenants: &'static std::sync::RwLock<TenantsMap>,
302 : tenant: Arc<Tenant>,
303 : cancel: &CancellationToken,
304 : ) -> Result<(), DeleteTenantError> {
305 : span::debug_assert_current_span_has_tenant_id();
306 :
307 : pausable_failpoint!("tenant-delete-before-run");
308 :
309 : let mut guard = Self::prepare(&tenant).await?;
310 :
311 : if let Err(e) =
312 : Self::run_inner(&mut guard, conf, remote_storage.as_ref(), &tenant, cancel).await
313 : {
314 : tenant.set_broken(format!("{e:#}")).await;
315 : return Err(e);
316 : }
317 :
318 : Self::schedule_background(guard, conf, remote_storage, tenants, tenant);
319 :
320 : Ok(())
321 : }
322 :
323 : // Helper function needed to be able to match once on returned error and transition tenant into broken state.
324 : // This is needed because tenant.shutwodn is not idempotent. If tenant state is set to stopping another call to tenant.shutdown
325 : // will result in an error, but here we need to be able to retry shutdown when tenant deletion is retried.
326 : // So the solution is to set tenant state to broken.
327 0 : async fn run_inner(
328 0 : guard: &mut OwnedMutexGuard<Self>,
329 0 : conf: &'static PageServerConf,
330 0 : remote_storage: Option<&GenericRemoteStorage>,
331 0 : tenant: &Tenant,
332 0 : cancel: &CancellationToken,
333 0 : ) -> Result<(), DeleteTenantError> {
334 0 : guard.mark_in_progress()?;
335 :
336 0 : fail::fail_point!("tenant-delete-before-create-remote-mark", |_| {
337 0 : Err(anyhow::anyhow!(
338 0 : "failpoint: tenant-delete-before-create-remote-mark"
339 0 : ))?
340 0 : });
341 :
342 : // IDEA: implement detach as delete without remote storage. Then they would use the same lock (deletion_progress) so wont contend.
343 : // Though sounds scary, different mark name?
344 : // Detach currently uses remove_dir_all so in case of a crash we can end up in a weird state.
345 0 : if let Some(remote_storage) = &remote_storage {
346 0 : create_remote_delete_mark(conf, remote_storage, &tenant.tenant_shard_id, cancel)
347 0 : .await
348 0 : .context("remote_mark")?
349 0 : }
350 :
351 0 : fail::fail_point!("tenant-delete-before-create-local-mark", |_| {
352 0 : Err(anyhow::anyhow!(
353 0 : "failpoint: tenant-delete-before-create-local-mark"
354 0 : ))?
355 0 : });
356 :
357 0 : create_local_delete_mark(conf, &tenant.tenant_shard_id)
358 0 : .await
359 0 : .context("local delete mark")?;
360 :
361 0 : fail::fail_point!("tenant-delete-before-background", |_| {
362 0 : Err(anyhow::anyhow!(
363 0 : "failpoint: tenant-delete-before-background"
364 0 : ))?
365 0 : });
366 :
367 0 : Ok(())
368 0 : }
369 :
370 0 : fn mark_in_progress(&mut self) -> anyhow::Result<()> {
371 0 : match self {
372 0 : Self::Finished => anyhow::bail!("Bug. Is in finished state"),
373 0 : Self::InProgress { .. } => { /* We're in a retry */ }
374 0 : Self::NotStarted => { /* Fresh start */ }
375 : }
376 :
377 0 : *self = Self::InProgress;
378 0 :
379 0 : Ok(())
380 0 : }
381 :
382 0 : pub(crate) async fn should_resume_deletion(
383 0 : conf: &'static PageServerConf,
384 0 : remote_mark_exists: bool,
385 0 : tenant: &Tenant,
386 0 : ) -> Result<Option<DeletionGuard>, DeleteTenantError> {
387 0 : let acquire = |t: &Tenant| {
388 0 : Some(
389 0 : Arc::clone(&t.delete_progress)
390 0 : .try_lock_owned()
391 0 : .expect("we're the only owner during init"),
392 0 : )
393 0 : };
394 :
395 0 : if remote_mark_exists {
396 0 : return Ok(acquire(tenant));
397 0 : }
398 0 :
399 0 : // Check local mark first, if its there there is no need to go to s3 to check whether remote one exists.
400 0 : if conf
401 0 : .tenant_deleted_mark_file_path(&tenant.tenant_shard_id)
402 0 : .exists()
403 : {
404 0 : Ok(acquire(tenant))
405 : } else {
406 0 : Ok(None)
407 : }
408 0 : }
409 :
410 0 : pub(crate) async fn resume_from_attach(
411 0 : guard: DeletionGuard,
412 0 : tenant: &Arc<Tenant>,
413 0 : preload: Option<TenantPreload>,
414 0 : tenants: &'static std::sync::RwLock<TenantsMap>,
415 0 : ctx: &RequestContext,
416 0 : ) -> Result<(), DeleteTenantError> {
417 0 : let (_, progress) = completion::channel();
418 0 :
419 0 : tenant
420 0 : .set_stopping(progress, false, true)
421 0 : .await
422 0 : .expect("cant be stopping or broken");
423 0 :
424 0 : tenant
425 0 : .attach(preload, super::SpawnMode::Eager, ctx)
426 0 : .await
427 0 : .context("attach")?;
428 :
429 0 : Self::background(
430 0 : guard,
431 0 : tenant.conf,
432 0 : tenant.remote_storage.clone(),
433 0 : tenants,
434 0 : tenant,
435 0 : )
436 0 : .await
437 0 : }
438 :
439 : /// Check whether background deletion of this tenant is currently in progress
440 0 : pub(crate) fn is_in_progress(tenant: &Tenant) -> bool {
441 0 : tenant.delete_progress.try_lock().is_err()
442 0 : }
443 :
444 0 : async fn prepare(
445 0 : tenant: &Arc<Tenant>,
446 0 : ) -> Result<tokio::sync::OwnedMutexGuard<Self>, DeleteTenantError> {
447 : // FIXME: unsure about active only. Our init jobs may not be cancellable properly,
448 : // so at least for now allow deletions only for active tenants. TODO recheck
449 : // Broken and Stopping is needed for retries.
450 0 : if !matches!(
451 0 : tenant.current_state(),
452 : TenantState::Active | TenantState::Broken { .. }
453 : ) {
454 0 : return Err(DeleteTenantError::InvalidState(tenant.current_state()));
455 0 : }
456 :
457 0 : let guard = Arc::clone(&tenant.delete_progress)
458 0 : .try_lock_owned()
459 0 : .map_err(|_| DeleteTenantError::AlreadyInProgress)?;
460 :
461 0 : fail::fail_point!("tenant-delete-before-shutdown", |_| {
462 0 : Err(anyhow::anyhow!("failpoint: tenant-delete-before-shutdown"))?
463 0 : });
464 :
465 : // make pageserver shutdown not to wait for our completion
466 0 : let (_, progress) = completion::channel();
467 0 :
468 0 : // It would be good to only set stopping here and continue shutdown in the background, but shutdown is not idempotent.
469 0 : // i e it is an error to do:
470 0 : // tenant.set_stopping
471 0 : // tenant.shutdown
472 0 : // Its also bad that we're holding tenants.read here.
473 0 : // TODO relax set_stopping to be idempotent?
474 0 : if tenant.shutdown(progress, ShutdownMode::Hard).await.is_err() {
475 0 : return Err(DeleteTenantError::Other(anyhow::anyhow!(
476 0 : "tenant shutdown is already in progress"
477 0 : )));
478 0 : }
479 0 :
480 0 : Ok(guard)
481 0 : }
482 :
483 0 : fn schedule_background(
484 0 : guard: OwnedMutexGuard<Self>,
485 0 : conf: &'static PageServerConf,
486 0 : remote_storage: Option<GenericRemoteStorage>,
487 0 : tenants: &'static std::sync::RwLock<TenantsMap>,
488 0 : tenant: Arc<Tenant>,
489 0 : ) {
490 0 : let tenant_shard_id = tenant.tenant_shard_id;
491 0 :
492 0 : task_mgr::spawn(
493 0 : task_mgr::BACKGROUND_RUNTIME.handle(),
494 0 : TaskKind::TimelineDeletionWorker,
495 0 : Some(tenant_shard_id),
496 0 : None,
497 0 : "tenant_delete",
498 : false,
499 0 : async move {
500 0 : if let Err(err) =
501 0 : Self::background(guard, conf, remote_storage, tenants, &tenant).await
502 : {
503 0 : error!("Error: {err:#}");
504 0 : tenant.set_broken(format!("{err:#}")).await;
505 0 : };
506 0 : Ok(())
507 0 : }
508 0 : .instrument(tracing::info_span!(parent: None, "delete_tenant", tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug())),
509 : );
510 0 : }
511 :
512 0 : async fn background(
513 0 : mut guard: OwnedMutexGuard<Self>,
514 0 : conf: &PageServerConf,
515 0 : remote_storage: Option<GenericRemoteStorage>,
516 0 : tenants: &'static std::sync::RwLock<TenantsMap>,
517 0 : tenant: &Arc<Tenant>,
518 0 : ) -> Result<(), DeleteTenantError> {
519 : // Tree sort timelines, schedule delete for them. Mention retries from the console side.
520 : // Note that if deletion fails we dont mark timelines as broken,
521 : // the whole tenant will become broken as by `Self::schedule_background` logic
522 0 : let already_running_timeline_deletions = schedule_ordered_timeline_deletions(tenant)
523 0 : .await
524 0 : .context("schedule_ordered_timeline_deletions")?;
525 :
526 0 : fail::fail_point!("tenant-delete-before-polling-ongoing-deletions", |_| {
527 0 : Err(anyhow::anyhow!(
528 0 : "failpoint: tenant-delete-before-polling-ongoing-deletions"
529 0 : ))?
530 0 : });
531 :
532 : // Wait for deletions that were already running at the moment when tenant deletion was requested.
533 : // When we can lock deletion guard it means that corresponding timeline deletion finished.
534 0 : for (guard, timeline_id) in already_running_timeline_deletions {
535 0 : let flow = guard.lock().await;
536 0 : if !flow.is_finished() {
537 0 : return Err(DeleteTenantError::Other(anyhow::anyhow!(
538 0 : "already running timeline deletion failed: {timeline_id}"
539 0 : )));
540 0 : }
541 : }
542 :
543 0 : let timelines_path = conf.timelines_path(&tenant.tenant_shard_id);
544 0 : // May not exist if we fail in cleanup_remaining_fs_traces after removing it
545 0 : if timelines_path.exists() {
546 : // sanity check to guard against layout changes
547 0 : ensure_timelines_dir_empty(&timelines_path)
548 0 : .await
549 0 : .context("timelines dir not empty")?;
550 0 : }
551 :
552 0 : remove_tenant_remote_delete_mark(
553 0 : conf,
554 0 : remote_storage.as_ref(),
555 0 : &tenant.tenant_shard_id,
556 0 : &task_mgr::shutdown_token(),
557 0 : )
558 0 : .await?;
559 :
560 : pausable_failpoint!("tenant-delete-before-cleanup-remaining-fs-traces-pausable");
561 0 : fail::fail_point!("tenant-delete-before-cleanup-remaining-fs-traces", |_| {
562 0 : Err(anyhow::anyhow!(
563 0 : "failpoint: tenant-delete-before-cleanup-remaining-fs-traces"
564 0 : ))?
565 0 : });
566 :
567 0 : cleanup_remaining_fs_traces(conf, &tenant.tenant_shard_id)
568 0 : .await
569 0 : .context("cleanup_remaining_fs_traces")?;
570 :
571 : {
572 : pausable_failpoint!("tenant-delete-before-map-remove");
573 :
574 : // This block is simply removing the TenantSlot for this tenant. It requires a loop because
575 : // we might conflict with a TenantSlot::InProgress marker and need to wait for it.
576 : //
577 : // This complexity will go away when we simplify how deletion works:
578 : // https://github.com/neondatabase/neon/issues/5080
579 : loop {
580 : // Under the TenantMap lock, try to remove the tenant. We usually succeed, but if
581 : // we encounter an InProgress marker, yield the barrier it contains and wait on it.
582 0 : let barrier = {
583 0 : let mut locked = tenants.write().unwrap();
584 0 : let removed = locked.remove(tenant.tenant_shard_id);
585 0 :
586 0 : // FIXME: we should not be modifying this from outside of mgr.rs.
587 0 : // This will go away when we simplify deletion (https://github.com/neondatabase/neon/issues/5080)
588 0 :
589 0 : // Update stats
590 0 : match &removed {
591 0 : TenantsMapRemoveResult::Occupied(slot) => {
592 0 : crate::metrics::TENANT_MANAGER.slot_removed(slot);
593 0 : }
594 0 : TenantsMapRemoveResult::InProgress(barrier) => {
595 0 : crate::metrics::TENANT_MANAGER
596 0 : .slot_removed(&TenantSlot::InProgress(barrier.clone()));
597 0 : }
598 0 : TenantsMapRemoveResult::Vacant => {
599 0 : // Nothing changed in map, no metric update
600 0 : }
601 : }
602 :
603 0 : match removed {
604 0 : TenantsMapRemoveResult::Occupied(TenantSlot::Attached(tenant)) => {
605 0 : match tenant.current_state() {
606 0 : TenantState::Stopping { .. } | TenantState::Broken { .. } => {
607 0 : // Expected: we put the tenant into stopping state before we start deleting it
608 0 : }
609 0 : state => {
610 0 : // Unexpected state
611 0 : tracing::warn!(
612 0 : "Tenant in unexpected state {state} after deletion"
613 : );
614 : }
615 : }
616 0 : break;
617 : }
618 : TenantsMapRemoveResult::Occupied(TenantSlot::Secondary(_)) => {
619 : // This is unexpected: this secondary tenants should not have been created, and we
620 : // are not in a position to shut it down from here.
621 0 : tracing::warn!("Tenant transitioned to secondary mode while deleting!");
622 0 : break;
623 : }
624 : TenantsMapRemoveResult::Occupied(TenantSlot::InProgress(_)) => {
625 0 : unreachable!("TenantsMap::remove handles InProgress separately, should never return it here");
626 : }
627 : TenantsMapRemoveResult::Vacant => {
628 0 : tracing::warn!(
629 0 : "Tenant removed from TenantsMap before deletion completed"
630 : );
631 0 : break;
632 : }
633 0 : TenantsMapRemoveResult::InProgress(barrier) => {
634 0 : // An InProgress entry was found, we must wait on its barrier
635 0 : barrier
636 0 : }
637 0 : }
638 0 : };
639 0 :
640 0 : tracing::info!(
641 0 : "Waiting for competing operation to complete before deleting state for tenant"
642 : );
643 0 : barrier.wait().await;
644 : }
645 : }
646 :
647 0 : *guard = Self::Finished;
648 0 :
649 0 : Ok(())
650 0 : }
651 : }
|