LCOV - code coverage report
Current view: top level - safekeeper/src - timelines_global_map.rs (source / functions) Coverage Total Hit
Test: 691a4c28fe7169edd60b367c52d448a0a6605f1f.info Lines: 0.0 % 266 0
Test Date: 2024-05-10 13:18:37 Functions: 0.0 % 29 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::safekeeper::ServerInfo;
       6              : use crate::timeline::{Timeline, TimelineError};
       7              : use crate::SafeKeeperConf;
       8              : use anyhow::{bail, Context, Result};
       9              : use camino::Utf8PathBuf;
      10              : use once_cell::sync::Lazy;
      11              : use serde::Serialize;
      12              : use std::collections::HashMap;
      13              : use std::str::FromStr;
      14              : use std::sync::{Arc, Mutex};
      15              : use tokio::sync::mpsc::Sender;
      16              : use tracing::*;
      17              : use utils::id::{TenantId, TenantTimelineId, TimelineId};
      18              : use utils::lsn::Lsn;
      19              : 
      20              : struct GlobalTimelinesState {
      21              :     timelines: HashMap<TenantTimelineId, Arc<Timeline>>,
      22              :     wal_backup_launcher_tx: Option<Sender<TenantTimelineId>>,
      23              :     conf: Option<SafeKeeperConf>,
      24              :     load_lock: Arc<tokio::sync::Mutex<TimelineLoadLock>>,
      25              : }
      26              : 
      27              : // Used to prevent concurrent timeline loading.
      28              : pub struct TimelineLoadLock;
      29              : 
      30              : impl GlobalTimelinesState {
      31              :     /// Get configuration, which must be set once during init.
      32            0 :     fn get_conf(&self) -> &SafeKeeperConf {
      33            0 :         self.conf
      34            0 :             .as_ref()
      35            0 :             .expect("GlobalTimelinesState conf is not initialized")
      36            0 :     }
      37              : 
      38              :     /// Get dependencies for a timeline constructor.
      39            0 :     fn get_dependencies(&self) -> (SafeKeeperConf, Sender<TenantTimelineId>) {
      40            0 :         (
      41            0 :             self.get_conf().clone(),
      42            0 :             self.wal_backup_launcher_tx.as_ref().unwrap().clone(),
      43            0 :         )
      44            0 :     }
      45              : 
      46              :     /// Insert timeline into the map. Returns error if timeline with the same id already exists.
      47            0 :     fn try_insert(&mut self, timeline: Arc<Timeline>) -> Result<()> {
      48            0 :         let ttid = timeline.ttid;
      49            0 :         if self.timelines.contains_key(&ttid) {
      50            0 :             bail!(TimelineError::AlreadyExists(ttid));
      51            0 :         }
      52            0 :         self.timelines.insert(ttid, timeline);
      53            0 :         Ok(())
      54            0 :     }
      55              : 
      56              :     /// Get timeline from the map. Returns error if timeline doesn't exist.
      57            0 :     fn get(&self, ttid: &TenantTimelineId) -> Result<Arc<Timeline>, TimelineError> {
      58            0 :         self.timelines
      59            0 :             .get(ttid)
      60            0 :             .cloned()
      61            0 :             .ok_or(TimelineError::NotFound(*ttid))
      62            0 :     }
      63              : }
      64              : 
      65            0 : static TIMELINES_STATE: Lazy<Mutex<GlobalTimelinesState>> = Lazy::new(|| {
      66            0 :     Mutex::new(GlobalTimelinesState {
      67            0 :         timelines: HashMap::new(),
      68            0 :         wal_backup_launcher_tx: None,
      69            0 :         conf: None,
      70            0 :         load_lock: Arc::new(tokio::sync::Mutex::new(TimelineLoadLock)),
      71            0 :     })
      72            0 : });
      73              : 
      74              : /// A zero-sized struct used to manage access to the global timelines map.
      75              : pub struct GlobalTimelines;
      76              : 
      77              : impl GlobalTimelines {
      78              :     /// Inject dependencies needed for the timeline constructors and load all timelines to memory.
      79            0 :     pub async fn init(
      80            0 :         conf: SafeKeeperConf,
      81            0 :         wal_backup_launcher_tx: Sender<TenantTimelineId>,
      82            0 :     ) -> Result<()> {
      83              :         // clippy isn't smart enough to understand that drop(state) releases the
      84              :         // lock, so use explicit block
      85            0 :         let tenants_dir = {
      86            0 :             let mut state = TIMELINES_STATE.lock().unwrap();
      87            0 :             assert!(state.wal_backup_launcher_tx.is_none());
      88            0 :             state.wal_backup_launcher_tx = Some(wal_backup_launcher_tx);
      89            0 :             state.conf = Some(conf);
      90            0 : 
      91            0 :             // Iterate through all directories and load tenants for all directories
      92            0 :             // named as a valid tenant_id.
      93            0 :             state.get_conf().workdir.clone()
      94            0 :         };
      95            0 :         let mut tenant_count = 0;
      96            0 :         for tenants_dir_entry in std::fs::read_dir(&tenants_dir)
      97            0 :             .with_context(|| format!("failed to list tenants dir {}", tenants_dir))?
      98              :         {
      99            0 :             match &tenants_dir_entry {
     100            0 :                 Ok(tenants_dir_entry) => {
     101            0 :                     if let Ok(tenant_id) =
     102            0 :                         TenantId::from_str(tenants_dir_entry.file_name().to_str().unwrap_or(""))
     103              :                     {
     104            0 :                         tenant_count += 1;
     105            0 :                         GlobalTimelines::load_tenant_timelines(tenant_id).await?;
     106            0 :                     }
     107              :                 }
     108            0 :                 Err(e) => error!(
     109            0 :                     "failed to list tenants dir entry {:?} in directory {}, reason: {:?}",
     110              :                     tenants_dir_entry, tenants_dir, e
     111              :                 ),
     112              :             }
     113              :         }
     114              : 
     115            0 :         info!(
     116            0 :             "found {} tenants directories, successfully loaded {} timelines",
     117            0 :             tenant_count,
     118            0 :             TIMELINES_STATE.lock().unwrap().timelines.len()
     119              :         );
     120            0 :         Ok(())
     121            0 :     }
     122              : 
     123              :     /// Loads all timelines for the given tenant to memory. Returns fs::read_dir
     124              :     /// errors if any.
     125              :     ///
     126              :     /// It is async for update_status_notify sake. Since TIMELINES_STATE lock is
     127              :     /// sync and there is no important reason to make it async (it is always
     128              :     /// held for a short while) we just lock and unlock it for each timeline --
     129              :     /// this function is called during init when nothing else is running, so
     130              :     /// this is fine.
     131            0 :     async fn load_tenant_timelines(tenant_id: TenantId) -> Result<()> {
     132            0 :         let (conf, wal_backup_launcher_tx) = {
     133            0 :             let state = TIMELINES_STATE.lock().unwrap();
     134            0 :             (
     135            0 :                 state.get_conf().clone(),
     136            0 :                 state.wal_backup_launcher_tx.as_ref().unwrap().clone(),
     137            0 :             )
     138            0 :         };
     139            0 : 
     140            0 :         let timelines_dir = conf.tenant_dir(&tenant_id);
     141            0 :         for timelines_dir_entry in std::fs::read_dir(&timelines_dir)
     142            0 :             .with_context(|| format!("failed to list timelines dir {}", timelines_dir))?
     143              :         {
     144            0 :             match &timelines_dir_entry {
     145            0 :                 Ok(timeline_dir_entry) => {
     146            0 :                     if let Ok(timeline_id) =
     147            0 :                         TimelineId::from_str(timeline_dir_entry.file_name().to_str().unwrap_or(""))
     148              :                     {
     149            0 :                         let ttid = TenantTimelineId::new(tenant_id, timeline_id);
     150            0 :                         match Timeline::load_timeline(&conf, ttid, wal_backup_launcher_tx.clone()) {
     151            0 :                             Ok(timeline) => {
     152            0 :                                 let tli = Arc::new(timeline);
     153            0 :                                 TIMELINES_STATE
     154            0 :                                     .lock()
     155            0 :                                     .unwrap()
     156            0 :                                     .timelines
     157            0 :                                     .insert(ttid, tli.clone());
     158            0 :                                 tli.bootstrap(&conf);
     159            0 :                                 tli.update_status_notify().await.unwrap();
     160              :                             }
     161              :                             // If we can't load a timeline, it's most likely because of a corrupted
     162              :                             // directory. We will log an error and won't allow to delete/recreate
     163              :                             // this timeline. The only way to fix this timeline is to repair manually
     164              :                             // and restart the safekeeper.
     165            0 :                             Err(e) => error!(
     166            0 :                                 "failed to load timeline {} for tenant {}, reason: {:?}",
     167              :                                 timeline_id, tenant_id, e
     168              :                             ),
     169              :                         }
     170            0 :                     }
     171              :                 }
     172            0 :                 Err(e) => error!(
     173            0 :                     "failed to list timelines dir entry {:?} in directory {}, reason: {:?}",
     174              :                     timelines_dir_entry, timelines_dir, e
     175              :                 ),
     176              :             }
     177              :         }
     178              : 
     179            0 :         Ok(())
     180            0 :     }
     181              : 
     182              :     /// Take a lock for timeline loading.
     183            0 :     pub async fn loading_lock() -> Arc<tokio::sync::Mutex<TimelineLoadLock>> {
     184            0 :         TIMELINES_STATE.lock().unwrap().load_lock.clone()
     185            0 :     }
     186              : 
     187              :     /// Load timeline from disk to the memory.
     188            0 :     pub async fn load_timeline<'a>(
     189            0 :         _guard: &tokio::sync::MutexGuard<'a, TimelineLoadLock>,
     190            0 :         ttid: TenantTimelineId,
     191            0 :     ) -> Result<Arc<Timeline>> {
     192            0 :         let (conf, wal_backup_launcher_tx) = TIMELINES_STATE.lock().unwrap().get_dependencies();
     193            0 : 
     194            0 :         match Timeline::load_timeline(&conf, ttid, wal_backup_launcher_tx) {
     195            0 :             Ok(timeline) => {
     196            0 :                 let tli = Arc::new(timeline);
     197            0 : 
     198            0 :                 // TODO: prevent concurrent timeline creation/loading
     199            0 :                 TIMELINES_STATE
     200            0 :                     .lock()
     201            0 :                     .unwrap()
     202            0 :                     .timelines
     203            0 :                     .insert(ttid, tli.clone());
     204            0 : 
     205            0 :                 tli.bootstrap(&conf);
     206            0 : 
     207            0 :                 Ok(tli)
     208              :             }
     209              :             // If we can't load a timeline, it's bad. Caller will figure it out.
     210            0 :             Err(e) => bail!("failed to load timeline {}, reason: {:?}", ttid, e),
     211              :         }
     212            0 :     }
     213              : 
     214              :     /// Get the number of timelines in the map.
     215            0 :     pub fn timelines_count() -> usize {
     216            0 :         TIMELINES_STATE.lock().unwrap().timelines.len()
     217            0 :     }
     218              : 
     219              :     /// Get the global safekeeper config.
     220            0 :     pub fn get_global_config() -> SafeKeeperConf {
     221            0 :         TIMELINES_STATE.lock().unwrap().get_conf().clone()
     222            0 :     }
     223              : 
     224              :     /// Create a new timeline with the given id. If the timeline already exists, returns
     225              :     /// an existing timeline.
     226            0 :     pub async fn create(
     227            0 :         ttid: TenantTimelineId,
     228            0 :         server_info: ServerInfo,
     229            0 :         commit_lsn: Lsn,
     230            0 :         local_start_lsn: Lsn,
     231            0 :     ) -> Result<Arc<Timeline>> {
     232            0 :         let (conf, wal_backup_launcher_tx) = {
     233            0 :             let state = TIMELINES_STATE.lock().unwrap();
     234            0 :             if let Ok(timeline) = state.get(&ttid) {
     235              :                 // Timeline already exists, return it.
     236            0 :                 return Ok(timeline);
     237            0 :             }
     238            0 :             state.get_dependencies()
     239            0 :         };
     240            0 : 
     241            0 :         info!("creating new timeline {}", ttid);
     242              : 
     243            0 :         let timeline = Arc::new(Timeline::create_empty(
     244            0 :             &conf,
     245            0 :             ttid,
     246            0 :             wal_backup_launcher_tx,
     247            0 :             server_info,
     248            0 :             commit_lsn,
     249            0 :             local_start_lsn,
     250            0 :         )?);
     251              : 
     252              :         // Take a lock and finish the initialization holding this mutex. No other threads
     253              :         // can interfere with creation after we will insert timeline into the map.
     254              :         {
     255            0 :             let mut shared_state = timeline.write_shared_state().await;
     256              : 
     257              :             // We can get a race condition here in case of concurrent create calls, but only
     258              :             // in theory. create() will return valid timeline on the next try.
     259            0 :             TIMELINES_STATE
     260            0 :                 .lock()
     261            0 :                 .unwrap()
     262            0 :                 .try_insert(timeline.clone())?;
     263              : 
     264              :             // Write the new timeline to the disk and start background workers.
     265              :             // Bootstrap is transactional, so if it fails, the timeline will be deleted,
     266              :             // and the state on disk should remain unchanged.
     267            0 :             if let Err(e) = timeline.init_new(&mut shared_state, &conf).await {
     268              :                 // Note: the most likely reason for init failure is that the timeline
     269              :                 // directory already exists on disk. This happens when timeline is corrupted
     270              :                 // and wasn't loaded from disk on startup because of that. We want to preserve
     271              :                 // the timeline directory in this case, for further inspection.
     272              : 
     273              :                 // TODO: this is an unusual error, perhaps we should send it to sentry
     274              :                 // TODO: compute will try to create timeline every second, we should add backoff
     275            0 :                 error!("failed to init new timeline {}: {}", ttid, e);
     276              : 
     277              :                 // Timeline failed to init, it cannot be used. Remove it from the map.
     278            0 :                 TIMELINES_STATE.lock().unwrap().timelines.remove(&ttid);
     279            0 :                 return Err(e);
     280            0 :             }
     281            0 :             // We are done with bootstrap, release the lock, return the timeline.
     282            0 :             // {} block forces release before .await
     283            0 :         }
     284            0 :         timeline.update_status_notify().await?;
     285            0 :         timeline.wal_backup_launcher_tx.send(timeline.ttid).await?;
     286            0 :         Ok(timeline)
     287            0 :     }
     288              : 
     289              :     /// Get a timeline from the global map. If it's not present, it doesn't exist on disk,
     290              :     /// or was corrupted and couldn't be loaded on startup. Returned timeline is always valid,
     291              :     /// i.e. loaded in memory and not cancelled.
     292            0 :     pub fn get(ttid: TenantTimelineId) -> Result<Arc<Timeline>, TimelineError> {
     293            0 :         let res = TIMELINES_STATE.lock().unwrap().get(&ttid);
     294            0 : 
     295            0 :         match res {
     296            0 :             Ok(tli) => {
     297            0 :                 if tli.is_cancelled() {
     298            0 :                     return Err(TimelineError::Cancelled(ttid));
     299            0 :                 }
     300            0 :                 Ok(tli)
     301              :             }
     302            0 :             _ => res,
     303              :         }
     304            0 :     }
     305              : 
     306              :     /// Returns all timelines. This is used for background timeline processes.
     307            0 :     pub fn get_all() -> Vec<Arc<Timeline>> {
     308            0 :         let global_lock = TIMELINES_STATE.lock().unwrap();
     309            0 :         global_lock
     310            0 :             .timelines
     311            0 :             .values()
     312            0 :             .filter(|t| !t.is_cancelled())
     313            0 :             .cloned()
     314            0 :             .collect()
     315            0 :     }
     316              : 
     317              :     /// Returns all timelines belonging to a given tenant. Used for deleting all timelines of a tenant,
     318              :     /// and that's why it can return cancelled timelines, to retry deleting them.
     319            0 :     fn get_all_for_tenant(tenant_id: TenantId) -> Vec<Arc<Timeline>> {
     320            0 :         let global_lock = TIMELINES_STATE.lock().unwrap();
     321            0 :         global_lock
     322            0 :             .timelines
     323            0 :             .values()
     324            0 :             .filter(|t| t.ttid.tenant_id == tenant_id)
     325            0 :             .cloned()
     326            0 :             .collect()
     327            0 :     }
     328              : 
     329              :     /// Cancels timeline, then deletes the corresponding data directory.
     330              :     /// If only_local, doesn't remove WAL segments in remote storage.
     331            0 :     pub async fn delete(
     332            0 :         ttid: &TenantTimelineId,
     333            0 :         only_local: bool,
     334            0 :     ) -> Result<TimelineDeleteForceResult> {
     335            0 :         let tli_res = TIMELINES_STATE.lock().unwrap().get(ttid);
     336            0 :         match tli_res {
     337            0 :             Ok(timeline) => {
     338              :                 // Take a lock and finish the deletion holding this mutex.
     339            0 :                 let mut shared_state = timeline.write_shared_state().await;
     340              : 
     341            0 :                 info!("deleting timeline {}, only_local={}", ttid, only_local);
     342            0 :                 let (dir_existed, was_active) =
     343            0 :                     timeline.delete(&mut shared_state, only_local).await?;
     344              : 
     345              :                 // Remove timeline from the map.
     346              :                 // FIXME: re-enable it once we fix the issue with recreation of deleted timelines
     347              :                 // https://github.com/neondatabase/neon/issues/3146
     348              :                 // TIMELINES_STATE.lock().unwrap().timelines.remove(ttid);
     349              : 
     350            0 :                 Ok(TimelineDeleteForceResult {
     351            0 :                     dir_existed,
     352            0 :                     was_active,
     353            0 :                 })
     354              :             }
     355              :             Err(_) => {
     356              :                 // Timeline is not memory, but it may still exist on disk in broken state.
     357            0 :                 let dir_path = TIMELINES_STATE
     358            0 :                     .lock()
     359            0 :                     .unwrap()
     360            0 :                     .get_conf()
     361            0 :                     .timeline_dir(ttid);
     362            0 :                 let dir_existed = delete_dir(dir_path)?;
     363              : 
     364            0 :                 Ok(TimelineDeleteForceResult {
     365            0 :                     dir_existed,
     366            0 :                     was_active: false,
     367            0 :                 })
     368              :             }
     369              :         }
     370            0 :     }
     371              : 
     372              :     /// Deactivates and deletes all timelines for the tenant. Returns map of all timelines which
     373              :     /// the tenant had, `true` if a timeline was active. There may be a race if new timelines are
     374              :     /// created simultaneously. In that case the function will return error and the caller should
     375              :     /// retry tenant deletion again later.
     376              :     ///
     377              :     /// If only_local, doesn't remove WAL segments in remote storage.
     378            0 :     pub async fn delete_force_all_for_tenant(
     379            0 :         tenant_id: &TenantId,
     380            0 :         only_local: bool,
     381            0 :     ) -> Result<HashMap<TenantTimelineId, TimelineDeleteForceResult>> {
     382            0 :         info!("deleting all timelines for tenant {}", tenant_id);
     383            0 :         let to_delete = Self::get_all_for_tenant(*tenant_id);
     384            0 : 
     385            0 :         let mut err = None;
     386            0 : 
     387            0 :         let mut deleted = HashMap::new();
     388            0 :         for tli in &to_delete {
     389            0 :             match Self::delete(&tli.ttid, only_local).await {
     390            0 :                 Ok(result) => {
     391            0 :                     deleted.insert(tli.ttid, result);
     392            0 :                 }
     393            0 :                 Err(e) => {
     394            0 :                     error!("failed to delete timeline {}: {}", tli.ttid, e);
     395              :                     // Save error to return later.
     396            0 :                     err = Some(e);
     397              :                 }
     398              :             }
     399              :         }
     400              : 
     401              :         // If there was an error, return it.
     402            0 :         if let Some(e) = err {
     403            0 :             return Err(e);
     404            0 :         }
     405            0 : 
     406            0 :         // There may be broken timelines on disk, so delete the whole tenant dir as well.
     407            0 :         // Note that we could concurrently create new timelines while we were deleting them,
     408            0 :         // so the directory may be not empty. In this case timelines will have bad state
     409            0 :         // and timeline background jobs can panic.
     410            0 :         delete_dir(
     411            0 :             TIMELINES_STATE
     412            0 :                 .lock()
     413            0 :                 .unwrap()
     414            0 :                 .get_conf()
     415            0 :                 .tenant_dir(tenant_id),
     416            0 :         )?;
     417              : 
     418              :         // FIXME: we temporarily disabled removing timelines from the map, see `delete_force`
     419              :         // let tlis_after_delete = Self::get_all_for_tenant(*tenant_id);
     420              :         // if !tlis_after_delete.is_empty() {
     421              :         //     // Some timelines were created while we were deleting them, returning error
     422              :         //     // to the caller, so it can retry later.
     423              :         //     bail!(
     424              :         //         "failed to delete all timelines for tenant {}: some timelines were created while we were deleting them",
     425              :         //         tenant_id
     426              :         //     );
     427              :         // }
     428              : 
     429            0 :         Ok(deleted)
     430            0 :     }
     431              : }
     432              : 
     433              : #[derive(Clone, Copy, Serialize)]
     434              : pub struct TimelineDeleteForceResult {
     435              :     pub dir_existed: bool,
     436              :     pub was_active: bool,
     437              : }
     438              : 
     439              : /// Deletes directory and it's contents. Returns false if directory does not exist.
     440            0 : fn delete_dir(path: Utf8PathBuf) -> Result<bool> {
     441            0 :     match std::fs::remove_dir_all(path) {
     442            0 :         Ok(_) => Ok(true),
     443            0 :         Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),
     444            0 :         Err(e) => Err(e.into()),
     445              :     }
     446            0 : }
        

Generated by: LCOV version 2.1-beta