LCOV - code coverage report
Current view: top level - safekeeper/src - timelines_global_map.rs (source / functions) Coverage Total Hit
Test: 47d527da5e8405637e322911c55c08727c2fd272.info Lines: 0.0 % 373 0
Test Date: 2025-01-16 17:37:50 Functions: 0.0 % 36 0

            Line data    Source code
       1              : //! This module contains global `(tenant_id, timeline_id)` -> `Arc<Timeline>` mapping.
       2              : //! All timelines should always be present in this map, this is done by loading them
       3              : //! all from the disk on startup and keeping them in memory.
       4              : 
       5              : use crate::defaults::DEFAULT_EVICTION_CONCURRENCY;
       6              : use crate::rate_limit::RateLimiter;
       7              : use crate::state::TimelinePersistentState;
       8              : use crate::timeline::{get_tenant_dir, get_timeline_dir, Timeline, TimelineError};
       9              : use crate::timelines_set::TimelinesSet;
      10              : use crate::wal_storage::Storage;
      11              : use crate::{control_file, wal_storage, SafeKeeperConf};
      12              : use anyhow::{bail, Context, Result};
      13              : use camino::Utf8PathBuf;
      14              : use camino_tempfile::Utf8TempDir;
      15              : use safekeeper_api::membership::Configuration;
      16              : use safekeeper_api::ServerInfo;
      17              : use serde::Serialize;
      18              : use std::collections::HashMap;
      19              : use std::str::FromStr;
      20              : use std::sync::atomic::Ordering;
      21              : use std::sync::{Arc, Mutex};
      22              : use std::time::{Duration, Instant};
      23              : use tokio::fs;
      24              : use tracing::*;
      25              : use utils::crashsafe::{durable_rename, fsync_async_opt};
      26              : use utils::id::{TenantId, TenantTimelineId, TimelineId};
      27              : use utils::lsn::Lsn;
      28              : 
      29              : // Timeline entry in the global map: either a ready timeline, or mark that it is
      30              : // being created.
      31              : #[derive(Clone)]
      32              : enum GlobalMapTimeline {
      33              :     CreationInProgress,
      34              :     Timeline(Arc<Timeline>),
      35              : }
      36              : 
      37              : struct GlobalTimelinesState {
      38              :     timelines: HashMap<TenantTimelineId, GlobalMapTimeline>,
      39              : 
      40              :     // A tombstone indicates this timeline used to exist has been deleted.  These are used to prevent
      41              :     // on-demand timeline creation from recreating deleted timelines.  This is only soft-enforced, as
      42              :     // this map is dropped on restart.
      43              :     tombstones: HashMap<TenantTimelineId, Instant>,
      44              : 
      45              :     conf: Arc<SafeKeeperConf>,
      46              :     broker_active_set: Arc<TimelinesSet>,
      47              :     global_rate_limiter: RateLimiter,
      48              : }
      49              : 
      50              : impl GlobalTimelinesState {
      51              :     /// Get dependencies for a timeline constructor.
      52            0 :     fn get_dependencies(&self) -> (Arc<SafeKeeperConf>, Arc<TimelinesSet>, RateLimiter) {
      53            0 :         (
      54            0 :             self.conf.clone(),
      55            0 :             self.broker_active_set.clone(),
      56            0 :             self.global_rate_limiter.clone(),
      57            0 :         )
      58            0 :     }
      59              : 
      60              :     /// Get timeline from the map. Returns error if timeline doesn't exist or
      61              :     /// creation is in progress.
      62            0 :     fn get(&self, ttid: &TenantTimelineId) -> Result<Arc<Timeline>, TimelineError> {
      63            0 :         match self.timelines.get(ttid).cloned() {
      64            0 :             Some(GlobalMapTimeline::Timeline(tli)) => Ok(tli),
      65              :             Some(GlobalMapTimeline::CreationInProgress) => {
      66            0 :                 Err(TimelineError::CreationInProgress(*ttid))
      67              :             }
      68            0 :             None => Err(TimelineError::NotFound(*ttid)),
      69              :         }
      70            0 :     }
      71              : 
      72            0 :     fn delete(&mut self, ttid: TenantTimelineId) {
      73            0 :         self.timelines.remove(&ttid);
      74            0 :         self.tombstones.insert(ttid, Instant::now());
      75            0 :     }
      76              : }
      77              : 
      78              : /// A struct used to manage access to the global timelines map.
      79              : pub struct GlobalTimelines {
      80              :     state: Mutex<GlobalTimelinesState>,
      81              : }
      82              : 
      83              : impl GlobalTimelines {
      84              :     /// Create a new instance of the global timelines map.
      85            0 :     pub fn new(conf: Arc<SafeKeeperConf>) -> Self {
      86            0 :         Self {
      87            0 :             state: Mutex::new(GlobalTimelinesState {
      88            0 :                 timelines: HashMap::new(),
      89            0 :                 tombstones: HashMap::new(),
      90            0 :                 conf,
      91            0 :                 broker_active_set: Arc::new(TimelinesSet::default()),
      92            0 :                 global_rate_limiter: RateLimiter::new(1, 1),
      93            0 :             }),
      94            0 :         }
      95            0 :     }
      96              : 
      97              :     /// Inject dependencies needed for the timeline constructors and load all timelines to memory.
      98            0 :     pub async fn init(&self) -> Result<()> {
      99            0 :         // clippy isn't smart enough to understand that drop(state) releases the
     100            0 :         // lock, so use explicit block
     101            0 :         let tenants_dir = {
     102            0 :             let mut state = self.state.lock().unwrap();
     103            0 :             state.global_rate_limiter = RateLimiter::new(
     104            0 :                 state.conf.partial_backup_concurrency,
     105            0 :                 DEFAULT_EVICTION_CONCURRENCY,
     106            0 :             );
     107            0 : 
     108            0 :             // Iterate through all directories and load tenants for all directories
     109            0 :             // named as a valid tenant_id.
     110            0 :             state.conf.workdir.clone()
     111            0 :         };
     112            0 :         let mut tenant_count = 0;
     113            0 :         for tenants_dir_entry in std::fs::read_dir(&tenants_dir)
     114            0 :             .with_context(|| format!("failed to list tenants dir {}", tenants_dir))?
     115              :         {
     116            0 :             match &tenants_dir_entry {
     117            0 :                 Ok(tenants_dir_entry) => {
     118            0 :                     if let Ok(tenant_id) =
     119            0 :                         TenantId::from_str(tenants_dir_entry.file_name().to_str().unwrap_or(""))
     120              :                     {
     121            0 :                         tenant_count += 1;
     122            0 :                         self.load_tenant_timelines(tenant_id).await?;
     123            0 :                     }
     124              :                 }
     125            0 :                 Err(e) => error!(
     126            0 :                     "failed to list tenants dir entry {:?} in directory {}, reason: {:?}",
     127              :                     tenants_dir_entry, tenants_dir, e
     128              :                 ),
     129              :             }
     130              :         }
     131              : 
     132            0 :         info!(
     133            0 :             "found {} tenants directories, successfully loaded {} timelines",
     134            0 :             tenant_count,
     135            0 :             self.state.lock().unwrap().timelines.len()
     136              :         );
     137            0 :         Ok(())
     138            0 :     }
     139              : 
     140              :     /// Loads all timelines for the given tenant to memory. Returns fs::read_dir
     141              :     /// errors if any.
     142              :     ///
     143              :     /// It is async, but self.state lock is sync and there is no important
     144              :     /// reason to make it async (it is always held for a short while), so we
     145              :     /// just lock and unlock it for each timeline -- this function is called
     146              :     /// during init when nothing else is running, so this is fine.
     147            0 :     async fn load_tenant_timelines(&self, tenant_id: TenantId) -> Result<()> {
     148            0 :         let (conf, broker_active_set, partial_backup_rate_limiter) = {
     149            0 :             let state = self.state.lock().unwrap();
     150            0 :             state.get_dependencies()
     151            0 :         };
     152            0 : 
     153            0 :         let timelines_dir = get_tenant_dir(&conf, &tenant_id);
     154            0 :         for timelines_dir_entry in std::fs::read_dir(&timelines_dir)
     155            0 :             .with_context(|| format!("failed to list timelines dir {}", timelines_dir))?
     156              :         {
     157            0 :             match &timelines_dir_entry {
     158            0 :                 Ok(timeline_dir_entry) => {
     159            0 :                     if let Ok(timeline_id) =
     160            0 :                         TimelineId::from_str(timeline_dir_entry.file_name().to_str().unwrap_or(""))
     161              :                     {
     162            0 :                         let ttid = TenantTimelineId::new(tenant_id, timeline_id);
     163            0 :                         match Timeline::load_timeline(conf.clone(), ttid) {
     164            0 :                             Ok(tli) => {
     165            0 :                                 let mut shared_state = tli.write_shared_state().await;
     166            0 :                                 self.state
     167            0 :                                     .lock()
     168            0 :                                     .unwrap()
     169            0 :                                     .timelines
     170            0 :                                     .insert(ttid, GlobalMapTimeline::Timeline(tli.clone()));
     171            0 :                                 tli.bootstrap(
     172            0 :                                     &mut shared_state,
     173            0 :                                     &conf,
     174            0 :                                     broker_active_set.clone(),
     175            0 :                                     partial_backup_rate_limiter.clone(),
     176            0 :                                 );
     177              :                             }
     178              :                             // If we can't load a timeline, it's most likely because of a corrupted
     179              :                             // directory. We will log an error and won't allow to delete/recreate
     180              :                             // this timeline. The only way to fix this timeline is to repair manually
     181              :                             // and restart the safekeeper.
     182            0 :                             Err(e) => error!(
     183            0 :                                 "failed to load timeline {} for tenant {}, reason: {:?}",
     184              :                                 timeline_id, tenant_id, e
     185              :                             ),
     186              :                         }
     187            0 :                     }
     188              :                 }
     189            0 :                 Err(e) => error!(
     190            0 :                     "failed to list timelines dir entry {:?} in directory {}, reason: {:?}",
     191              :                     timelines_dir_entry, timelines_dir, e
     192              :                 ),
     193              :             }
     194              :         }
     195              : 
     196            0 :         Ok(())
     197            0 :     }
     198              : 
     199              :     /// Get the number of timelines in the map.
     200            0 :     pub fn timelines_count(&self) -> usize {
     201            0 :         self.state.lock().unwrap().timelines.len()
     202            0 :     }
     203              : 
     204              :     /// Get the global safekeeper config.
     205            0 :     pub fn get_global_config(&self) -> Arc<SafeKeeperConf> {
     206            0 :         self.state.lock().unwrap().conf.clone()
     207            0 :     }
     208              : 
     209            0 :     pub fn get_global_broker_active_set(&self) -> Arc<TimelinesSet> {
     210            0 :         self.state.lock().unwrap().broker_active_set.clone()
     211            0 :     }
     212              : 
     213              :     /// Create a new timeline with the given id. If the timeline already exists, returns
     214              :     /// an existing timeline.
     215            0 :     pub(crate) async fn create(
     216            0 :         &self,
     217            0 :         ttid: TenantTimelineId,
     218            0 :         mconf: Configuration,
     219            0 :         server_info: ServerInfo,
     220            0 :         start_lsn: Lsn,
     221            0 :         commit_lsn: Lsn,
     222            0 :     ) -> Result<Arc<Timeline>> {
     223            0 :         let (conf, _, _) = {
     224            0 :             let state = self.state.lock().unwrap();
     225            0 :             if let Ok(timeline) = state.get(&ttid) {
     226              :                 // Timeline already exists, return it.
     227            0 :                 return Ok(timeline);
     228            0 :             }
     229            0 : 
     230            0 :             if state.tombstones.contains_key(&ttid) {
     231            0 :                 anyhow::bail!("Timeline {ttid} is deleted, refusing to recreate");
     232            0 :             }
     233            0 : 
     234            0 :             state.get_dependencies()
     235            0 :         };
     236            0 : 
     237            0 :         info!("creating new timeline {}", ttid);
     238              : 
     239              :         // Do on disk initialization in tmp dir.
     240            0 :         let (_tmp_dir, tmp_dir_path) = create_temp_timeline_dir(&conf, ttid).await?;
     241              : 
     242              :         // TODO: currently we create only cfile. It would be reasonable to
     243              :         // immediately initialize first WAL segment as well.
     244            0 :         let state = TimelinePersistentState::new(&ttid, mconf, server_info, start_lsn, commit_lsn)?;
     245            0 :         control_file::FileStorage::create_new(&tmp_dir_path, state, conf.no_sync).await?;
     246            0 :         let timeline = self.load_temp_timeline(ttid, &tmp_dir_path, true).await?;
     247            0 :         Ok(timeline)
     248            0 :     }
     249              : 
     250              :     /// Move timeline from a temp directory to the main storage, and load it to
     251              :     /// the global map. Creating timeline in this way ensures atomicity: rename
     252              :     /// is atomic, so either move of the whole datadir succeeds or it doesn't,
     253              :     /// but corrupted data dir shouldn't be possible.
     254              :     ///
     255              :     /// We'd like to avoid holding map lock while doing IO, so it's a 3 step
     256              :     /// process:
     257              :     /// 1) check the global map that timeline doesn't exist and mark that we're
     258              :     ///    creating it;
     259              :     /// 2) move the directory and load the timeline
     260              :     /// 3) take lock again and insert the timeline into the global map.
     261            0 :     pub async fn load_temp_timeline(
     262            0 :         &self,
     263            0 :         ttid: TenantTimelineId,
     264            0 :         tmp_path: &Utf8PathBuf,
     265            0 :         check_tombstone: bool,
     266            0 :     ) -> Result<Arc<Timeline>> {
     267              :         // Check for existence and mark that we're creating it.
     268            0 :         let (conf, broker_active_set, partial_backup_rate_limiter) = {
     269            0 :             let mut state = self.state.lock().unwrap();
     270            0 :             match state.timelines.get(&ttid) {
     271              :                 Some(GlobalMapTimeline::CreationInProgress) => {
     272            0 :                     bail!(TimelineError::CreationInProgress(ttid));
     273              :                 }
     274              :                 Some(GlobalMapTimeline::Timeline(_)) => {
     275            0 :                     bail!(TimelineError::AlreadyExists(ttid));
     276              :                 }
     277            0 :                 _ => {}
     278            0 :             }
     279            0 :             if check_tombstone {
     280            0 :                 if state.tombstones.contains_key(&ttid) {
     281            0 :                     anyhow::bail!("timeline {ttid} is deleted, refusing to recreate");
     282            0 :                 }
     283              :             } else {
     284              :                 // We may be have been asked to load a timeline that was previously deleted (e.g. from `pull_timeline.rs`).  We trust
     285              :                 // that the human doing this manual intervention knows what they are doing, and remove its tombstone.
     286            0 :                 if state.tombstones.remove(&ttid).is_some() {
     287            0 :                     warn!("un-deleted timeline {ttid}");
     288            0 :                 }
     289              :             }
     290            0 :             state
     291            0 :                 .timelines
     292            0 :                 .insert(ttid, GlobalMapTimeline::CreationInProgress);
     293            0 :             state.get_dependencies()
     294            0 :         };
     295            0 : 
     296            0 :         // Do the actual move and reflect the result in the map.
     297            0 :         match GlobalTimelines::install_temp_timeline(ttid, tmp_path, conf.clone()).await {
     298            0 :             Ok(timeline) => {
     299            0 :                 let mut timeline_shared_state = timeline.write_shared_state().await;
     300            0 :                 let mut state = self.state.lock().unwrap();
     301            0 :                 assert!(matches!(
     302            0 :                     state.timelines.get(&ttid),
     303              :                     Some(GlobalMapTimeline::CreationInProgress)
     304              :                 ));
     305              : 
     306            0 :                 state
     307            0 :                     .timelines
     308            0 :                     .insert(ttid, GlobalMapTimeline::Timeline(timeline.clone()));
     309            0 :                 drop(state);
     310            0 :                 timeline.bootstrap(
     311            0 :                     &mut timeline_shared_state,
     312            0 :                     &conf,
     313            0 :                     broker_active_set,
     314            0 :                     partial_backup_rate_limiter,
     315            0 :                 );
     316            0 :                 drop(timeline_shared_state);
     317            0 :                 Ok(timeline)
     318              :             }
     319            0 :             Err(e) => {
     320            0 :                 // Init failed, remove the marker from the map
     321            0 :                 let mut state = self.state.lock().unwrap();
     322            0 :                 assert!(matches!(
     323            0 :                     state.timelines.get(&ttid),
     324              :                     Some(GlobalMapTimeline::CreationInProgress)
     325              :                 ));
     326            0 :                 state.timelines.remove(&ttid);
     327            0 :                 Err(e)
     328              :             }
     329              :         }
     330            0 :     }
     331              : 
     332              :     /// Main part of load_temp_timeline: do the move and load.
     333            0 :     async fn install_temp_timeline(
     334            0 :         ttid: TenantTimelineId,
     335            0 :         tmp_path: &Utf8PathBuf,
     336            0 :         conf: Arc<SafeKeeperConf>,
     337            0 :     ) -> Result<Arc<Timeline>> {
     338            0 :         let tenant_path = get_tenant_dir(conf.as_ref(), &ttid.tenant_id);
     339            0 :         let timeline_path = get_timeline_dir(conf.as_ref(), &ttid);
     340            0 : 
     341            0 :         // We must have already checked that timeline doesn't exist in the map,
     342            0 :         // but there might be existing datadir: if timeline is corrupted it is
     343            0 :         // not loaded. We don't want to overwrite such a dir, so check for its
     344            0 :         // existence.
     345            0 :         match fs::metadata(&timeline_path).await {
     346              :             Ok(_) => {
     347              :                 // Timeline directory exists on disk, we should leave state unchanged
     348              :                 // and return error.
     349            0 :                 bail!(TimelineError::Invalid(ttid));
     350              :             }
     351            0 :             Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
     352            0 :             Err(e) => {
     353            0 :                 return Err(e.into());
     354              :             }
     355              :         }
     356              : 
     357            0 :         info!(
     358            0 :             "moving timeline {} from {} to {}",
     359              :             ttid, tmp_path, timeline_path
     360              :         );
     361              : 
     362              :         // Now it is safe to move the timeline directory to the correct
     363              :         // location. First, create tenant directory. Ignore error if it already
     364              :         // exists.
     365            0 :         if let Err(e) = tokio::fs::create_dir(&tenant_path).await {
     366            0 :             if e.kind() != std::io::ErrorKind::AlreadyExists {
     367            0 :                 return Err(e.into());
     368            0 :             }
     369            0 :         }
     370              :         // fsync it
     371            0 :         fsync_async_opt(&tenant_path, !conf.no_sync).await?;
     372              :         // and its creation
     373            0 :         fsync_async_opt(&conf.workdir, !conf.no_sync).await?;
     374              : 
     375              :         // Do the move.
     376            0 :         durable_rename(tmp_path, &timeline_path, !conf.no_sync).await?;
     377              : 
     378            0 :         Timeline::load_timeline(conf, ttid)
     379            0 :     }
     380              : 
     381              :     /// Get a timeline from the global map. If it's not present, it doesn't exist on disk,
     382              :     /// or was corrupted and couldn't be loaded on startup. Returned timeline is always valid,
     383              :     /// i.e. loaded in memory and not cancelled.
     384            0 :     pub(crate) fn get(&self, ttid: TenantTimelineId) -> Result<Arc<Timeline>, TimelineError> {
     385            0 :         let tli_res = {
     386            0 :             let state = self.state.lock().unwrap();
     387            0 :             state.get(&ttid)
     388            0 :         };
     389            0 :         match tli_res {
     390            0 :             Ok(tli) => {
     391            0 :                 if tli.is_cancelled() {
     392            0 :                     return Err(TimelineError::Cancelled(ttid));
     393            0 :                 }
     394            0 :                 Ok(tli)
     395              :             }
     396            0 :             _ => tli_res,
     397              :         }
     398            0 :     }
     399              : 
     400              :     /// Returns all timelines. This is used for background timeline processes.
     401            0 :     pub fn get_all(&self) -> Vec<Arc<Timeline>> {
     402            0 :         let global_lock = self.state.lock().unwrap();
     403            0 :         global_lock
     404            0 :             .timelines
     405            0 :             .values()
     406            0 :             .filter_map(|t| match t {
     407            0 :                 GlobalMapTimeline::Timeline(t) => {
     408            0 :                     if t.is_cancelled() {
     409            0 :                         None
     410              :                     } else {
     411            0 :                         Some(t.clone())
     412              :                     }
     413              :                 }
     414            0 :                 _ => None,
     415            0 :             })
     416            0 :             .collect()
     417            0 :     }
     418              : 
     419              :     /// Returns all timelines belonging to a given tenant. Used for deleting all timelines of a tenant,
     420              :     /// and that's why it can return cancelled timelines, to retry deleting them.
     421            0 :     fn get_all_for_tenant(&self, tenant_id: TenantId) -> Vec<Arc<Timeline>> {
     422            0 :         let global_lock = self.state.lock().unwrap();
     423            0 :         global_lock
     424            0 :             .timelines
     425            0 :             .values()
     426            0 :             .filter_map(|t| match t {
     427            0 :                 GlobalMapTimeline::Timeline(t) => Some(t.clone()),
     428            0 :                 _ => None,
     429            0 :             })
     430            0 :             .filter(|t| t.ttid.tenant_id == tenant_id)
     431            0 :             .collect()
     432            0 :     }
     433              : 
     434              :     /// Cancels timeline, then deletes the corresponding data directory.
     435              :     /// If only_local, doesn't remove WAL segments in remote storage.
     436            0 :     pub(crate) async fn delete(
     437            0 :         &self,
     438            0 :         ttid: &TenantTimelineId,
     439            0 :         only_local: bool,
     440            0 :     ) -> Result<TimelineDeleteForceResult> {
     441            0 :         let tli_res = {
     442            0 :             let state = self.state.lock().unwrap();
     443            0 : 
     444            0 :             if state.tombstones.contains_key(ttid) {
     445              :                 // Presence of a tombstone guarantees that a previous deletion has completed and there is no work to do.
     446            0 :                 info!("Timeline {ttid} was already deleted");
     447            0 :                 return Ok(TimelineDeleteForceResult {
     448            0 :                     dir_existed: false,
     449            0 :                     was_active: false,
     450            0 :                 });
     451            0 :             }
     452            0 : 
     453            0 :             state.get(ttid)
     454              :         };
     455              : 
     456            0 :         let result = match tli_res {
     457            0 :             Ok(timeline) => {
     458            0 :                 let was_active = timeline.broker_active.load(Ordering::Relaxed);
     459            0 : 
     460            0 :                 info!("deleting timeline {}, only_local={}", ttid, only_local);
     461            0 :                 timeline.shutdown().await;
     462              : 
     463              :                 // Take a lock and finish the deletion holding this mutex.
     464            0 :                 let mut shared_state = timeline.write_shared_state().await;
     465              : 
     466            0 :                 let dir_existed = timeline.delete(&mut shared_state, only_local).await?;
     467              : 
     468            0 :                 Ok(TimelineDeleteForceResult {
     469            0 :                     dir_existed,
     470            0 :                     was_active, // TODO: we probably should remove this field
     471            0 :                 })
     472              :             }
     473              :             Err(_) => {
     474              :                 // Timeline is not memory, but it may still exist on disk in broken state.
     475            0 :                 let dir_path = get_timeline_dir(self.state.lock().unwrap().conf.as_ref(), ttid);
     476            0 :                 let dir_existed = delete_dir(dir_path)?;
     477              : 
     478            0 :                 Ok(TimelineDeleteForceResult {
     479            0 :                     dir_existed,
     480            0 :                     was_active: false,
     481            0 :                 })
     482              :             }
     483              :         };
     484              : 
     485              :         // Finalize deletion, by dropping Timeline objects and storing smaller tombstones.  The tombstones
     486              :         // are used to prevent still-running computes from re-creating the same timeline when they send data,
     487              :         // and to speed up repeated deletion calls by avoiding re-listing objects.
     488            0 :         self.state.lock().unwrap().delete(*ttid);
     489            0 : 
     490            0 :         result
     491            0 :     }
     492              : 
     493              :     /// Deactivates and deletes all timelines for the tenant. Returns map of all timelines which
     494              :     /// the tenant had, `true` if a timeline was active. There may be a race if new timelines are
     495              :     /// created simultaneously. In that case the function will return error and the caller should
     496              :     /// retry tenant deletion again later.
     497              :     ///
     498              :     /// If only_local, doesn't remove WAL segments in remote storage.
     499            0 :     pub async fn delete_force_all_for_tenant(
     500            0 :         &self,
     501            0 :         tenant_id: &TenantId,
     502            0 :         only_local: bool,
     503            0 :     ) -> Result<HashMap<TenantTimelineId, TimelineDeleteForceResult>> {
     504            0 :         info!("deleting all timelines for tenant {}", tenant_id);
     505            0 :         let to_delete = self.get_all_for_tenant(*tenant_id);
     506            0 : 
     507            0 :         let mut err = None;
     508            0 : 
     509            0 :         let mut deleted = HashMap::new();
     510            0 :         for tli in &to_delete {
     511            0 :             match self.delete(&tli.ttid, only_local).await {
     512            0 :                 Ok(result) => {
     513            0 :                     deleted.insert(tli.ttid, result);
     514            0 :                 }
     515            0 :                 Err(e) => {
     516            0 :                     error!("failed to delete timeline {}: {}", tli.ttid, e);
     517              :                     // Save error to return later.
     518            0 :                     err = Some(e);
     519              :                 }
     520              :             }
     521              :         }
     522              : 
     523              :         // If there was an error, return it.
     524            0 :         if let Some(e) = err {
     525            0 :             return Err(e);
     526            0 :         }
     527            0 : 
     528            0 :         // There may be broken timelines on disk, so delete the whole tenant dir as well.
     529            0 :         // Note that we could concurrently create new timelines while we were deleting them,
     530            0 :         // so the directory may be not empty. In this case timelines will have bad state
     531            0 :         // and timeline background jobs can panic.
     532            0 :         delete_dir(get_tenant_dir(
     533            0 :             self.state.lock().unwrap().conf.as_ref(),
     534            0 :             tenant_id,
     535            0 :         ))?;
     536              : 
     537            0 :         Ok(deleted)
     538            0 :     }
     539              : 
     540            0 :     pub fn housekeeping(&self, tombstone_ttl: &Duration) {
     541            0 :         let mut state = self.state.lock().unwrap();
     542            0 : 
     543            0 :         // We keep tombstones long enough to have a good chance of preventing rogue computes from re-creating deleted
     544            0 :         // timelines.  If a compute kept running for longer than this TTL (or across a safekeeper restart) then they
     545            0 :         // may recreate a deleted timeline.
     546            0 :         let now = Instant::now();
     547            0 :         state
     548            0 :             .tombstones
     549            0 :             .retain(|_, v| now.duration_since(*v) < *tombstone_ttl);
     550            0 :     }
     551              : }
     552              : 
     553              : #[derive(Clone, Copy, Serialize)]
     554              : pub struct TimelineDeleteForceResult {
     555              :     pub dir_existed: bool,
     556              :     pub was_active: bool,
     557              : }
     558              : 
     559              : /// Deletes directory and it's contents. Returns false if directory does not exist.
     560            0 : fn delete_dir(path: Utf8PathBuf) -> Result<bool> {
     561            0 :     match std::fs::remove_dir_all(path) {
     562            0 :         Ok(_) => Ok(true),
     563            0 :         Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),
     564            0 :         Err(e) => Err(e.into()),
     565              :     }
     566            0 : }
     567              : 
     568              : /// Create temp directory for a new timeline. It needs to be located on the same
     569              : /// filesystem as the rest of the timelines. It will be automatically deleted when
     570              : /// Utf8TempDir goes out of scope.
     571            0 : pub async fn create_temp_timeline_dir(
     572            0 :     conf: &SafeKeeperConf,
     573            0 :     ttid: TenantTimelineId,
     574            0 : ) -> Result<(Utf8TempDir, Utf8PathBuf)> {
     575            0 :     let temp_base = conf.workdir.join("tmp");
     576            0 : 
     577            0 :     tokio::fs::create_dir_all(&temp_base).await?;
     578              : 
     579            0 :     let tli_dir = camino_tempfile::Builder::new()
     580            0 :         .suffix("_temptli")
     581            0 :         .prefix(&format!("{}_{}_", ttid.tenant_id, ttid.timeline_id))
     582            0 :         .tempdir_in(temp_base)?;
     583              : 
     584            0 :     let tli_dir_path = tli_dir.path().to_path_buf();
     585            0 : 
     586            0 :     Ok((tli_dir, tli_dir_path))
     587            0 : }
     588              : 
     589              : /// Do basic validation of a temp timeline, before moving it to the global map.
     590            0 : pub async fn validate_temp_timeline(
     591            0 :     conf: &SafeKeeperConf,
     592            0 :     ttid: TenantTimelineId,
     593            0 :     path: &Utf8PathBuf,
     594            0 : ) -> Result<(Lsn, Lsn)> {
     595            0 :     let control_path = path.join("safekeeper.control");
     596              : 
     597            0 :     let control_store = control_file::FileStorage::load_control_file(control_path)?;
     598            0 :     if control_store.server.wal_seg_size == 0 {
     599            0 :         bail!("wal_seg_size is not set");
     600            0 :     }
     601              : 
     602            0 :     let wal_store = wal_storage::PhysicalStorage::new(&ttid, path, &control_store, conf.no_sync)?;
     603              : 
     604            0 :     let commit_lsn = control_store.commit_lsn;
     605            0 :     let flush_lsn = wal_store.flush_lsn();
     606            0 : 
     607            0 :     Ok((commit_lsn, flush_lsn))
     608            0 : }
        

Generated by: LCOV version 2.1-beta