LCOV - code coverage report
Current view: top level - pageserver/client/src - mgmt_api.rs (source / functions) Coverage Total Hit
Test: aca8877be6ceba750c1be359ed71bc1799d52b30.info Lines: 61.2 % 281 172
Test Date: 2024-02-14 18:05:35 Functions: 61.4 % 70 43

            Line data    Source code
       1              : use pageserver_api::{models::*, shard::TenantShardId};
       2              : use reqwest::{IntoUrl, Method, StatusCode};
       3              : use utils::{
       4              :     http::error::HttpErrorBody,
       5              :     id::{TenantId, TimelineId},
       6              : };
       7              : 
       8              : pub mod util;
       9              : 
      10            0 : #[derive(Debug)]
      11              : pub struct Client {
      12              :     mgmt_api_endpoint: String,
      13              :     authorization_header: Option<String>,
      14              :     client: reqwest::Client,
      15              : }
      16              : 
      17           23 : #[derive(thiserror::Error, Debug)]
      18              : pub enum Error {
      19              :     #[error("receive body: {0}")]
      20              :     ReceiveBody(reqwest::Error),
      21              : 
      22              :     #[error("receive error body: {0}")]
      23              :     ReceiveErrorBody(String),
      24              : 
      25              :     #[error("pageserver API: {1}")]
      26              :     ApiError(StatusCode, String),
      27              : }
      28              : 
      29              : pub type Result<T> = std::result::Result<T, Error>;
      30              : 
      31              : pub trait ResponseErrorMessageExt: Sized {
      32              :     fn error_from_body(self) -> impl std::future::Future<Output = Result<Self>> + Send;
      33              : }
      34              : 
      35              : impl ResponseErrorMessageExt for reqwest::Response {
      36         4888 :     async fn error_from_body(self) -> Result<Self> {
      37         4888 :         let status = self.status();
      38         4888 :         if !(status.is_client_error() || status.is_server_error()) {
      39         4860 :             return Ok(self);
      40           28 :         }
      41           28 : 
      42           28 :         let url = self.url().to_owned();
      43           28 :         Err(match self.json::<HttpErrorBody>().await {
      44           28 :             Ok(HttpErrorBody { msg }) => Error::ApiError(status, msg),
      45              :             Err(_) => {
      46            0 :                 Error::ReceiveErrorBody(format!("Http error ({}) at {}.", status.as_u16(), url))
      47              :             }
      48              :         })
      49         4888 :     }
      50              : }
      51              : 
      52              : pub enum ForceAwaitLogicalSize {
      53              :     Yes,
      54              :     No,
      55              : }
      56              : 
      57              : impl Client {
      58         4116 :     pub fn new(mgmt_api_endpoint: String, jwt: Option<&str>) -> Self {
      59         4116 :         Self::from_client(reqwest::Client::new(), mgmt_api_endpoint, jwt)
      60         4116 :     }
      61              : 
      62         4126 :     pub fn from_client(
      63         4126 :         client: reqwest::Client,
      64         4126 :         mgmt_api_endpoint: String,
      65         4126 :         jwt: Option<&str>,
      66         4126 :     ) -> Self {
      67         4126 :         Self {
      68         4126 :             mgmt_api_endpoint,
      69         4126 :             authorization_header: jwt.map(|jwt| format!("Bearer {jwt}")),
      70         4126 :             client,
      71         4126 :         }
      72         4126 :     }
      73              : 
      74            6 :     pub async fn list_tenants(&self) -> Result<Vec<pageserver_api::models::TenantInfo>> {
      75            6 :         let uri = format!("{}/v1/tenant", self.mgmt_api_endpoint);
      76           24 :         let resp = self.get(&uri).await?;
      77            6 :         resp.json().await.map_err(Error::ReceiveBody)
      78            6 :     }
      79              : 
      80              :     /// Get an arbitrary path and returning a streaming Response.  This function is suitable
      81              :     /// for pass-through/proxy use cases where we don't care what the response content looks
      82              :     /// like.
      83              :     ///
      84              :     /// Use/add one of the properly typed methods below if you know aren't proxying, and
      85              :     /// know what kind of response you expect.
      86            5 :     pub async fn get_raw(&self, path: String) -> Result<reqwest::Response> {
      87            5 :         debug_assert!(path.starts_with('/'));
      88            5 :         let uri = format!("{}{}", self.mgmt_api_endpoint, path);
      89            5 : 
      90            5 :         let req = self.client.request(Method::GET, uri);
      91            5 :         let req = if let Some(value) = &self.authorization_header {
      92            0 :             req.header(reqwest::header::AUTHORIZATION, value)
      93              :         } else {
      94            5 :             req
      95              :         };
      96           20 :         req.send().await.map_err(Error::ReceiveBody)
      97            5 :     }
      98              : 
      99            0 :     pub async fn tenant_details(
     100            0 :         &self,
     101            0 :         tenant_shard_id: TenantShardId,
     102            0 :     ) -> Result<pageserver_api::models::TenantDetails> {
     103            0 :         let uri = format!("{}/v1/tenant/{tenant_shard_id}", self.mgmt_api_endpoint);
     104            0 :         self.get(uri)
     105            0 :             .await?
     106            0 :             .json()
     107            0 :             .await
     108            0 :             .map_err(Error::ReceiveBody)
     109            0 :     }
     110              : 
     111           19 :     pub async fn list_timelines(
     112           19 :         &self,
     113           19 :         tenant_shard_id: TenantShardId,
     114           19 :     ) -> Result<Vec<pageserver_api::models::TimelineInfo>> {
     115           19 :         let uri = format!(
     116           19 :             "{}/v1/tenant/{tenant_shard_id}/timeline",
     117           19 :             self.mgmt_api_endpoint
     118           19 :         );
     119           19 :         self.get(&uri)
     120           76 :             .await?
     121           19 :             .json()
     122            0 :             .await
     123           19 :             .map_err(Error::ReceiveBody)
     124           19 :     }
     125              : 
     126            0 :     pub async fn timeline_info(
     127            0 :         &self,
     128            0 :         tenant_id: TenantId,
     129            0 :         timeline_id: TimelineId,
     130            0 :         force_await_logical_size: ForceAwaitLogicalSize,
     131            0 :     ) -> Result<pageserver_api::models::TimelineInfo> {
     132            0 :         let uri = format!(
     133            0 :             "{}/v1/tenant/{tenant_id}/timeline/{timeline_id}",
     134            0 :             self.mgmt_api_endpoint
     135            0 :         );
     136              : 
     137            0 :         let uri = match force_await_logical_size {
     138            0 :             ForceAwaitLogicalSize::Yes => format!("{}?force-await-logical-size={}", uri, true),
     139            0 :             ForceAwaitLogicalSize::No => uri,
     140              :         };
     141              : 
     142            0 :         self.get(&uri)
     143            0 :             .await?
     144            0 :             .json()
     145            0 :             .await
     146            0 :             .map_err(Error::ReceiveBody)
     147            0 :     }
     148              : 
     149            0 :     pub async fn keyspace(
     150            0 :         &self,
     151            0 :         tenant_id: TenantId,
     152            0 :         timeline_id: TimelineId,
     153            0 :     ) -> Result<pageserver_api::models::partitioning::Partitioning> {
     154            0 :         let uri = format!(
     155            0 :             "{}/v1/tenant/{tenant_id}/timeline/{timeline_id}/keyspace",
     156            0 :             self.mgmt_api_endpoint
     157            0 :         );
     158            0 :         self.get(&uri)
     159            0 :             .await?
     160            0 :             .json()
     161            0 :             .await
     162            0 :             .map_err(Error::ReceiveBody)
     163            0 :     }
     164              : 
     165         1320 :     async fn get<U: IntoUrl>(&self, uri: U) -> Result<reqwest::Response> {
     166         3965 :         self.request(Method::GET, uri, ()).await
     167         1320 :     }
     168              : 
     169         2735 :     async fn request<B: serde::Serialize, U: reqwest::IntoUrl>(
     170         2735 :         &self,
     171         2735 :         method: Method,
     172         2735 :         uri: U,
     173         2735 :         body: B,
     174         2735 :     ) -> Result<reqwest::Response> {
     175         2735 :         let req = self.client.request(method, uri);
     176         2735 :         let req = if let Some(value) = &self.authorization_header {
     177           60 :             req.header(reqwest::header::AUTHORIZATION, value)
     178              :         } else {
     179         2675 :             req
     180              :         };
     181         9536 :         let res = req.json(&body).send().await.map_err(Error::ReceiveBody)?;
     182         2066 :         let response = res.error_from_body().await?;
     183         2043 :         Ok(response)
     184         2735 :     }
     185              : 
     186         1283 :     pub async fn status(&self) -> Result<()> {
     187         1283 :         let uri = format!("{}/v1/status", self.mgmt_api_endpoint);
     188         3817 :         self.get(&uri).await?;
     189          626 :         Ok(())
     190         1283 :     }
     191              : 
     192            0 :     pub async fn tenant_create(&self, req: &TenantCreateRequest) -> Result<TenantId> {
     193            0 :         let uri = format!("{}/v1/tenant", self.mgmt_api_endpoint);
     194            0 :         self.request(Method::POST, &uri, req)
     195            0 :             .await?
     196            0 :             .json()
     197            0 :             .await
     198            0 :             .map_err(Error::ReceiveBody)
     199            0 :     }
     200              : 
     201              :     /// The tenant deletion API can return 202 if deletion is incomplete, or
     202              :     /// 404 if it is complete.  Callers are responsible for checking the status
     203              :     /// code and retrying.  Error codes other than 404 will return Err().
     204           24 :     pub async fn tenant_delete(&self, tenant_shard_id: TenantShardId) -> Result<StatusCode> {
     205           24 :         let uri = format!("{}/v1/tenant/{tenant_shard_id}", self.mgmt_api_endpoint);
     206           24 : 
     207           96 :         match self.request(Method::DELETE, &uri, ()).await {
     208           12 :             Err(Error::ApiError(status_code, msg)) => {
     209           12 :                 if status_code == StatusCode::NOT_FOUND {
     210           12 :                     Ok(StatusCode::NOT_FOUND)
     211              :                 } else {
     212            0 :                     Err(Error::ApiError(status_code, msg))
     213              :                 }
     214              :             }
     215            0 :             Err(e) => Err(e),
     216           12 :             Ok(response) => Ok(response.status()),
     217              :         }
     218           24 :     }
     219              : 
     220           14 :     pub async fn tenant_config(&self, req: &TenantConfigRequest) -> Result<()> {
     221           14 :         let uri = format!("{}/v1/tenant/config", self.mgmt_api_endpoint);
     222           56 :         self.request(Method::PUT, &uri, req).await?;
     223           14 :         Ok(())
     224           14 :     }
     225              : 
     226            0 :     pub async fn tenant_secondary_download(&self, tenant_id: TenantShardId) -> Result<()> {
     227            0 :         let uri = format!(
     228            0 :             "{}/v1/tenant/{}/secondary/download",
     229            0 :             self.mgmt_api_endpoint, tenant_id
     230            0 :         );
     231            0 :         self.request(Method::POST, &uri, ()).await?;
     232            0 :         Ok(())
     233            0 :     }
     234              : 
     235          522 :     pub async fn location_config(
     236          522 :         &self,
     237          522 :         tenant_shard_id: TenantShardId,
     238          522 :         config: LocationConfig,
     239          522 :         flush_ms: Option<std::time::Duration>,
     240          522 :     ) -> Result<()> {
     241          522 :         let req_body = TenantLocationConfigRequest {
     242          522 :             tenant_id: tenant_shard_id,
     243          522 :             config,
     244          522 :         };
     245          522 :         let path = format!(
     246          522 :             "{}/v1/tenant/{}/location_config",
     247          522 :             self.mgmt_api_endpoint, tenant_shard_id
     248          522 :         );
     249          522 :         let path = if let Some(flush_ms) = flush_ms {
     250            4 :             format!("{}?flush_ms={}", path, flush_ms.as_millis())
     251              :         } else {
     252          518 :             path
     253              :         };
     254         2060 :         self.request(Method::PUT, &path, &req_body).await?;
     255          521 :         Ok(())
     256          522 :     }
     257              : 
     258           18 :     pub async fn list_location_config(&self) -> Result<LocationConfigListResponse> {
     259           18 :         let path = format!("{}/v1/location_config", self.mgmt_api_endpoint);
     260           18 :         self.request(Method::GET, &path, ())
     261           48 :             .await?
     262            6 :             .json()
     263            0 :             .await
     264            6 :             .map_err(Error::ReceiveBody)
     265           18 :     }
     266              : 
     267          828 :     pub async fn timeline_create(
     268          828 :         &self,
     269          828 :         tenant_shard_id: TenantShardId,
     270          828 :         req: &TimelineCreateRequest,
     271          828 :     ) -> Result<TimelineInfo> {
     272          828 :         let uri = format!(
     273          828 :             "{}/v1/tenant/{}/timeline",
     274          828 :             self.mgmt_api_endpoint, tenant_shard_id
     275          828 :         );
     276          828 :         self.request(Method::POST, &uri, req)
     277         3275 :             .await?
     278          824 :             .json()
     279            0 :             .await
     280          824 :             .map_err(Error::ReceiveBody)
     281          828 :     }
     282              : 
     283              :     /// The timeline deletion API can return 201 if deletion is incomplete, or
     284              :     /// 403 if it is complete.  Callers are responsible for checking the status
     285              :     /// code and retrying.  Error codes other than 403 will return Err().
     286            4 :     pub async fn timeline_delete(
     287            4 :         &self,
     288            4 :         tenant_shard_id: TenantShardId,
     289            4 :         timeline_id: TimelineId,
     290            4 :     ) -> Result<StatusCode> {
     291            4 :         let uri = format!(
     292            4 :             "{}/v1/tenant/{tenant_shard_id}/timeline/{timeline_id}",
     293            4 :             self.mgmt_api_endpoint
     294            4 :         );
     295            4 : 
     296           16 :         match self.request(Method::DELETE, &uri, ()).await {
     297            2 :             Err(Error::ApiError(status_code, msg)) => {
     298            2 :                 if status_code == StatusCode::NOT_FOUND {
     299            2 :                     Ok(StatusCode::NOT_FOUND)
     300              :                 } else {
     301            0 :                     Err(Error::ApiError(status_code, msg))
     302              :                 }
     303              :             }
     304            0 :             Err(e) => Err(e),
     305            2 :             Ok(response) => Ok(response.status()),
     306              :         }
     307            4 :     }
     308              : 
     309            0 :     pub async fn tenant_reset(&self, tenant_shard_id: TenantShardId) -> Result<()> {
     310            0 :         let uri = format!(
     311            0 :             "{}/v1/tenant/{}/reset",
     312            0 :             self.mgmt_api_endpoint, tenant_shard_id
     313            0 :         );
     314            0 :         self.request(Method::POST, &uri, ())
     315            0 :             .await?
     316            0 :             .json()
     317            0 :             .await
     318            0 :             .map_err(Error::ReceiveBody)
     319            0 :     }
     320              : 
     321            5 :     pub async fn tenant_shard_split(
     322            5 :         &self,
     323            5 :         tenant_shard_id: TenantShardId,
     324            5 :         req: TenantShardSplitRequest,
     325            5 :     ) -> Result<TenantShardSplitResponse> {
     326            5 :         let uri = format!(
     327            5 :             "{}/v1/tenant/{}/shard_split",
     328            5 :             self.mgmt_api_endpoint, tenant_shard_id
     329            5 :         );
     330            5 :         self.request(Method::PUT, &uri, req)
     331           20 :             .await?
     332            5 :             .json()
     333            0 :             .await
     334            5 :             .map_err(Error::ReceiveBody)
     335            5 :     }
     336              : 
     337           12 :     pub async fn timeline_list(
     338           12 :         &self,
     339           12 :         tenant_shard_id: &TenantShardId,
     340           12 :     ) -> Result<Vec<TimelineInfo>> {
     341           12 :         let uri = format!(
     342           12 :             "{}/v1/tenant/{}/timeline",
     343           12 :             self.mgmt_api_endpoint, tenant_shard_id
     344           12 :         );
     345           12 :         self.get(&uri)
     346           48 :             .await?
     347            8 :             .json()
     348            0 :             .await
     349            8 :             .map_err(Error::ReceiveBody)
     350           12 :     }
     351              : 
     352            0 :     pub async fn tenant_synthetic_size(
     353            0 :         &self,
     354            0 :         tenant_shard_id: TenantShardId,
     355            0 :     ) -> Result<TenantHistorySize> {
     356            0 :         let uri = format!(
     357            0 :             "{}/v1/tenant/{}/synthetic_size",
     358            0 :             self.mgmt_api_endpoint, tenant_shard_id
     359            0 :         );
     360            0 :         self.get(&uri)
     361            0 :             .await?
     362            0 :             .json()
     363            0 :             .await
     364            0 :             .map_err(Error::ReceiveBody)
     365            0 :     }
     366              : 
     367            0 :     pub async fn put_io_engine(
     368            0 :         &self,
     369            0 :         engine: &pageserver_api::models::virtual_file::IoEngineKind,
     370            0 :     ) -> Result<()> {
     371            0 :         let uri = format!("{}/v1/io_engine", self.mgmt_api_endpoint);
     372            0 :         self.request(Method::PUT, uri, engine)
     373            0 :             .await?
     374            0 :             .json()
     375            0 :             .await
     376            0 :             .map_err(Error::ReceiveBody)
     377            0 :     }
     378              : }
        

Generated by: LCOV version 2.1-beta