LCOV - code coverage report
Current view: top level - pageserver/src - control_plane_client.rs (source / functions) Coverage Total Hit
Test: fabb29a6339542ee130cd1d32b534fafdc0be240.info Lines: 0.0 % 137 0
Test Date: 2024-06-25 13:20:00 Functions: 0.0 % 23 0

            Line data    Source code
       1              : use std::collections::HashMap;
       2              : 
       3              : use futures::Future;
       4              : use pageserver_api::{
       5              :     controller_api::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 control plane API: this is a small subset
      21              : /// of the overall control plane API, for dealing with generations (see docs/rfcs/025-generation-numbers.md)
      22              : pub struct ControlPlaneClient {
      23              :     http_client: reqwest::Client,
      24              :     base_url: Url,
      25              :     node_id: NodeId,
      26              :     cancel: CancellationToken,
      27              : }
      28              : 
      29              : /// Represent operations which internally retry on all errors other than
      30              : /// cancellation token firing: the only way they can fail is ShuttingDown.
      31              : pub enum RetryForeverError {
      32              :     ShuttingDown,
      33              : }
      34              : 
      35              : pub trait ControlPlaneGenerationsApi {
      36              :     fn re_attach(
      37              :         &self,
      38              :         conf: &PageServerConf,
      39              :     ) -> impl Future<
      40              :         Output = Result<HashMap<TenantShardId, ReAttachResponseTenant>, RetryForeverError>,
      41              :     > + Send;
      42              :     fn validate(
      43              :         &self,
      44              :         tenants: Vec<(TenantShardId, Generation)>,
      45              :     ) -> impl Future<Output = Result<HashMap<TenantShardId, bool>, RetryForeverError>> + Send;
      46              : }
      47              : 
      48              : impl ControlPlaneClient {
      49              :     /// A None return value indicates that the input `conf` object does not have control
      50              :     /// plane API enabled.
      51            0 :     pub fn new(conf: &'static PageServerConf, cancel: &CancellationToken) -> Option<Self> {
      52            0 :         let mut url = match conf.control_plane_api.as_ref() {
      53            0 :             Some(u) => u.clone(),
      54            0 :             None => return None,
      55              :         };
      56              : 
      57            0 :         if let Ok(mut segs) = url.path_segments_mut() {
      58            0 :             // This ensures that `url` ends with a slash if it doesn't already.
      59            0 :             // That way, we can subsequently use join() to safely attach extra path elements.
      60            0 :             segs.pop_if_empty().push("");
      61            0 :         }
      62              : 
      63            0 :         let mut client = reqwest::ClientBuilder::new();
      64              : 
      65            0 :         if let Some(jwt) = &conf.control_plane_api_token {
      66            0 :             let mut headers = reqwest::header::HeaderMap::new();
      67            0 :             headers.insert(
      68            0 :                 "Authorization",
      69            0 :                 format!("Bearer {}", jwt.get_contents()).parse().unwrap(),
      70            0 :             );
      71            0 :             client = client.default_headers(headers);
      72            0 :         }
      73              : 
      74            0 :         Some(Self {
      75            0 :             http_client: client.build().expect("Failed to construct HTTP client"),
      76            0 :             base_url: url,
      77            0 :             node_id: conf.id,
      78            0 :             cancel: cancel.clone(),
      79            0 :         })
      80            0 :     }
      81              : 
      82            0 :     async fn retry_http_forever<R, T>(
      83            0 :         &self,
      84            0 :         url: &url::Url,
      85            0 :         request: R,
      86            0 :     ) -> Result<T, RetryForeverError>
      87            0 :     where
      88            0 :         R: Serialize,
      89            0 :         T: DeserializeOwned,
      90            0 :     {
      91            0 :         let res = backoff::retry(
      92            0 :             || async {
      93            0 :                 let response = self
      94            0 :                     .http_client
      95            0 :                     .post(url.clone())
      96            0 :                     .json(&request)
      97            0 :                     .send()
      98            0 :                     .await?;
      99            0 : 
     100            0 :                 response.error_for_status_ref()?;
     101            0 :                 response.json::<T>().await
     102            0 :             },
     103            0 :             |_| false,
     104            0 :             3,
     105            0 :             u32::MAX,
     106            0 :             "calling control plane generation validation API",
     107            0 :             &self.cancel,
     108            0 :         )
     109            0 :         .await
     110            0 :         .ok_or(RetryForeverError::ShuttingDown)?
     111            0 :         .expect("We retry forever, this should never be reached");
     112            0 : 
     113            0 :         Ok(res)
     114            0 :     }
     115              : }
     116              : 
     117              : impl ControlPlaneGenerationsApi for ControlPlaneClient {
     118              :     /// Block until we get a successful response, or error out if we are shut down
     119            0 :     async fn re_attach(
     120            0 :         &self,
     121            0 :         conf: &PageServerConf,
     122            0 :     ) -> Result<HashMap<TenantShardId, ReAttachResponseTenant>, RetryForeverError> {
     123            0 :         let re_attach_path = self
     124            0 :             .base_url
     125            0 :             .join("re-attach")
     126            0 :             .expect("Failed to build re-attach path");
     127            0 : 
     128            0 :         // Include registration content in the re-attach request if a metadata file is readable
     129            0 :         let metadata_path = conf.metadata_path();
     130            0 :         let register = match tokio::fs::read_to_string(&metadata_path).await {
     131            0 :             Ok(metadata_str) => match serde_json::from_str::<NodeMetadata>(&metadata_str) {
     132            0 :                 Ok(m) => {
     133            0 :                     // Since we run one time at startup, be generous in our logging and
     134            0 :                     // dump all metadata.
     135            0 :                     tracing::info!(
     136            0 :                         "Loaded node metadata: postgres {}:{}, http {}:{}, other fields: {:?}",
     137              :                         m.postgres_host,
     138              :                         m.postgres_port,
     139              :                         m.http_host,
     140              :                         m.http_port,
     141              :                         m.other
     142              :                     );
     143              : 
     144            0 :                     Some(NodeRegisterRequest {
     145            0 :                         node_id: conf.id,
     146            0 :                         listen_pg_addr: m.postgres_host,
     147            0 :                         listen_pg_port: m.postgres_port,
     148            0 :                         listen_http_addr: m.http_host,
     149            0 :                         listen_http_port: m.http_port,
     150            0 :                     })
     151              :                 }
     152            0 :                 Err(e) => {
     153            0 :                     tracing::error!("Unreadable metadata in {metadata_path}: {e}");
     154            0 :                     None
     155              :                 }
     156              :             },
     157            0 :             Err(e) => {
     158            0 :                 if e.kind() == std::io::ErrorKind::NotFound {
     159              :                     // This is legal: we may have been deployed with some external script
     160              :                     // doing registration for us.
     161            0 :                     tracing::info!("Metadata file not found at {metadata_path}");
     162              :                 } else {
     163            0 :                     on_fatal_io_error(&e, &format!("Loading metadata at {metadata_path}"))
     164              :                 }
     165            0 :                 None
     166              :             }
     167              :         };
     168              : 
     169            0 :         let request = ReAttachRequest {
     170            0 :             node_id: self.node_id,
     171            0 :             register,
     172            0 :         };
     173              : 
     174              :         fail::fail_point!("control-plane-client-re-attach");
     175              : 
     176            0 :         let response: ReAttachResponse = self.retry_http_forever(&re_attach_path, request).await?;
     177            0 :         tracing::info!(
     178            0 :             "Received re-attach response with {} tenants",
     179            0 :             response.tenants.len()
     180              :         );
     181              : 
     182            0 :         Ok(response
     183            0 :             .tenants
     184            0 :             .into_iter()
     185            0 :             .map(|rart| (rart.id, rart))
     186            0 :             .collect::<HashMap<_, _>>())
     187            0 :     }
     188              : 
     189              :     /// Block until we get a successful response, or error out if we are shut down
     190            0 :     async fn validate(
     191            0 :         &self,
     192            0 :         tenants: Vec<(TenantShardId, Generation)>,
     193            0 :     ) -> Result<HashMap<TenantShardId, bool>, RetryForeverError> {
     194            0 :         let re_attach_path = self
     195            0 :             .base_url
     196            0 :             .join("validate")
     197            0 :             .expect("Failed to build validate path");
     198            0 : 
     199            0 :         let request = ValidateRequest {
     200            0 :             tenants: tenants
     201            0 :                 .into_iter()
     202            0 :                 .map(|(id, gen)| ValidateRequestTenant {
     203            0 :                     id,
     204            0 :                     gen: gen
     205            0 :                         .into()
     206            0 :                         .expect("Generation should always be valid for a Tenant doing deletions"),
     207            0 :                 })
     208            0 :                 .collect(),
     209            0 :         };
     210            0 : 
     211            0 :         failpoint_support::sleep_millis_async!("control-plane-client-validate-sleep", &self.cancel);
     212            0 :         if self.cancel.is_cancelled() {
     213            0 :             return Err(RetryForeverError::ShuttingDown);
     214            0 :         }
     215              : 
     216            0 :         let response: ValidateResponse = self.retry_http_forever(&re_attach_path, request).await?;
     217              : 
     218            0 :         Ok(response
     219            0 :             .tenants
     220            0 :             .into_iter()
     221            0 :             .map(|rt| (rt.id, rt.valid))
     222            0 :             .collect())
     223            0 :     }
     224              : }
        

Generated by: LCOV version 2.1-beta