LCOV - code coverage report
Current view: top level - storage_controller/src - node.rs (source / functions) Coverage Total Hit
Test: 98683a8629f0f7f0031d02e04512998d589d76ea.info Lines: 29.5 % 241 71
Test Date: 2025-04-11 16:58:57 Functions: 7.1 % 99 7

            Line data    Source code
       1              : use std::str::FromStr;
       2              : use std::time::Duration;
       3              : 
       4              : use pageserver_api::controller_api::{
       5              :     AvailabilityZone, NodeAvailability, NodeDescribeResponse, NodeRegisterRequest,
       6              :     NodeSchedulingPolicy, TenantLocateResponseShard,
       7              : };
       8              : use pageserver_api::shard::TenantShardId;
       9              : use pageserver_client::mgmt_api;
      10              : use reqwest::StatusCode;
      11              : use serde::Serialize;
      12              : use tokio_util::sync::CancellationToken;
      13              : use utils::backoff;
      14              : use utils::id::NodeId;
      15              : 
      16              : use crate::pageserver_client::PageserverClient;
      17              : use crate::persistence::NodePersistence;
      18              : use crate::scheduler::MaySchedule;
      19              : 
      20              : /// Represents the in-memory description of a Node.
      21              : ///
      22              : /// Scheduling statistics are maintened separately in [`crate::scheduler`].
      23              : ///
      24              : /// The persistent subset of the Node is defined in [`crate::persistence::NodePersistence`]: the
      25              : /// implementation of serialization on this type is only for debug dumps.
      26              : #[derive(Clone, Serialize)]
      27              : pub(crate) struct Node {
      28              :     id: NodeId,
      29              : 
      30              :     availability: NodeAvailability,
      31              :     scheduling: NodeSchedulingPolicy,
      32              : 
      33              :     listen_http_addr: String,
      34              :     listen_http_port: u16,
      35              :     listen_https_port: Option<u16>,
      36              : 
      37              :     listen_pg_addr: String,
      38              :     listen_pg_port: u16,
      39              : 
      40              :     availability_zone_id: AvailabilityZone,
      41              : 
      42              :     // Flag from storcon's config to use https for pageserver admin API.
      43              :     // Invariant: if |true|, listen_https_port should contain a value.
      44              :     use_https: bool,
      45              :     // This cancellation token means "stop any RPCs in flight to this node, and don't start
      46              :     // any more". It is not related to process shutdown.
      47              :     #[serde(skip)]
      48              :     cancel: CancellationToken,
      49              : }
      50              : 
      51              : /// When updating [`Node::availability`] we use this type to indicate to the caller
      52              : /// whether/how they changed it.
      53              : pub(crate) enum AvailabilityTransition {
      54              :     ToActive,
      55              :     ToWarmingUpFromActive,
      56              :     ToWarmingUpFromOffline,
      57              :     ToOffline,
      58              :     Unchanged,
      59              : }
      60              : 
      61              : impl Node {
      62            0 :     pub(crate) fn base_url(&self) -> String {
      63            0 :         if self.use_https {
      64            0 :             format!(
      65            0 :                 "https://{}:{}",
      66            0 :                 self.listen_http_addr,
      67            0 :                 self.listen_https_port
      68            0 :                     .expect("https port should be specified if use_https is on")
      69            0 :             )
      70              :         } else {
      71            0 :             format!("http://{}:{}", self.listen_http_addr, self.listen_http_port)
      72              :         }
      73            0 :     }
      74              : 
      75          285 :     pub(crate) fn get_id(&self) -> NodeId {
      76          285 :         self.id
      77          285 :     }
      78              : 
      79              :     #[allow(unused)]
      80        25481 :     pub(crate) fn get_availability_zone_id(&self) -> &AvailabilityZone {
      81        25481 :         &self.availability_zone_id
      82        25481 :     }
      83              : 
      84            0 :     pub(crate) fn get_scheduling(&self) -> NodeSchedulingPolicy {
      85            0 :         self.scheduling
      86            0 :     }
      87              : 
      88            0 :     pub(crate) fn set_scheduling(&mut self, scheduling: NodeSchedulingPolicy) {
      89            0 :         self.scheduling = scheduling
      90            0 :     }
      91              : 
      92            0 :     pub(crate) fn has_https_port(&self) -> bool {
      93            0 :         self.listen_https_port.is_some()
      94            0 :     }
      95              : 
      96              :     /// Does this registration request match `self`?  This is used when deciding whether a registration
      97              :     /// request should be allowed to update an existing record with the same node ID.
      98            0 :     pub(crate) fn registration_match(&self, register_req: &NodeRegisterRequest) -> bool {
      99            0 :         self.id == register_req.node_id
     100            0 :             && self.listen_http_addr == register_req.listen_http_addr
     101            0 :             && self.listen_http_port == register_req.listen_http_port
     102              :             // Note: listen_https_port may change. See [`Self::need_update`] for mode details.
     103              :             // && self.listen_https_port == register_req.listen_https_port
     104            0 :             && self.listen_pg_addr == register_req.listen_pg_addr
     105            0 :             && self.listen_pg_port == register_req.listen_pg_port
     106            0 :             && self.availability_zone_id == register_req.availability_zone_id
     107            0 :     }
     108              : 
     109              :     // Do we need to update an existing record in DB on this registration request?
     110            0 :     pub(crate) fn need_update(&self, register_req: &NodeRegisterRequest) -> bool {
     111            0 :         // listen_https_port is checked here because it may change during migration to https.
     112            0 :         // After migration, this check may be moved to registration_match.
     113            0 :         self.listen_https_port != register_req.listen_https_port
     114            0 :     }
     115              : 
     116              :     /// For a shard located on this node, populate a response object
     117              :     /// with this node's address information.
     118            0 :     pub(crate) fn shard_location(&self, shard_id: TenantShardId) -> TenantLocateResponseShard {
     119            0 :         TenantLocateResponseShard {
     120            0 :             shard_id,
     121            0 :             node_id: self.id,
     122            0 :             listen_http_addr: self.listen_http_addr.clone(),
     123            0 :             listen_http_port: self.listen_http_port,
     124            0 :             listen_https_port: self.listen_https_port,
     125            0 :             listen_pg_addr: self.listen_pg_addr.clone(),
     126            0 :             listen_pg_port: self.listen_pg_port,
     127            0 :         }
     128            0 :     }
     129              : 
     130            0 :     pub(crate) fn get_availability(&self) -> &NodeAvailability {
     131            0 :         &self.availability
     132            0 :     }
     133              : 
     134          282 :     pub(crate) fn set_availability(&mut self, availability: NodeAvailability) {
     135              :         use AvailabilityTransition::*;
     136              :         use NodeAvailability::WarmingUp;
     137              : 
     138          282 :         match self.get_availability_transition(&availability) {
     139          278 :             ToActive => {
     140          278 :                 // Give the node a new cancellation token, effectively resetting it to un-cancelled.  Any
     141          278 :                 // users of previously-cloned copies of the node will still see the old cancellation
     142          278 :                 // state.  For example, Reconcilers in flight will have to complete and be spawned
     143          278 :                 // again to realize that the node has become available.
     144          278 :                 self.cancel = CancellationToken::new();
     145          278 :             }
     146            2 :             ToOffline | ToWarmingUpFromActive => {
     147            2 :                 // Fire the node's cancellation token to cancel any in-flight API requests to it
     148            2 :                 self.cancel.cancel();
     149            2 :             }
     150            2 :             Unchanged | ToWarmingUpFromOffline => {}
     151              :         }
     152              : 
     153          282 :         if let (WarmingUp(crnt), WarmingUp(proposed)) = (&self.availability, &availability) {
     154            0 :             self.availability = WarmingUp(std::cmp::max(*crnt, *proposed));
     155          282 :         } else {
     156          282 :             self.availability = availability;
     157          282 :         }
     158          282 :     }
     159              : 
     160              :     /// Without modifying the availability of the node, convert the intended availability
     161              :     /// into a description of the transition.
     162          282 :     pub(crate) fn get_availability_transition(
     163          282 :         &self,
     164          282 :         availability: &NodeAvailability,
     165          282 :     ) -> AvailabilityTransition {
     166              :         use AvailabilityTransition::*;
     167              :         use NodeAvailability::*;
     168              : 
     169          282 :         match (&self.availability, availability) {
     170          278 :             (Offline, Active(_)) => ToActive,
     171            2 :             (Active(_), Offline) => ToOffline,
     172            0 :             (Active(_), WarmingUp(_)) => ToWarmingUpFromActive,
     173            0 :             (WarmingUp(_), Offline) => ToOffline,
     174            0 :             (WarmingUp(_), Active(_)) => ToActive,
     175            0 :             (Offline, WarmingUp(_)) => ToWarmingUpFromOffline,
     176            2 :             _ => Unchanged,
     177              :         }
     178          282 :     }
     179              : 
     180              :     /// Whether we may send API requests to this node.
     181          278 :     pub(crate) fn is_available(&self) -> bool {
     182              :         // When we clone a node, [`Self::availability`] is a snapshot, but [`Self::cancel`] holds
     183              :         // a reference to the original Node's cancellation status.  Checking both of these results
     184              :         // in a "pessimistic" check where we will consider a Node instance unavailable if it was unavailable
     185              :         // when we cloned it, or if the original Node instance's cancellation token was fired.
     186          278 :         matches!(self.availability, NodeAvailability::Active(_)) && !self.cancel.is_cancelled()
     187          278 :     }
     188              : 
     189              :     /// Is this node elegible to have work scheduled onto it?
     190          285 :     pub(crate) fn may_schedule(&self) -> MaySchedule {
     191          285 :         let utilization = match &self.availability {
     192          283 :             NodeAvailability::Active(u) => u.clone(),
     193            2 :             NodeAvailability::Offline | NodeAvailability::WarmingUp(_) => return MaySchedule::No,
     194              :         };
     195              : 
     196          283 :         match self.scheduling {
     197          283 :             NodeSchedulingPolicy::Active => MaySchedule::Yes(utilization),
     198            0 :             NodeSchedulingPolicy::Draining => MaySchedule::No,
     199            0 :             NodeSchedulingPolicy::Filling => MaySchedule::Yes(utilization),
     200            0 :             NodeSchedulingPolicy::Pause => MaySchedule::No,
     201            0 :             NodeSchedulingPolicy::PauseForRestart => MaySchedule::No,
     202              :         }
     203          285 :     }
     204              : 
     205              :     #[allow(clippy::too_many_arguments)]
     206          278 :     pub(crate) fn new(
     207          278 :         id: NodeId,
     208          278 :         listen_http_addr: String,
     209          278 :         listen_http_port: u16,
     210          278 :         listen_https_port: Option<u16>,
     211          278 :         listen_pg_addr: String,
     212          278 :         listen_pg_port: u16,
     213          278 :         availability_zone_id: AvailabilityZone,
     214          278 :         use_https: bool,
     215          278 :     ) -> anyhow::Result<Self> {
     216          278 :         if use_https && listen_https_port.is_none() {
     217            0 :             anyhow::bail!(
     218            0 :                 "cannot create node {id}: \
     219            0 :                 https is enabled, but https port is not specified"
     220            0 :             );
     221          278 :         }
     222          278 : 
     223          278 :         Ok(Self {
     224          278 :             id,
     225          278 :             listen_http_addr,
     226          278 :             listen_http_port,
     227          278 :             listen_https_port,
     228          278 :             listen_pg_addr,
     229          278 :             listen_pg_port,
     230          278 :             scheduling: NodeSchedulingPolicy::Active,
     231          278 :             availability: NodeAvailability::Offline,
     232          278 :             availability_zone_id,
     233          278 :             use_https,
     234          278 :             cancel: CancellationToken::new(),
     235          278 :         })
     236          278 :     }
     237              : 
     238            0 :     pub(crate) fn to_persistent(&self) -> NodePersistence {
     239            0 :         NodePersistence {
     240            0 :             node_id: self.id.0 as i64,
     241            0 :             scheduling_policy: self.scheduling.into(),
     242            0 :             listen_http_addr: self.listen_http_addr.clone(),
     243            0 :             listen_http_port: self.listen_http_port as i32,
     244            0 :             listen_https_port: self.listen_https_port.map(|x| x as i32),
     245            0 :             listen_pg_addr: self.listen_pg_addr.clone(),
     246            0 :             listen_pg_port: self.listen_pg_port as i32,
     247            0 :             availability_zone_id: self.availability_zone_id.0.clone(),
     248            0 :         }
     249            0 :     }
     250              : 
     251            0 :     pub(crate) fn from_persistent(np: NodePersistence, use_https: bool) -> anyhow::Result<Self> {
     252            0 :         if use_https && np.listen_https_port.is_none() {
     253            0 :             anyhow::bail!(
     254            0 :                 "cannot load node {} from persistent: \
     255            0 :                 https is enabled, but https port is not specified",
     256            0 :                 np.node_id,
     257            0 :             );
     258            0 :         }
     259            0 : 
     260            0 :         Ok(Self {
     261            0 :             id: NodeId(np.node_id as u64),
     262            0 :             // At startup we consider a node offline until proven otherwise.
     263            0 :             availability: NodeAvailability::Offline,
     264            0 :             scheduling: NodeSchedulingPolicy::from_str(&np.scheduling_policy)
     265            0 :                 .expect("Bad scheduling policy in DB"),
     266            0 :             listen_http_addr: np.listen_http_addr,
     267            0 :             listen_http_port: np.listen_http_port as u16,
     268            0 :             listen_https_port: np.listen_https_port.map(|x| x as u16),
     269            0 :             listen_pg_addr: np.listen_pg_addr,
     270            0 :             listen_pg_port: np.listen_pg_port as u16,
     271            0 :             availability_zone_id: AvailabilityZone(np.availability_zone_id),
     272            0 :             use_https,
     273            0 :             cancel: CancellationToken::new(),
     274            0 :         })
     275            0 :     }
     276              : 
     277              :     /// Wrapper for issuing requests to pageserver management API: takes care of generic
     278              :     /// retry/backoff for retryable HTTP status codes.
     279              :     ///
     280              :     /// This will return None to indicate cancellation.  Cancellation may happen from
     281              :     /// the cancellation token passed in, or from Self's cancellation token (i.e. node
     282              :     /// going offline).
     283              :     #[allow(clippy::too_many_arguments)]
     284            0 :     pub(crate) async fn with_client_retries<T, O, F>(
     285            0 :         &self,
     286            0 :         mut op: O,
     287            0 :         http_client: &reqwest::Client,
     288            0 :         jwt: &Option<String>,
     289            0 :         warn_threshold: u32,
     290            0 :         max_retries: u32,
     291            0 :         timeout: Duration,
     292            0 :         cancel: &CancellationToken,
     293            0 :     ) -> Option<mgmt_api::Result<T>>
     294            0 :     where
     295            0 :         O: FnMut(PageserverClient) -> F,
     296            0 :         F: std::future::Future<Output = mgmt_api::Result<T>>,
     297            0 :     {
     298            0 :         fn is_fatal(e: &mgmt_api::Error) -> bool {
     299              :             use mgmt_api::Error::*;
     300            0 :             match e {
     301            0 :                 SendRequest(_) | ReceiveBody(_) | ReceiveErrorBody(_) => false,
     302              :                 ApiError(StatusCode::SERVICE_UNAVAILABLE, _)
     303              :                 | ApiError(StatusCode::GATEWAY_TIMEOUT, _)
     304            0 :                 | ApiError(StatusCode::REQUEST_TIMEOUT, _) => false,
     305            0 :                 ApiError(_, _) => true,
     306            0 :                 Cancelled => true,
     307            0 :                 Timeout(_) => false,
     308              :             }
     309            0 :         }
     310              : 
     311            0 :         backoff::retry(
     312            0 :             || {
     313            0 :                 let client = PageserverClient::new(
     314            0 :                     self.get_id(),
     315            0 :                     http_client.clone(),
     316            0 :                     self.base_url(),
     317            0 :                     jwt.as_deref(),
     318            0 :                 );
     319            0 : 
     320            0 :                 let node_cancel_fut = self.cancel.cancelled();
     321            0 : 
     322            0 :                 let op_fut = tokio::time::timeout(timeout, op(client));
     323              : 
     324            0 :                 async {
     325            0 :                     tokio::select! {
     326            0 :                         r = op_fut => match r {
     327            0 :                             Ok(r) => r,
     328            0 :                             Err(e) => Err(mgmt_api::Error::Timeout(format!("{e}"))),
     329              :                         },
     330            0 :                         _ = node_cancel_fut => {
     331            0 :                         Err(mgmt_api::Error::Cancelled)
     332              :                     }}
     333            0 :                 }
     334            0 :             },
     335            0 :             is_fatal,
     336            0 :             warn_threshold,
     337            0 :             max_retries,
     338            0 :             &format!(
     339            0 :                 "Call to node {} ({}) management API",
     340            0 :                 self.id,
     341            0 :                 self.base_url(),
     342            0 :             ),
     343            0 :             cancel,
     344            0 :         )
     345            0 :         .await
     346            0 :     }
     347              : 
     348              :     /// Generate the simplified API-friendly description of a node's state
     349            0 :     pub(crate) fn describe(&self) -> NodeDescribeResponse {
     350            0 :         NodeDescribeResponse {
     351            0 :             id: self.id,
     352            0 :             availability: self.availability.clone().into(),
     353            0 :             scheduling: self.scheduling,
     354            0 :             availability_zone_id: self.availability_zone_id.0.clone(),
     355            0 :             listen_http_addr: self.listen_http_addr.clone(),
     356            0 :             listen_http_port: self.listen_http_port,
     357            0 :             listen_https_port: self.listen_https_port,
     358            0 :             listen_pg_addr: self.listen_pg_addr.clone(),
     359            0 :             listen_pg_port: self.listen_pg_port,
     360            0 :         }
     361            0 :     }
     362              : }
     363              : 
     364              : impl std::fmt::Display for Node {
     365            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     366            0 :         write!(f, "{} ({})", self.id, self.listen_http_addr)
     367            0 :     }
     368              : }
     369              : 
     370              : impl std::fmt::Debug for Node {
     371            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     372            0 :         write!(f, "{} ({})", self.id, self.listen_http_addr)
     373            0 :     }
     374              : }
        

Generated by: LCOV version 2.1-beta