LCOV - code coverage report
Current view: top level - storage_controller/src/service - safekeeper_service.rs (source / functions) Coverage Total Hit
Test: c28d23d327d4ca6acc894004f1432d7b7eea829c.info Lines: 0.0 % 467 0
Test Date: 2025-03-21 14:50:36 Functions: 0.0 % 36 0

            Line data    Source code
       1              : use std::collections::{HashMap, HashSet};
       2              : use std::str::FromStr;
       3              : use std::sync::Arc;
       4              : use std::time::Duration;
       5              : 
       6              : use super::safekeeper_reconciler::ScheduleRequest;
       7              : use crate::heartbeater::SafekeeperState;
       8              : use crate::persistence::{
       9              :     DatabaseError, SafekeeperTimelineOpKind, TimelinePendingOpPersistence, TimelinePersistence,
      10              : };
      11              : use crate::safekeeper::Safekeeper;
      12              : use anyhow::Context;
      13              : use http_utils::error::ApiError;
      14              : use pageserver_api::controller_api::{SafekeeperDescribeResponse, SkSchedulingPolicy};
      15              : use pageserver_api::models::{self, SafekeeperInfo, SafekeepersInfo, TimelineInfo};
      16              : use safekeeper_api::membership::{MemberSet, SafekeeperId};
      17              : use tokio::task::JoinSet;
      18              : use tokio_util::sync::CancellationToken;
      19              : use utils::id::{NodeId, TenantId, TimelineId};
      20              : use utils::logging::SecretString;
      21              : 
      22              : use super::Service;
      23              : 
      24              : impl Service {
      25              :     /// Timeline creation on safekeepers
      26              :     ///
      27              :     /// Returns `Ok(left)` if the timeline has been created on a quorum of safekeepers,
      28              :     /// where `left` contains the list of safekeepers that didn't have a successful response.
      29              :     /// Assumes tenant lock is held while calling this function.
      30            0 :     pub(super) async fn tenant_timeline_create_safekeepers_quorum(
      31            0 :         &self,
      32            0 :         tenant_id: TenantId,
      33            0 :         timeline_id: TimelineId,
      34            0 :         pg_version: u32,
      35            0 :         timeline_persistence: &TimelinePersistence,
      36            0 :     ) -> Result<Vec<NodeId>, ApiError> {
      37            0 :         // If quorum is reached, return if we are outside of a specified timeout
      38            0 :         let jwt = self
      39            0 :             .config
      40            0 :             .safekeeper_jwt_token
      41            0 :             .clone()
      42            0 :             .map(SecretString::from);
      43            0 :         let mut joinset = JoinSet::new();
      44            0 : 
      45            0 :         let safekeepers = {
      46            0 :             let locked = self.inner.read().unwrap();
      47            0 :             locked.safekeepers.clone()
      48            0 :         };
      49            0 : 
      50            0 :         let mut members = Vec::new();
      51            0 :         for sk_id in timeline_persistence.sk_set.iter() {
      52            0 :             let sk_id = NodeId(*sk_id as u64);
      53            0 :             let Some(safekeeper) = safekeepers.get(&sk_id) else {
      54            0 :                 return Err(ApiError::InternalServerError(anyhow::anyhow!(
      55            0 :                     "couldn't find entry for safekeeper with id {sk_id}"
      56            0 :                 )))?;
      57              :             };
      58            0 :             members.push(SafekeeperId {
      59            0 :                 id: sk_id,
      60            0 :                 host: safekeeper.skp.host.clone(),
      61            0 :                 pg_port: safekeeper.skp.port as u16,
      62            0 :             });
      63              :         }
      64            0 :         let mset = MemberSet::new(members).map_err(ApiError::InternalServerError)?;
      65            0 :         let mconf = safekeeper_api::membership::Configuration::new(mset);
      66            0 : 
      67            0 :         let req = safekeeper_api::models::TimelineCreateRequest {
      68            0 :             commit_lsn: None,
      69            0 :             mconf,
      70            0 :             pg_version,
      71            0 :             start_lsn: timeline_persistence.start_lsn.0,
      72            0 :             system_id: None,
      73            0 :             tenant_id,
      74            0 :             timeline_id,
      75            0 :             wal_seg_size: None,
      76            0 :         };
      77              :         const SK_CREATE_TIMELINE_RECONCILE_TIMEOUT: Duration = Duration::from_secs(30);
      78            0 :         for sk in timeline_persistence.sk_set.iter() {
      79            0 :             let sk_id = NodeId(*sk as u64);
      80            0 :             let safekeepers = safekeepers.clone();
      81            0 :             let http_client = self.http_client.clone();
      82            0 :             let jwt = jwt.clone();
      83            0 :             let req = req.clone();
      84            0 :             joinset.spawn(async move {
      85            0 :                 // Unwrap is fine as we already would have returned error above
      86            0 :                 let sk_p = safekeepers.get(&sk_id).unwrap();
      87            0 :                 let res = sk_p
      88            0 :                     .with_client_retries(
      89            0 :                         |client| {
      90            0 :                             let req = req.clone();
      91            0 :                             async move { client.create_timeline(&req).await }
      92            0 :                         },
      93            0 :                         &http_client,
      94            0 :                         &jwt,
      95            0 :                         3,
      96            0 :                         3,
      97            0 :                         SK_CREATE_TIMELINE_RECONCILE_TIMEOUT,
      98            0 :                         &CancellationToken::new(),
      99            0 :                     )
     100            0 :                     .await;
     101            0 :                 (sk_id, sk_p.skp.host.clone(), res)
     102            0 :             });
     103            0 :         }
     104              :         // After we have built the joinset, we now wait for the tasks to complete,
     105              :         // but with a specified timeout to make sure we return swiftly, either with
     106              :         // a failure or success.
     107            0 :         let reconcile_deadline = tokio::time::Instant::now() + SK_CREATE_TIMELINE_RECONCILE_TIMEOUT;
     108            0 : 
     109            0 :         // Wait until all tasks finish or timeout is hit, whichever occurs
     110            0 :         // first.
     111            0 :         let mut reconcile_results = Vec::new();
     112              :         loop {
     113            0 :             if let Ok(res) = tokio::time::timeout_at(reconcile_deadline, joinset.join_next()).await
     114              :             {
     115            0 :                 let Some(res) = res else { break };
     116            0 :                 match res {
     117            0 :                     Ok(res) => {
     118            0 :                         tracing::info!(
     119            0 :                             "response from safekeeper id:{} at {}: {:?}",
     120              :                             res.0,
     121              :                             res.1,
     122              :                             res.2
     123              :                         );
     124            0 :                         reconcile_results.push(res);
     125              :                     }
     126            0 :                     Err(join_err) => {
     127            0 :                         tracing::info!("join_err for task in joinset: {join_err}");
     128              :                     }
     129              :                 }
     130              :             } else {
     131            0 :                 tracing::info!(
     132            0 :                     "timeout for creation call after {} responses",
     133            0 :                     reconcile_results.len()
     134              :                 );
     135            0 :                 break;
     136              :             }
     137              :         }
     138              : 
     139              :         // Now check now if quorum was reached in reconcile_results.
     140            0 :         let total_result_count = reconcile_results.len();
     141            0 :         let remaining = reconcile_results
     142            0 :             .into_iter()
     143            0 :             .filter_map(|res| res.2.is_err().then_some(res.0))
     144            0 :             .collect::<Vec<_>>();
     145            0 :         tracing::info!(
     146            0 :             "Got {} non-successful responses from initial creation request of total {total_result_count} responses",
     147            0 :             remaining.len()
     148              :         );
     149            0 :         if remaining.len() >= 2 {
     150              :             // Failure
     151            0 :             return Err(ApiError::InternalServerError(anyhow::anyhow!(
     152            0 :                 "not enough successful reconciliations to reach quorum, please retry: {} errored",
     153            0 :                 remaining.len()
     154            0 :             )));
     155            0 :         }
     156            0 : 
     157            0 :         Ok(remaining)
     158            0 :     }
     159              : 
     160              :     /// Create timeline in controller database and on safekeepers.
     161              :     /// `timeline_info` is result of timeline creation on pageserver.
     162              :     ///
     163              :     /// All actions must be idempotent as the call is retried until success. It
     164              :     /// tries to create timeline in the db and on at least majority of
     165              :     /// safekeepers + queue creation for safekeepers which missed it in the db
     166              :     /// for infinite retries; after that, call returns Ok.
     167              :     ///
     168              :     /// The idea is that once this is reached as long as we have alive majority
     169              :     /// of safekeepers it is expected to get eventually operational as storcon
     170              :     /// will be able to seed timeline on nodes which missed creation by making
     171              :     /// pull_timeline from peers. On the other hand we don't want to fail
     172              :     /// timeline creation if one safekeeper is down.
     173            0 :     pub(super) async fn tenant_timeline_create_safekeepers(
     174            0 :         self: &Arc<Self>,
     175            0 :         tenant_id: TenantId,
     176            0 :         timeline_info: &TimelineInfo,
     177            0 :         create_mode: models::TimelineCreateRequestMode,
     178            0 :     ) -> Result<SafekeepersInfo, ApiError> {
     179            0 :         let timeline_id = timeline_info.timeline_id;
     180            0 :         let pg_version = timeline_info.pg_version * 10000;
     181              :         // Initially start_lsn is determined by last_record_lsn in pageserver
     182              :         // response as it does initdb. However, later we persist it and in sk
     183              :         // creation calls replace with the value from the timeline row if it
     184              :         // previously existed as on retries in theory endpoint might have
     185              :         // already written some data and advanced last_record_lsn, while we want
     186              :         // safekeepers to have consistent start_lsn.
     187            0 :         let start_lsn = match create_mode {
     188            0 :             models::TimelineCreateRequestMode::Bootstrap { .. } => timeline_info.last_record_lsn,
     189            0 :             models::TimelineCreateRequestMode::Branch { .. } => timeline_info.last_record_lsn,
     190              :             models::TimelineCreateRequestMode::ImportPgdata { .. } => {
     191            0 :                 return Err(ApiError::InternalServerError(anyhow::anyhow!(
     192            0 :                     "import pgdata doesn't specify the start lsn, aborting creation on safekeepers"
     193            0 :                 )))?;
     194              :             }
     195              :         };
     196              :         // Choose initial set of safekeepers respecting affinity
     197            0 :         let sks = self.safekeepers_for_new_timeline().await?;
     198            0 :         let sks_persistence = sks.iter().map(|sk| sk.id.0 as i64).collect::<Vec<_>>();
     199            0 :         // Add timeline to db
     200            0 :         let mut timeline_persist = TimelinePersistence {
     201            0 :             tenant_id: tenant_id.to_string(),
     202            0 :             timeline_id: timeline_id.to_string(),
     203            0 :             start_lsn: start_lsn.into(),
     204            0 :             generation: 0,
     205            0 :             sk_set: sks_persistence.clone(),
     206            0 :             new_sk_set: None,
     207            0 :             cplane_notified_generation: 0,
     208            0 :             deleted_at: None,
     209            0 :         };
     210            0 :         let inserted = self
     211            0 :             .persistence
     212            0 :             .insert_timeline(timeline_persist.clone())
     213            0 :             .await?;
     214            0 :         if !inserted {
     215            0 :             if let Some(existent_persist) = self
     216            0 :                 .persistence
     217            0 :                 .get_timeline(tenant_id, timeline_id)
     218            0 :                 .await?
     219            0 :             {
     220            0 :                 // Replace with what we have in the db, to get stuff like the generation right.
     221            0 :                 // We do still repeat the http calls to the safekeepers. After all, we could have
     222            0 :                 // crashed right after the wrote to the DB.
     223            0 :                 timeline_persist = existent_persist;
     224            0 :             } else {
     225            0 :                 return Err(ApiError::InternalServerError(anyhow::anyhow!(
     226            0 :                     "insertion said timeline already in db, but looking it up, it was gone"
     227            0 :                 )));
     228              :             }
     229            0 :         }
     230              :         // Create the timeline on a quorum of safekeepers
     231            0 :         let remaining = self
     232            0 :             .tenant_timeline_create_safekeepers_quorum(
     233            0 :                 tenant_id,
     234            0 :                 timeline_id,
     235            0 :                 pg_version,
     236            0 :                 &timeline_persist,
     237            0 :             )
     238            0 :             .await?;
     239              : 
     240              :         // For the remaining safekeepers, take care of their reconciliation asynchronously
     241            0 :         for &remaining_id in remaining.iter() {
     242            0 :             let pending_op = TimelinePendingOpPersistence {
     243            0 :                 tenant_id: tenant_id.to_string(),
     244            0 :                 timeline_id: timeline_id.to_string(),
     245            0 :                 generation: timeline_persist.generation,
     246            0 :                 op_kind: crate::persistence::SafekeeperTimelineOpKind::Pull,
     247            0 :                 sk_id: remaining_id.0 as i64,
     248            0 :             };
     249            0 :             tracing::info!("writing pending op for sk id {remaining_id}");
     250            0 :             self.persistence.insert_pending_op(pending_op).await?;
     251              :         }
     252            0 :         if !remaining.is_empty() {
     253            0 :             let mut locked = self.inner.write().unwrap();
     254            0 :             for remaining_id in remaining {
     255            0 :                 let Some(sk) = locked.safekeepers.get(&remaining_id) else {
     256            0 :                     return Err(ApiError::InternalServerError(anyhow::anyhow!(
     257            0 :                         "Couldn't find safekeeper with id {remaining_id}"
     258            0 :                     )));
     259              :                 };
     260            0 :                 let Ok(host_list) = sks
     261            0 :                     .iter()
     262            0 :                     .map(|sk| {
     263            0 :                         Ok((
     264            0 :                             sk.id,
     265            0 :                             locked
     266            0 :                                 .safekeepers
     267            0 :                                 .get(&sk.id)
     268            0 :                                 .ok_or_else(|| {
     269            0 :                                     ApiError::InternalServerError(anyhow::anyhow!(
     270            0 :                                         "Couldn't find safekeeper with id {} to pull from",
     271            0 :                                         sk.id
     272            0 :                                     ))
     273            0 :                                 })?
     274            0 :                                 .base_url(),
     275              :                         ))
     276            0 :                     })
     277            0 :                     .collect::<Result<_, ApiError>>()
     278              :                 else {
     279            0 :                     continue;
     280              :                 };
     281            0 :                 let req = ScheduleRequest {
     282            0 :                     safekeeper: Box::new(sk.clone()),
     283            0 :                     host_list,
     284            0 :                     tenant_id,
     285            0 :                     timeline_id: Some(timeline_id),
     286            0 :                     generation: timeline_persist.generation as u32,
     287            0 :                     kind: crate::persistence::SafekeeperTimelineOpKind::Pull,
     288            0 :                 };
     289            0 :                 locked.safekeeper_reconcilers.schedule_request(self, req);
     290              :             }
     291            0 :         }
     292              : 
     293            0 :         Ok(SafekeepersInfo {
     294            0 :             generation: timeline_persist.generation as u32,
     295            0 :             safekeepers: sks,
     296            0 :             tenant_id,
     297            0 :             timeline_id,
     298            0 :         })
     299            0 :     }
     300              :     /// Perform timeline deletion on safekeepers. Will return success: we persist the deletion into the reconciler.
     301            0 :     pub(super) async fn tenant_timeline_delete_safekeepers(
     302            0 :         self: &Arc<Self>,
     303            0 :         tenant_id: TenantId,
     304            0 :         timeline_id: TimelineId,
     305            0 :     ) -> Result<(), ApiError> {
     306            0 :         let tl = self
     307            0 :             .persistence
     308            0 :             .get_timeline(tenant_id, timeline_id)
     309            0 :             .await?;
     310            0 :         let Some(tl) = tl else {
     311            0 :             tracing::info!(
     312            0 :                 "timeline {tenant_id}/{timeline_id} doesn't exist in timelines table, no deletions on safekeepers needed"
     313              :             );
     314            0 :             return Ok(());
     315              :         };
     316            0 :         let all_sks = tl
     317            0 :             .new_sk_set
     318            0 :             .iter()
     319            0 :             .flat_map(|sks| {
     320            0 :                 sks.iter()
     321            0 :                     .map(|sk| (*sk, SafekeeperTimelineOpKind::Exclude))
     322            0 :             })
     323            0 :             .chain(
     324            0 :                 tl.sk_set
     325            0 :                     .iter()
     326            0 :                     .map(|v| (*v, SafekeeperTimelineOpKind::Delete)),
     327            0 :             )
     328            0 :             .collect::<HashMap<_, _>>();
     329            0 : 
     330            0 :         // Schedule reconciliations
     331            0 :         {
     332            0 :             let mut locked = self.inner.write().unwrap();
     333            0 :             for (sk_id, kind) in all_sks {
     334            0 :                 let sk_id = NodeId(sk_id as u64);
     335            0 :                 let Some(sk) = locked.safekeepers.get(&sk_id) else {
     336            0 :                     return Err(ApiError::InternalServerError(anyhow::anyhow!(
     337            0 :                         "Couldn't find safekeeper with id {sk_id}"
     338            0 :                     )));
     339              :                 };
     340              : 
     341            0 :                 let req = ScheduleRequest {
     342            0 :                     safekeeper: Box::new(sk.clone()),
     343            0 :                     // we don't use this for this kind, put a dummy value
     344            0 :                     host_list: Vec::new(),
     345            0 :                     tenant_id,
     346            0 :                     timeline_id: Some(timeline_id),
     347            0 :                     generation: tl.generation as u32,
     348            0 :                     kind,
     349            0 :                 };
     350            0 :                 locked.safekeeper_reconcilers.schedule_request(self, req);
     351              :             }
     352              :         }
     353            0 :         Ok(())
     354            0 :     }
     355              : 
     356              :     /// Perform tenant deletion on safekeepers.
     357            0 :     pub(super) async fn tenant_delete_safekeepers(
     358            0 :         self: &Arc<Self>,
     359            0 :         tenant_id: TenantId,
     360            0 :     ) -> Result<(), ApiError> {
     361            0 :         let timeline_list = self
     362            0 :             .persistence
     363            0 :             .list_timelines_for_tenant(tenant_id)
     364            0 :             .await?;
     365              : 
     366            0 :         if timeline_list.is_empty() {
     367              :             // Early exit: the tenant is either empty or not migrated to the storcon yet
     368            0 :             tracing::info!("Skipping tenant delete as the timeline doesn't exist in db");
     369            0 :             return Ok(());
     370            0 :         }
     371              : 
     372            0 :         let timeline_list = timeline_list
     373            0 :             .into_iter()
     374            0 :             .map(|timeline| {
     375            0 :                 let timeline_id = TimelineId::from_str(&timeline.timeline_id)
     376            0 :                     .context("timeline id loaded from db")
     377            0 :                     .map_err(ApiError::InternalServerError)?;
     378            0 :                 Ok((timeline_id, timeline))
     379            0 :             })
     380            0 :             .collect::<Result<Vec<_>, ApiError>>()?;
     381              : 
     382              :         // Remove pending ops from db.
     383              :         // We cancel them in a later iteration once we hold the state lock.
     384            0 :         for (timeline_id, _timeline) in timeline_list.iter() {
     385            0 :             self.persistence
     386            0 :                 .remove_pending_ops_for_timeline(tenant_id, Some(*timeline_id))
     387            0 :                 .await?;
     388              :         }
     389              : 
     390            0 :         let mut locked = self.inner.write().unwrap();
     391            0 : 
     392            0 :         // The list of safekeepers that have any of the timelines
     393            0 :         let mut sk_list = HashSet::new();
     394              : 
     395              :         // List all pending ops for all timelines, cancel them
     396            0 :         for (timeline_id, timeline) in timeline_list.iter() {
     397            0 :             let sk_iter = timeline
     398            0 :                 .sk_set
     399            0 :                 .iter()
     400            0 :                 .chain(timeline.new_sk_set.iter().flatten())
     401            0 :                 .map(|id| NodeId(*id as u64));
     402            0 :             for sk_id in sk_iter.clone() {
     403            0 :                 locked
     404            0 :                     .safekeeper_reconcilers
     405            0 :                     .cancel_reconciles_for_timeline(sk_id, tenant_id, Some(*timeline_id));
     406            0 :             }
     407            0 :             sk_list.extend(sk_iter);
     408              :         }
     409              : 
     410              :         // unwrap is safe: we return above for an empty timeline list
     411            0 :         let max_generation = timeline_list
     412            0 :             .iter()
     413            0 :             .map(|(_tl_id, tl)| tl.generation as u32)
     414            0 :             .max()
     415            0 :             .unwrap();
     416              : 
     417            0 :         for sk_id in sk_list {
     418            0 :             let Some(safekeeper) = locked.safekeepers.get(&sk_id) else {
     419            0 :                 tracing::warn!("Couldn't find safekeeper with id {sk_id}");
     420            0 :                 continue;
     421              :             };
     422              :             // Add pending op for tenant deletion
     423            0 :             let req = ScheduleRequest {
     424            0 :                 generation: max_generation,
     425            0 :                 host_list: Vec::new(),
     426            0 :                 kind: SafekeeperTimelineOpKind::Delete,
     427            0 :                 safekeeper: Box::new(safekeeper.clone()),
     428            0 :                 tenant_id,
     429            0 :                 timeline_id: None,
     430            0 :             };
     431            0 :             locked.safekeeper_reconcilers.schedule_request(self, req);
     432              :         }
     433            0 :         Ok(())
     434            0 :     }
     435              : 
     436              :     /// Choose safekeepers for the new timeline: 3 in different azs.
     437            0 :     pub(crate) async fn safekeepers_for_new_timeline(
     438            0 :         &self,
     439            0 :     ) -> Result<Vec<SafekeeperInfo>, ApiError> {
     440            0 :         // Number of safekeepers in different AZs we are looking for
     441            0 :         let wanted_count = 3;
     442            0 :         let mut all_safekeepers = {
     443            0 :             let locked = self.inner.read().unwrap();
     444            0 :             locked
     445            0 :                 .safekeepers
     446            0 :                 .iter()
     447            0 :                 .filter_map(|sk| {
     448            0 :                     if sk.1.scheduling_policy() != SkSchedulingPolicy::Active {
     449              :                         // If we don't want to schedule stuff onto the safekeeper, respect that.
     450            0 :                         return None;
     451            0 :                     }
     452            0 :                     let utilization_opt = if let SafekeeperState::Available {
     453              :                         last_seen_at: _,
     454            0 :                         utilization,
     455            0 :                     } = sk.1.availability()
     456              :                     {
     457            0 :                         Some(utilization)
     458              :                     } else {
     459              :                         // non-available safekeepers still get a chance for new timelines,
     460              :                         // but put them last in the list.
     461            0 :                         None
     462              :                     };
     463            0 :                     let info = SafekeeperInfo {
     464            0 :                         hostname: sk.1.skp.host.clone(),
     465            0 :                         id: NodeId(sk.1.skp.id as u64),
     466            0 :                     };
     467            0 :                     Some((utilization_opt, info, sk.1.skp.availability_zone_id.clone()))
     468            0 :                 })
     469            0 :                 .collect::<Vec<_>>()
     470            0 :         };
     471            0 :         all_safekeepers.sort_by_key(|sk| {
     472            0 :             (
     473            0 :                 sk.0.as_ref()
     474            0 :                     .map(|ut| ut.timeline_count)
     475            0 :                     .unwrap_or(u64::MAX),
     476            0 :                 // Use the id to decide on equal scores for reliability
     477            0 :                 sk.1.id.0,
     478            0 :             )
     479            0 :         });
     480            0 :         let mut sks = Vec::new();
     481            0 :         let mut azs = HashSet::new();
     482            0 :         for (_sk_util, sk_info, az_id) in all_safekeepers.iter() {
     483            0 :             if !azs.insert(az_id) {
     484            0 :                 continue;
     485            0 :             }
     486            0 :             sks.push(sk_info.clone());
     487            0 :             if sks.len() == wanted_count {
     488            0 :                 break;
     489            0 :             }
     490              :         }
     491            0 :         if sks.len() == wanted_count {
     492            0 :             Ok(sks)
     493              :         } else {
     494            0 :             Err(ApiError::InternalServerError(anyhow::anyhow!(
     495            0 :                 "couldn't find {wanted_count} safekeepers in different AZs for new timeline (found: {}, total active: {})",
     496            0 :                 sks.len(),
     497            0 :                 all_safekeepers.len(),
     498            0 :             )))
     499              :         }
     500            0 :     }
     501              : 
     502            0 :     pub(crate) async fn safekeepers_list(
     503            0 :         &self,
     504            0 :     ) -> Result<Vec<SafekeeperDescribeResponse>, DatabaseError> {
     505            0 :         let locked = self.inner.read().unwrap();
     506            0 :         let mut list = locked
     507            0 :             .safekeepers
     508            0 :             .iter()
     509            0 :             .map(|sk| sk.1.describe_response())
     510            0 :             .collect::<Result<Vec<_>, _>>()?;
     511            0 :         list.sort_by_key(|v| v.id);
     512            0 :         Ok(list)
     513            0 :     }
     514              : 
     515            0 :     pub(crate) async fn get_safekeeper(
     516            0 :         &self,
     517            0 :         id: i64,
     518            0 :     ) -> Result<SafekeeperDescribeResponse, DatabaseError> {
     519            0 :         let locked = self.inner.read().unwrap();
     520            0 :         let sk = locked
     521            0 :             .safekeepers
     522            0 :             .get(&NodeId(id as u64))
     523            0 :             .ok_or(diesel::result::Error::NotFound)?;
     524            0 :         sk.describe_response()
     525            0 :     }
     526              : 
     527            0 :     pub(crate) async fn upsert_safekeeper(
     528            0 :         &self,
     529            0 :         record: crate::persistence::SafekeeperUpsert,
     530            0 :     ) -> Result<(), ApiError> {
     531            0 :         let node_id = NodeId(record.id as u64);
     532            0 :         let use_https = self.config.use_https_safekeeper_api;
     533            0 : 
     534            0 :         if use_https && record.https_port.is_none() {
     535            0 :             return Err(ApiError::PreconditionFailed(
     536            0 :                 format!(
     537            0 :                     "cannot upsert safekeeper {node_id}: \
     538            0 :                     https is enabled, but https port is not specified"
     539            0 :                 )
     540            0 :                 .into(),
     541            0 :             ));
     542            0 :         }
     543            0 : 
     544            0 :         self.persistence.safekeeper_upsert(record.clone()).await?;
     545              :         {
     546            0 :             let mut locked = self.inner.write().unwrap();
     547            0 :             let mut safekeepers = (*locked.safekeepers).clone();
     548            0 :             match safekeepers.entry(node_id) {
     549            0 :                 std::collections::hash_map::Entry::Occupied(mut entry) => entry
     550            0 :                     .get_mut()
     551            0 :                     .update_from_record(record)
     552            0 :                     .expect("all preconditions should be checked before upsert to database"),
     553            0 :                 std::collections::hash_map::Entry::Vacant(entry) => {
     554            0 :                     entry.insert(
     555            0 :                         Safekeeper::from_persistence(
     556            0 :                             crate::persistence::SafekeeperPersistence::from_upsert(
     557            0 :                                 record,
     558            0 :                                 SkSchedulingPolicy::Pause,
     559            0 :                             ),
     560            0 :                             CancellationToken::new(),
     561            0 :                             use_https,
     562            0 :                         )
     563            0 :                         .expect("all preconditions should be checked before upsert to database"),
     564            0 :                     );
     565            0 :                 }
     566              :             }
     567            0 :             locked.safekeepers = Arc::new(safekeepers);
     568            0 :         }
     569            0 :         Ok(())
     570            0 :     }
     571              : 
     572            0 :     pub(crate) async fn set_safekeeper_scheduling_policy(
     573            0 :         &self,
     574            0 :         id: i64,
     575            0 :         scheduling_policy: SkSchedulingPolicy,
     576            0 :     ) -> Result<(), DatabaseError> {
     577            0 :         self.persistence
     578            0 :             .set_safekeeper_scheduling_policy(id, scheduling_policy)
     579            0 :             .await?;
     580            0 :         let node_id = NodeId(id as u64);
     581            0 :         // After the change has been persisted successfully, update the in-memory state
     582            0 :         {
     583            0 :             let mut locked = self.inner.write().unwrap();
     584            0 :             let mut safekeepers = (*locked.safekeepers).clone();
     585            0 :             let sk = safekeepers
     586            0 :                 .get_mut(&node_id)
     587            0 :                 .ok_or(DatabaseError::Logical("Not found".to_string()))?;
     588            0 :             sk.set_scheduling_policy(scheduling_policy);
     589            0 : 
     590            0 :             match scheduling_policy {
     591            0 :                 SkSchedulingPolicy::Active => (),
     592            0 :                 SkSchedulingPolicy::Decomissioned | SkSchedulingPolicy::Pause => {
     593            0 :                     locked.safekeeper_reconcilers.cancel_safekeeper(node_id);
     594            0 :                 }
     595              :             }
     596              : 
     597            0 :             locked.safekeepers = Arc::new(safekeepers);
     598            0 :         }
     599            0 :         Ok(())
     600            0 :     }
     601              : }
        

Generated by: LCOV version 2.1-beta