Line data Source code
1 : use std::{
2 : ops::{Deref, DerefMut},
3 : sync::Arc,
4 : };
5 :
6 : use anyhow::Context;
7 : use pageserver_api::{models::TimelineState, shard::TenantShardId};
8 : use remote_storage::DownloadError;
9 : use tokio::sync::OwnedMutexGuard;
10 : use tracing::{error, info, info_span, instrument, Instrument};
11 : use utils::{crashsafe, fs_ext, id::TimelineId, pausable_failpoint};
12 :
13 : use crate::{
14 : config::PageServerConf,
15 : task_mgr::{self, TaskKind},
16 : tenant::{
17 : metadata::TimelineMetadata,
18 : remote_timeline_client::{PersistIndexPartWithDeletedFlagError, RemoteTimelineClient},
19 : CreateTimelineCause, DeleteTimelineError, MaybeDeletedIndexPart, Tenant,
20 : TenantManifestError, TimelineOrOffloaded,
21 : },
22 : virtual_file::MaybeFatalIo,
23 : };
24 :
25 : use super::{Timeline, TimelineResources};
26 :
27 : /// Mark timeline as deleted in S3 so we won't pick it up next time
28 : /// during attach or pageserver restart.
29 : /// See comment in persist_index_part_with_deleted_flag.
30 0 : async fn set_deleted_in_remote_index(
31 0 : remote_client: &Arc<RemoteTimelineClient>,
32 0 : ) -> Result<(), DeleteTimelineError> {
33 0 : let res = remote_client.persist_index_part_with_deleted_flag().await;
34 0 : match res {
35 : // If we (now, or already) marked it successfully as deleted, we can proceed
36 0 : Ok(()) | Err(PersistIndexPartWithDeletedFlagError::AlreadyDeleted(_)) => (),
37 : // Bail out otherwise
38 : //
39 : // AlreadyInProgress shouldn't happen, because the 'delete_lock' prevents
40 : // two tasks from performing the deletion at the same time. The first task
41 : // that starts deletion should run it to completion.
42 0 : Err(e @ PersistIndexPartWithDeletedFlagError::AlreadyInProgress(_))
43 0 : | Err(e @ PersistIndexPartWithDeletedFlagError::Other(_)) => {
44 0 : return Err(DeleteTimelineError::Other(anyhow::anyhow!(e)));
45 : }
46 : }
47 0 : Ok(())
48 0 : }
49 :
50 : /// Grab the compaction and gc locks, and actually perform the deletion.
51 : ///
52 : /// The locks prevent GC or compaction from running at the same time. The background tasks do not
53 : /// register themselves with the timeline it's operating on, so it might still be running even
54 : /// though we called `shutdown_tasks`.
55 : ///
56 : /// Note that there are still other race conditions between
57 : /// GC, compaction and timeline deletion. See
58 : /// <https://github.com/neondatabase/neon/issues/2671>
59 : ///
60 : /// No timeout here, GC & Compaction should be responsive to the
61 : /// `TimelineState::Stopping` change.
62 : // pub(super): documentation link
63 2 : pub(super) async fn delete_local_timeline_directory(
64 2 : conf: &PageServerConf,
65 2 : tenant_shard_id: TenantShardId,
66 2 : timeline: &Timeline,
67 2 : ) {
68 2 : // Always ensure the lock order is compaction -> gc.
69 2 : let compaction_lock = timeline.compaction_lock.lock();
70 2 : let _compaction_lock = crate::timed(
71 2 : compaction_lock,
72 2 : "acquires compaction lock",
73 2 : std::time::Duration::from_secs(5),
74 2 : )
75 2 : .await;
76 :
77 2 : let gc_lock = timeline.gc_lock.lock();
78 2 : let _gc_lock = crate::timed(
79 2 : gc_lock,
80 2 : "acquires gc lock",
81 2 : std::time::Duration::from_secs(5),
82 2 : )
83 2 : .await;
84 :
85 : // NB: storage_sync upload tasks that reference these layers have been cancelled
86 : // by the caller.
87 :
88 2 : let local_timeline_directory = conf.timeline_path(&tenant_shard_id, &timeline.timeline_id);
89 2 :
90 2 : // NB: This need not be atomic because the deleted flag in the IndexPart
91 2 : // will be observed during tenant/timeline load. The deletion will be resumed there.
92 2 : //
93 2 : // ErrorKind::NotFound can happen e.g. if we race with tenant detach, because,
94 2 : // no locks are shared.
95 2 : tokio::fs::remove_dir_all(local_timeline_directory)
96 2 : .await
97 2 : .or_else(fs_ext::ignore_not_found)
98 2 : .fatal_err("removing timeline directory");
99 2 :
100 2 : // Make sure previous deletions are ordered before mark removal.
101 2 : // Otherwise there is no guarantee that they reach the disk before mark deletion.
102 2 : // So its possible for mark to reach disk first and for other deletions
103 2 : // to be reordered later and thus missed if a crash occurs.
104 2 : // Note that we dont need to sync after mark file is removed
105 2 : // because we can tolerate the case when mark file reappears on startup.
106 2 : let timeline_path = conf.timelines_path(&tenant_shard_id);
107 2 : crashsafe::fsync_async(timeline_path)
108 2 : .await
109 2 : .fatal_err("fsync after removing timeline directory");
110 2 :
111 2 : info!("finished deleting layer files, releasing locks");
112 2 : }
113 :
114 : /// It is important that this gets called when DeletionGuard is being held.
115 : /// For more context see comments in [`DeleteTimelineFlow::prepare`]
116 0 : async fn remove_maybe_offloaded_timeline_from_tenant(
117 0 : tenant: &Tenant,
118 0 : timeline: &TimelineOrOffloaded,
119 0 : _: &DeletionGuard, // using it as a witness
120 0 : ) -> anyhow::Result<()> {
121 0 : // Remove the timeline from the map.
122 0 : // This observes the locking order between timelines and timelines_offloaded
123 0 : let mut timelines = tenant.timelines.lock().unwrap();
124 0 : let mut timelines_offloaded = tenant.timelines_offloaded.lock().unwrap();
125 0 : let offloaded_children_exist = timelines_offloaded
126 0 : .iter()
127 0 : .any(|(_, entry)| entry.ancestor_timeline_id == Some(timeline.timeline_id()));
128 0 : let children_exist = timelines
129 0 : .iter()
130 0 : .any(|(_, entry)| entry.get_ancestor_timeline_id() == Some(timeline.timeline_id()));
131 0 : // XXX this can happen because of race conditions with branch creation.
132 0 : // We already deleted the remote layer files, so it's probably best to panic.
133 0 : if children_exist || offloaded_children_exist {
134 0 : panic!("Timeline grew children while we removed layer files");
135 0 : }
136 0 :
137 0 : match timeline {
138 0 : TimelineOrOffloaded::Timeline(timeline) => {
139 0 : timelines.remove(&timeline.timeline_id).expect(
140 0 : "timeline that we were deleting was concurrently removed from 'timelines' map",
141 0 : );
142 0 : }
143 0 : TimelineOrOffloaded::Offloaded(timeline) => {
144 0 : let offloaded_timeline = timelines_offloaded
145 0 : .remove(&timeline.timeline_id)
146 0 : .expect("timeline that we were deleting was concurrently removed from 'timelines_offloaded' map");
147 0 : offloaded_timeline.delete_from_ancestor_with_timelines(&timelines);
148 0 : }
149 : }
150 :
151 0 : drop(timelines_offloaded);
152 0 : drop(timelines);
153 0 :
154 0 : Ok(())
155 0 : }
156 :
157 : /// Orchestrates timeline shut down of all timeline tasks, removes its in-memory structures,
158 : /// and deletes its data from both disk and s3.
159 : /// The sequence of steps:
160 : /// 1. Set deleted_at in remote index part.
161 : /// 2. Create local mark file.
162 : /// 3. Delete local files except metadata (it is simpler this way, to be able to reuse timeline initialization code that expects metadata)
163 : /// 4. Delete remote layers
164 : /// 5. Delete index part
165 : /// 6. Delete meta, timeline directory
166 : /// 7. Delete mark file
167 : ///
168 : /// It is resumable from any step in case a crash/restart occurs.
169 : /// There are two entrypoints to the process:
170 : /// 1. [`DeleteTimelineFlow::run`] this is the main one called by a management api handler.
171 : /// 2. [`DeleteTimelineFlow::resume_deletion`] is called during restarts when local metadata is still present
172 : /// and we possibly neeed to continue deletion of remote files.
173 : ///
174 : /// Note the only other place that messes around timeline delete mark is the logic that scans directory with timelines during tenant load.
175 : #[derive(Default)]
176 : pub enum DeleteTimelineFlow {
177 : #[default]
178 : NotStarted,
179 : InProgress,
180 : Finished,
181 : }
182 :
183 : impl DeleteTimelineFlow {
184 : // These steps are run in the context of management api request handler.
185 : // Long running steps are continued to run in the background.
186 : // NB: If this fails half-way through, and is retried, the retry will go through
187 : // all the same steps again. Make sure the code here is idempotent, and don't
188 : // error out if some of the shutdown tasks have already been completed!
189 : #[instrument(skip_all)]
190 : pub async fn run(
191 : tenant: &Arc<Tenant>,
192 : timeline_id: TimelineId,
193 : ) -> Result<(), DeleteTimelineError> {
194 : super::debug_assert_current_span_has_tenant_and_timeline_id();
195 :
196 : let allow_offloaded_children = false;
197 : let set_stopping = true;
198 : let (timeline, mut guard) =
199 : Self::prepare(tenant, timeline_id, allow_offloaded_children, set_stopping)?;
200 :
201 : guard.mark_in_progress()?;
202 :
203 : // Now that the Timeline is in Stopping state, request all the related tasks to shut down.
204 : if let TimelineOrOffloaded::Timeline(timeline) = &timeline {
205 : timeline.shutdown(super::ShutdownMode::Hard).await;
206 : }
207 :
208 : tenant.gc_block.before_delete(&timeline.timeline_id());
209 :
210 0 : fail::fail_point!("timeline-delete-before-index-deleted-at", |_| {
211 0 : Err(anyhow::anyhow!(
212 0 : "failpoint: timeline-delete-before-index-deleted-at"
213 0 : ))?
214 0 : });
215 :
216 : let remote_client = match timeline.maybe_remote_client() {
217 : Some(remote_client) => remote_client,
218 : None => {
219 : let remote_client = tenant
220 : .build_timeline_client(timeline.timeline_id(), tenant.remote_storage.clone());
221 : let result = match remote_client
222 : .download_index_file(&tenant.cancel)
223 : .instrument(info_span!("download_index_file"))
224 : .await
225 : {
226 : Ok(r) => r,
227 : Err(DownloadError::NotFound) => {
228 : // Deletion is already complete
229 : tracing::info!("Timeline already deleted in remote storage");
230 : return Ok(());
231 : }
232 : Err(e) => {
233 : return Err(DeleteTimelineError::Other(anyhow::anyhow!(
234 : "error: {:?}",
235 : e
236 : )));
237 : }
238 : };
239 : let index_part = match result {
240 : MaybeDeletedIndexPart::Deleted(p) => {
241 : tracing::info!("Timeline already set as deleted in remote index");
242 : p
243 : }
244 : MaybeDeletedIndexPart::IndexPart(p) => p,
245 : };
246 : let remote_client = Arc::new(remote_client);
247 :
248 : remote_client
249 : .init_upload_queue(&index_part)
250 : .map_err(DeleteTimelineError::Other)?;
251 : remote_client.shutdown().await;
252 : remote_client
253 : }
254 : };
255 : set_deleted_in_remote_index(&remote_client).await?;
256 :
257 0 : fail::fail_point!("timeline-delete-before-schedule", |_| {
258 0 : Err(anyhow::anyhow!(
259 0 : "failpoint: timeline-delete-before-schedule"
260 0 : ))?
261 0 : });
262 :
263 : Self::schedule_background(
264 : guard,
265 : tenant.conf,
266 : Arc::clone(tenant),
267 : timeline,
268 : remote_client,
269 : );
270 :
271 : Ok(())
272 : }
273 :
274 0 : fn mark_in_progress(&mut self) -> anyhow::Result<()> {
275 0 : match self {
276 0 : Self::Finished => anyhow::bail!("Bug. Is in finished state"),
277 0 : Self::InProgress { .. } => { /* We're in a retry */ }
278 0 : Self::NotStarted => { /* Fresh start */ }
279 : }
280 :
281 0 : *self = Self::InProgress;
282 0 :
283 0 : Ok(())
284 0 : }
285 :
286 : /// Shortcut to create Timeline in stopping state and spawn deletion task.
287 : #[instrument(skip_all, fields(%timeline_id))]
288 : pub(crate) async fn resume_deletion(
289 : tenant: Arc<Tenant>,
290 : timeline_id: TimelineId,
291 : local_metadata: &TimelineMetadata,
292 : remote_client: RemoteTimelineClient,
293 : ) -> anyhow::Result<()> {
294 : // Note: here we even skip populating layer map. Timeline is essentially uninitialized.
295 : // RemoteTimelineClient is the only functioning part.
296 : let timeline = tenant
297 : .create_timeline_struct(
298 : timeline_id,
299 : local_metadata,
300 : None, // Ancestor is not needed for deletion.
301 : TimelineResources {
302 : remote_client,
303 : pagestream_throttle: tenant.pagestream_throttle.clone(),
304 : l0_flush_global_state: tenant.l0_flush_global_state.clone(),
305 : },
306 : // Important. We dont pass ancestor above because it can be missing.
307 : // Thus we need to skip the validation here.
308 : CreateTimelineCause::Delete,
309 : crate::tenant::CreateTimelineIdempotency::FailWithConflict, // doesn't matter what we put here
310 : )
311 : .context("create_timeline_struct")?;
312 :
313 : let mut guard = DeletionGuard(
314 : Arc::clone(&timeline.delete_progress)
315 : .try_lock_owned()
316 : .expect("cannot happen because we're the only owner"),
317 : );
318 :
319 : // We meed to do this because when console retries delete request we shouldnt answer with 404
320 : // because 404 means successful deletion.
321 : {
322 : let mut locked = tenant.timelines.lock().unwrap();
323 : locked.insert(timeline_id, Arc::clone(&timeline));
324 : }
325 :
326 : guard.mark_in_progress()?;
327 :
328 : let remote_client = timeline.remote_client.clone();
329 : let timeline = TimelineOrOffloaded::Timeline(timeline);
330 : Self::schedule_background(guard, tenant.conf, tenant, timeline, remote_client);
331 :
332 : Ok(())
333 : }
334 :
335 2 : pub(super) fn prepare(
336 2 : tenant: &Tenant,
337 2 : timeline_id: TimelineId,
338 2 : allow_offloaded_children: bool,
339 2 : set_stopping: bool,
340 2 : ) -> Result<(TimelineOrOffloaded, DeletionGuard), DeleteTimelineError> {
341 2 : // Note the interaction between this guard and deletion guard.
342 2 : // Here we attempt to lock deletion guard when we're holding a lock on timelines.
343 2 : // This is important because when you take into account `remove_timeline_from_tenant`
344 2 : // we remove timeline from memory when we still hold the deletion guard.
345 2 : // So here when timeline deletion is finished timeline wont be present in timelines map at all
346 2 : // which makes the following sequence impossible:
347 2 : // T1: get preempted right before the try_lock on `Timeline::delete_progress`
348 2 : // T2: do a full deletion, acquire and drop `Timeline::delete_progress`
349 2 : // T1: acquire deletion lock, do another `DeleteTimelineFlow::run`
350 2 : // For more context see this discussion: `https://github.com/neondatabase/neon/pull/4552#discussion_r1253437346`
351 2 : let timelines = tenant.timelines.lock().unwrap();
352 2 : let timelines_offloaded = tenant.timelines_offloaded.lock().unwrap();
353 :
354 2 : let timeline = match timelines.get(&timeline_id) {
355 2 : Some(t) => TimelineOrOffloaded::Timeline(Arc::clone(t)),
356 0 : None => match timelines_offloaded.get(&timeline_id) {
357 0 : Some(t) => TimelineOrOffloaded::Offloaded(Arc::clone(t)),
358 0 : None => return Err(DeleteTimelineError::NotFound),
359 : },
360 : };
361 :
362 : // Ensure that there are no child timelines, because we are about to remove files,
363 : // which will break child branches
364 2 : let mut children = Vec::new();
365 2 : if !allow_offloaded_children {
366 0 : children.extend(timelines_offloaded.iter().filter_map(|(id, entry)| {
367 0 : (entry.ancestor_timeline_id == Some(timeline_id)).then_some(*id)
368 0 : }));
369 2 : }
370 4 : children.extend(timelines.iter().filter_map(|(id, entry)| {
371 4 : (entry.get_ancestor_timeline_id() == Some(timeline_id)).then_some(*id)
372 4 : }));
373 2 :
374 2 : if !children.is_empty() {
375 0 : return Err(DeleteTimelineError::HasChildren(children));
376 2 : }
377 2 :
378 2 : // Note that using try_lock here is important to avoid a deadlock.
379 2 : // Here we take lock on timelines and then the deletion guard.
380 2 : // At the end of the operation we're holding the guard and need to lock timelines map
381 2 : // to remove the timeline from it.
382 2 : // Always if you have two locks that are taken in different order this can result in a deadlock.
383 2 :
384 2 : let delete_progress = Arc::clone(timeline.delete_progress());
385 2 : let delete_lock_guard = match delete_progress.try_lock_owned() {
386 2 : Ok(guard) => DeletionGuard(guard),
387 : Err(_) => {
388 : // Unfortunately if lock fails arc is consumed.
389 0 : return Err(DeleteTimelineError::AlreadyInProgress(Arc::clone(
390 0 : timeline.delete_progress(),
391 0 : )));
392 : }
393 : };
394 :
395 2 : if set_stopping {
396 0 : if let TimelineOrOffloaded::Timeline(timeline) = &timeline {
397 0 : timeline.set_state(TimelineState::Stopping);
398 0 : }
399 2 : }
400 :
401 2 : Ok((timeline, delete_lock_guard))
402 2 : }
403 :
404 0 : fn schedule_background(
405 0 : guard: DeletionGuard,
406 0 : conf: &'static PageServerConf,
407 0 : tenant: Arc<Tenant>,
408 0 : timeline: TimelineOrOffloaded,
409 0 : remote_client: Arc<RemoteTimelineClient>,
410 0 : ) {
411 0 : let tenant_shard_id = timeline.tenant_shard_id();
412 0 : let timeline_id = timeline.timeline_id();
413 0 :
414 0 : task_mgr::spawn(
415 0 : task_mgr::BACKGROUND_RUNTIME.handle(),
416 0 : TaskKind::TimelineDeletionWorker,
417 0 : tenant_shard_id,
418 0 : Some(timeline_id),
419 0 : "timeline_delete",
420 0 : async move {
421 0 : if let Err(err) = Self::background(guard, conf, &tenant, &timeline, remote_client).await {
422 : // Only log as an error if it's not a cancellation.
423 0 : if matches!(err, DeleteTimelineError::Cancelled) {
424 0 : info!("Shutdown during timeline deletion");
425 : }else {
426 0 : error!("Error: {err:#}");
427 : }
428 0 : if let TimelineOrOffloaded::Timeline(timeline) = timeline {
429 0 : timeline.set_broken(format!("{err:#}"))
430 0 : }
431 0 : };
432 0 : Ok(())
433 0 : }
434 0 : .instrument(tracing::info_span!(parent: None, "delete_timeline", tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug(),timeline_id=%timeline_id)),
435 : );
436 0 : }
437 :
438 0 : async fn background(
439 0 : mut guard: DeletionGuard,
440 0 : conf: &PageServerConf,
441 0 : tenant: &Tenant,
442 0 : timeline: &TimelineOrOffloaded,
443 0 : remote_client: Arc<RemoteTimelineClient>,
444 0 : ) -> Result<(), DeleteTimelineError> {
445 0 : fail::fail_point!("timeline-delete-before-rm", |_| {
446 0 : Err(anyhow::anyhow!("failpoint: timeline-delete-before-rm"))?
447 0 : });
448 :
449 : // Offloaded timelines have no local state
450 : // TODO: once we persist offloaded information, delete the timeline from there, too
451 0 : if let TimelineOrOffloaded::Timeline(timeline) = timeline {
452 0 : delete_local_timeline_directory(conf, tenant.tenant_shard_id, timeline).await;
453 0 : }
454 :
455 0 : fail::fail_point!("timeline-delete-after-rm", |_| {
456 0 : Err(anyhow::anyhow!("failpoint: timeline-delete-after-rm"))?
457 0 : });
458 :
459 0 : remote_client.delete_all().await?;
460 :
461 0 : pausable_failpoint!("in_progress_delete");
462 :
463 0 : remove_maybe_offloaded_timeline_from_tenant(tenant, timeline, &guard).await?;
464 :
465 : // This is susceptible to race conditions, i.e. we won't continue deletions if there is a crash
466 : // between the deletion of the index-part.json and reaching of this code.
467 : // So indeed, the tenant manifest might refer to an offloaded timeline which has already been deleted.
468 : // However, we handle this case in tenant loading code so the next time we attach, the issue is
469 : // resolved.
470 0 : tenant.store_tenant_manifest().await.map_err(|e| match e {
471 0 : TenantManifestError::Cancelled => DeleteTimelineError::Cancelled,
472 0 : _ => DeleteTimelineError::Other(e.into()),
473 0 : })?;
474 :
475 0 : *guard = Self::Finished;
476 0 :
477 0 : Ok(())
478 0 : }
479 :
480 0 : pub(crate) fn is_not_started(&self) -> bool {
481 0 : matches!(self, Self::NotStarted)
482 0 : }
483 : }
484 :
485 : pub(super) struct DeletionGuard(OwnedMutexGuard<DeleteTimelineFlow>);
486 :
487 : impl Deref for DeletionGuard {
488 : type Target = DeleteTimelineFlow;
489 :
490 0 : fn deref(&self) -> &Self::Target {
491 0 : &self.0
492 0 : }
493 : }
494 :
495 : impl DerefMut for DeletionGuard {
496 0 : fn deref_mut(&mut self) -> &mut Self::Target {
497 0 : &mut self.0
498 0 : }
499 : }
|