LCOV - code coverage report
Current view: top level - pageserver/src - controller_upcall_client.rs (source / functions) Coverage Total Hit
Test: 49aa928ec5b4b510172d8b5c6d154da28e70a46c.info Lines: 0.0 % 158 0
Test Date: 2024-11-13 18:23:39 Functions: 0.0 % 24 0

            Line data    Source code
       1              : use std::collections::HashMap;
       2              : 
       3              : use futures::Future;
       4              : use pageserver_api::{
       5              :     controller_api::{AvailabilityZone, NodeRegisterRequest},
       6              :     shard::TenantShardId,
       7              :     upcall_api::{
       8              :         ReAttachRequest, ReAttachResponse, ReAttachResponseTenant, ValidateRequest,
       9              :         ValidateRequestTenant, ValidateResponse,
      10              :     },
      11              : };
      12              : use serde::{de::DeserializeOwned, Serialize};
      13              : use tokio_util::sync::CancellationToken;
      14              : use url::Url;
      15              : use utils::{backoff, failpoint_support, generation::Generation, id::NodeId};
      16              : 
      17              : use crate::{config::PageServerConf, virtual_file::on_fatal_io_error};
      18              : use pageserver_api::config::NodeMetadata;
      19              : 
      20              : /// The Pageserver's client for using the storage controller upcall API: this is a small API
      21              : /// for dealing with generations (see docs/rfcs/025-generation-numbers.md).
      22              : ///
      23              : /// The server presenting this API may either be the storage controller or some other
      24              : /// service (such as the Neon control plane) providing a store of generation numbers.
      25              : pub struct ControllerUpcallClient {
      26              :     http_client: reqwest::Client,
      27              :     base_url: Url,
      28              :     node_id: NodeId,
      29              :     cancel: CancellationToken,
      30              : }
      31              : 
      32              : /// Represent operations which internally retry on all errors other than
      33              : /// cancellation token firing: the only way they can fail is ShuttingDown.
      34              : pub enum RetryForeverError {
      35              :     ShuttingDown,
      36              : }
      37              : 
      38              : pub trait ControlPlaneGenerationsApi {
      39              :     fn re_attach(
      40              :         &self,
      41              :         conf: &PageServerConf,
      42              :     ) -> impl Future<
      43              :         Output = Result<HashMap<TenantShardId, ReAttachResponseTenant>, RetryForeverError>,
      44              :     > + Send;
      45              :     fn validate(
      46              :         &self,
      47              :         tenants: Vec<(TenantShardId, Generation)>,
      48              :     ) -> impl Future<Output = Result<HashMap<TenantShardId, bool>, RetryForeverError>> + Send;
      49              : }
      50              : 
      51              : impl ControllerUpcallClient {
      52              :     /// A None return value indicates that the input `conf` object does not have control
      53              :     /// plane API enabled.
      54            0 :     pub fn new(conf: &'static PageServerConf, cancel: &CancellationToken) -> Option<Self> {
      55            0 :         let mut url = match conf.control_plane_api.as_ref() {
      56            0 :             Some(u) => u.clone(),
      57            0 :             None => return None,
      58              :         };
      59              : 
      60            0 :         if let Ok(mut segs) = url.path_segments_mut() {
      61            0 :             // This ensures that `url` ends with a slash if it doesn't already.
      62            0 :             // That way, we can subsequently use join() to safely attach extra path elements.
      63            0 :             segs.pop_if_empty().push("");
      64            0 :         }
      65              : 
      66            0 :         let mut client = reqwest::ClientBuilder::new();
      67              : 
      68            0 :         if let Some(jwt) = &conf.control_plane_api_token {
      69            0 :             let mut headers = reqwest::header::HeaderMap::new();
      70            0 :             headers.insert(
      71            0 :                 "Authorization",
      72            0 :                 format!("Bearer {}", jwt.get_contents()).parse().unwrap(),
      73            0 :             );
      74            0 :             client = client.default_headers(headers);
      75            0 :         }
      76              : 
      77            0 :         Some(Self {
      78            0 :             http_client: client.build().expect("Failed to construct HTTP client"),
      79            0 :             base_url: url,
      80            0 :             node_id: conf.id,
      81            0 :             cancel: cancel.clone(),
      82            0 :         })
      83            0 :     }
      84              : 
      85            0 :     async fn retry_http_forever<R, T>(
      86            0 :         &self,
      87            0 :         url: &url::Url,
      88            0 :         request: R,
      89            0 :     ) -> Result<T, RetryForeverError>
      90            0 :     where
      91            0 :         R: Serialize,
      92            0 :         T: DeserializeOwned,
      93            0 :     {
      94            0 :         let res = backoff::retry(
      95            0 :             || async {
      96            0 :                 let response = self
      97            0 :                     .http_client
      98            0 :                     .post(url.clone())
      99            0 :                     .json(&request)
     100            0 :                     .send()
     101            0 :                     .await?;
     102              : 
     103            0 :                 response.error_for_status_ref()?;
     104            0 :                 response.json::<T>().await
     105            0 :             },
     106            0 :             |_| false,
     107            0 :             3,
     108            0 :             u32::MAX,
     109            0 :             "calling control plane generation validation API",
     110            0 :             &self.cancel,
     111            0 :         )
     112            0 :         .await
     113            0 :         .ok_or(RetryForeverError::ShuttingDown)?
     114            0 :         .expect("We retry forever, this should never be reached");
     115            0 : 
     116            0 :         Ok(res)
     117            0 :     }
     118              : }
     119              : 
     120              : impl ControlPlaneGenerationsApi for ControllerUpcallClient {
     121              :     /// Block until we get a successful response, or error out if we are shut down
     122            0 :     async fn re_attach(
     123            0 :         &self,
     124            0 :         conf: &PageServerConf,
     125            0 :     ) -> Result<HashMap<TenantShardId, ReAttachResponseTenant>, RetryForeverError> {
     126            0 :         let re_attach_path = self
     127            0 :             .base_url
     128            0 :             .join("re-attach")
     129            0 :             .expect("Failed to build re-attach path");
     130            0 : 
     131            0 :         // Include registration content in the re-attach request if a metadata file is readable
     132            0 :         let metadata_path = conf.metadata_path();
     133            0 :         let register = match tokio::fs::read_to_string(&metadata_path).await {
     134            0 :             Ok(metadata_str) => match serde_json::from_str::<NodeMetadata>(&metadata_str) {
     135            0 :                 Ok(m) => {
     136            0 :                     // Since we run one time at startup, be generous in our logging and
     137            0 :                     // dump all metadata.
     138            0 :                     tracing::info!(
     139            0 :                         "Loaded node metadata: postgres {}:{}, http {}:{}, other fields: {:?}",
     140              :                         m.postgres_host,
     141              :                         m.postgres_port,
     142              :                         m.http_host,
     143              :                         m.http_port,
     144              :                         m.other
     145              :                     );
     146              : 
     147            0 :                     let az_id = {
     148            0 :                         let az_id_from_metadata = m
     149            0 :                             .other
     150            0 :                             .get("availability_zone_id")
     151            0 :                             .and_then(|jv| jv.as_str().map(|str| str.to_owned()));
     152            0 : 
     153            0 :                         match az_id_from_metadata {
     154            0 :                             Some(az_id) => Some(AvailabilityZone(az_id)),
     155              :                             None => {
     156            0 :                                 tracing::warn!("metadata.json does not contain an 'availability_zone_id' field");
     157            0 :                                 conf.availability_zone.clone().map(AvailabilityZone)
     158              :                             }
     159              :                         }
     160              :                     };
     161              : 
     162            0 :                     if az_id.is_none() {
     163            0 :                         panic!("Availablity zone id could not be inferred from metadata.json or pageserver config");
     164            0 :                     }
     165            0 : 
     166            0 :                     Some(NodeRegisterRequest {
     167            0 :                         node_id: conf.id,
     168            0 :                         listen_pg_addr: m.postgres_host,
     169            0 :                         listen_pg_port: m.postgres_port,
     170            0 :                         listen_http_addr: m.http_host,
     171            0 :                         listen_http_port: m.http_port,
     172            0 :                         availability_zone_id: az_id.expect("Checked above"),
     173            0 :                     })
     174              :                 }
     175            0 :                 Err(e) => {
     176            0 :                     tracing::error!("Unreadable metadata in {metadata_path}: {e}");
     177            0 :                     None
     178              :                 }
     179              :             },
     180            0 :             Err(e) => {
     181            0 :                 if e.kind() == std::io::ErrorKind::NotFound {
     182              :                     // This is legal: we may have been deployed with some external script
     183              :                     // doing registration for us.
     184            0 :                     tracing::info!("Metadata file not found at {metadata_path}");
     185              :                 } else {
     186            0 :                     on_fatal_io_error(&e, &format!("Loading metadata at {metadata_path}"))
     187              :                 }
     188            0 :                 None
     189              :             }
     190              :         };
     191              : 
     192            0 :         let request = ReAttachRequest {
     193            0 :             node_id: self.node_id,
     194            0 :             register,
     195            0 :         };
     196              : 
     197            0 :         let response: ReAttachResponse = self.retry_http_forever(&re_attach_path, request).await?;
     198            0 :         tracing::info!(
     199            0 :             "Received re-attach response with {} tenants",
     200            0 :             response.tenants.len()
     201              :         );
     202              : 
     203            0 :         failpoint_support::sleep_millis_async!("control-plane-client-re-attach");
     204              : 
     205            0 :         Ok(response
     206            0 :             .tenants
     207            0 :             .into_iter()
     208            0 :             .map(|rart| (rart.id, rart))
     209            0 :             .collect::<HashMap<_, _>>())
     210            0 :     }
     211              : 
     212              :     /// Block until we get a successful response, or error out if we are shut down
     213            0 :     async fn validate(
     214            0 :         &self,
     215            0 :         tenants: Vec<(TenantShardId, Generation)>,
     216            0 :     ) -> Result<HashMap<TenantShardId, bool>, RetryForeverError> {
     217            0 :         let re_attach_path = self
     218            0 :             .base_url
     219            0 :             .join("validate")
     220            0 :             .expect("Failed to build validate path");
     221            0 : 
     222            0 :         // When sending validate requests, break them up into chunks so that we
     223            0 :         // avoid possible edge cases of generating any HTTP requests that
     224            0 :         // require database I/O across many thousands of tenants.
     225            0 :         let mut result: HashMap<TenantShardId, bool> = HashMap::with_capacity(tenants.len());
     226            0 :         for tenant_chunk in (tenants).chunks(128) {
     227            0 :             let request = ValidateRequest {
     228            0 :                 tenants: tenant_chunk
     229            0 :                     .iter()
     230            0 :                     .map(|(id, generation)| ValidateRequestTenant {
     231            0 :                         id: *id,
     232            0 :                         gen: (*generation).into().expect(
     233            0 :                             "Generation should always be valid for a Tenant doing deletions",
     234            0 :                         ),
     235            0 :                     })
     236            0 :                     .collect(),
     237            0 :             };
     238            0 : 
     239            0 :             failpoint_support::sleep_millis_async!(
     240              :                 "control-plane-client-validate-sleep",
     241            0 :                 &self.cancel
     242              :             );
     243            0 :             if self.cancel.is_cancelled() {
     244            0 :                 return Err(RetryForeverError::ShuttingDown);
     245            0 :             }
     246              : 
     247            0 :             let response: ValidateResponse =
     248            0 :                 self.retry_http_forever(&re_attach_path, request).await?;
     249            0 :             for rt in response.tenants {
     250            0 :                 result.insert(rt.id, rt.valid);
     251            0 :             }
     252              :         }
     253              : 
     254            0 :         Ok(result.into_iter().collect())
     255            0 :     }
     256              : }
        

Generated by: LCOV version 2.1-beta