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