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