Line data Source code
1 : use std::collections::HashMap;
2 : use std::error::Error as _;
3 : use std::time::Duration;
4 :
5 : use bytes::Bytes;
6 : use detach_ancestor::AncestorDetached;
7 : use http_utils::error::HttpErrorBody;
8 : use pageserver_api::models::*;
9 : use pageserver_api::shard::TenantShardId;
10 : use postgres_versioninfo::PgMajorVersion;
11 : pub use reqwest::Body as ReqwestBody;
12 : use reqwest::{IntoUrl, Method, StatusCode, Url};
13 : use utils::id::{TenantId, TimelineId};
14 : use utils::lsn::Lsn;
15 :
16 : use crate::BlockUnblock;
17 :
18 : pub mod util;
19 :
20 : #[derive(Debug, Clone)]
21 : pub struct Client {
22 : mgmt_api_endpoint: String,
23 : authorization_header: Option<String>,
24 : client: reqwest::Client,
25 : }
26 :
27 : #[derive(thiserror::Error, Debug)]
28 : pub enum Error {
29 0 : #[error("send request: {0}{}", .0.source().map(|e| format!(": {e}")).unwrap_or_default())]
30 : SendRequest(reqwest::Error),
31 :
32 0 : #[error("receive body: {0}{}", .0.source().map(|e| format!(": {e}")).unwrap_or_default())]
33 : ReceiveBody(reqwest::Error),
34 :
35 : #[error("receive error body: {0}")]
36 : ReceiveErrorBody(String),
37 :
38 : #[error("pageserver API: {1}")]
39 : ApiError(StatusCode, String),
40 :
41 : #[error("Cancelled")]
42 : Cancelled,
43 :
44 : #[error("request timed out: {0}")]
45 : Timeout(String),
46 : }
47 :
48 : pub type Result<T> = std::result::Result<T, Error>;
49 :
50 : pub trait ResponseErrorMessageExt: Sized {
51 : fn error_from_body(self) -> impl std::future::Future<Output = Result<Self>> + Send;
52 : }
53 :
54 : impl ResponseErrorMessageExt for reqwest::Response {
55 0 : async fn error_from_body(self) -> Result<Self> {
56 0 : let status = self.status();
57 0 : if !(status.is_client_error() || status.is_server_error()) {
58 0 : return Ok(self);
59 0 : }
60 :
61 0 : let url = self.url().to_owned();
62 0 : Err(match self.json::<HttpErrorBody>().await {
63 0 : Ok(HttpErrorBody { msg }) => Error::ApiError(status, msg),
64 : Err(_) => {
65 0 : Error::ReceiveErrorBody(format!("Http error ({}) at {}.", status.as_u16(), url))
66 : }
67 : })
68 0 : }
69 : }
70 :
71 : pub enum ForceAwaitLogicalSize {
72 : Yes,
73 : No,
74 : }
75 :
76 : impl Client {
77 0 : pub fn new(client: reqwest::Client, mgmt_api_endpoint: String, jwt: Option<&str>) -> Self {
78 : Self {
79 0 : mgmt_api_endpoint,
80 0 : authorization_header: jwt.map(|jwt| format!("Bearer {jwt}")),
81 0 : client,
82 : }
83 0 : }
84 :
85 0 : pub async fn list_tenants(&self) -> Result<Vec<pageserver_api::models::TenantInfo>> {
86 0 : let uri = format!("{}/v1/tenant", self.mgmt_api_endpoint);
87 0 : let resp = self.get(&uri).await?;
88 0 : resp.json().await.map_err(Error::ReceiveBody)
89 0 : }
90 :
91 : /// Send an HTTP request to an arbitrary path with a desired HTTP method and returning a streaming
92 : /// Response. This function is suitable for pass-through/proxy use cases where we don't care
93 : /// what the response content looks like.
94 : ///
95 : /// Use/add one of the properly typed methods below if you know aren't proxying, and
96 : /// know what kind of response you expect.
97 0 : pub async fn op_raw(&self, method: Method, path: String) -> Result<reqwest::Response> {
98 0 : debug_assert!(path.starts_with('/'));
99 0 : let uri = format!("{}{}", self.mgmt_api_endpoint, path);
100 :
101 0 : let mut req = self.client.request(method, uri);
102 0 : if let Some(value) = &self.authorization_header {
103 0 : req = req.header(reqwest::header::AUTHORIZATION, value);
104 0 : }
105 0 : req.send().await.map_err(Error::ReceiveBody)
106 0 : }
107 :
108 0 : pub async fn tenant_details(
109 0 : &self,
110 0 : tenant_shard_id: TenantShardId,
111 0 : ) -> Result<pageserver_api::models::TenantDetails> {
112 0 : let uri = format!("{}/v1/tenant/{tenant_shard_id}", self.mgmt_api_endpoint);
113 0 : self.get(uri)
114 0 : .await?
115 0 : .json()
116 0 : .await
117 0 : .map_err(Error::ReceiveBody)
118 0 : }
119 :
120 0 : pub async fn list_timelines(
121 0 : &self,
122 0 : tenant_shard_id: TenantShardId,
123 0 : ) -> Result<Vec<pageserver_api::models::TimelineInfo>> {
124 0 : let uri = format!(
125 0 : "{}/v1/tenant/{tenant_shard_id}/timeline",
126 : self.mgmt_api_endpoint
127 : );
128 0 : self.get(&uri)
129 0 : .await?
130 0 : .json()
131 0 : .await
132 0 : .map_err(Error::ReceiveBody)
133 0 : }
134 :
135 0 : pub async fn timeline_info(
136 0 : &self,
137 0 : tenant_shard_id: TenantShardId,
138 0 : timeline_id: TimelineId,
139 0 : force_await_logical_size: ForceAwaitLogicalSize,
140 0 : ) -> Result<pageserver_api::models::TimelineInfo> {
141 0 : let uri = format!(
142 0 : "{}/v1/tenant/{tenant_shard_id}/timeline/{timeline_id}",
143 : self.mgmt_api_endpoint
144 : );
145 :
146 0 : let uri = match force_await_logical_size {
147 0 : ForceAwaitLogicalSize::Yes => format!("{}?force-await-logical-size={}", uri, true),
148 0 : ForceAwaitLogicalSize::No => uri,
149 : };
150 :
151 0 : self.get(&uri)
152 0 : .await?
153 0 : .json()
154 0 : .await
155 0 : .map_err(Error::ReceiveBody)
156 0 : }
157 :
158 0 : pub async fn keyspace(
159 0 : &self,
160 0 : tenant_shard_id: TenantShardId,
161 0 : timeline_id: TimelineId,
162 0 : ) -> Result<pageserver_api::models::partitioning::Partitioning> {
163 0 : let uri = format!(
164 0 : "{}/v1/tenant/{tenant_shard_id}/timeline/{timeline_id}/keyspace",
165 : self.mgmt_api_endpoint
166 : );
167 0 : self.get(&uri)
168 0 : .await?
169 0 : .json()
170 0 : .await
171 0 : .map_err(Error::ReceiveBody)
172 0 : }
173 :
174 0 : async fn get<U: IntoUrl>(&self, uri: U) -> Result<reqwest::Response> {
175 0 : self.request(Method::GET, uri, ()).await
176 0 : }
177 :
178 0 : fn start_request<U: reqwest::IntoUrl>(
179 0 : &self,
180 0 : method: Method,
181 0 : uri: U,
182 0 : ) -> reqwest::RequestBuilder {
183 0 : let req = self.client.request(method, uri);
184 0 : if let Some(value) = &self.authorization_header {
185 0 : req.header(reqwest::header::AUTHORIZATION, value)
186 : } else {
187 0 : req
188 : }
189 0 : }
190 :
191 0 : async fn request_noerror<B: serde::Serialize, U: reqwest::IntoUrl>(
192 0 : &self,
193 0 : method: Method,
194 0 : uri: U,
195 0 : body: B,
196 0 : ) -> Result<reqwest::Response> {
197 0 : self.start_request(method, uri)
198 0 : .json(&body)
199 0 : .send()
200 0 : .await
201 0 : .map_err(Error::ReceiveBody)
202 0 : }
203 :
204 0 : async fn request<B: serde::Serialize, U: reqwest::IntoUrl>(
205 0 : &self,
206 0 : method: Method,
207 0 : uri: U,
208 0 : body: B,
209 0 : ) -> Result<reqwest::Response> {
210 0 : let res = self.request_noerror(method, uri, body).await?;
211 0 : let response = res.error_from_body().await?;
212 0 : Ok(response)
213 0 : }
214 :
215 0 : pub async fn status(&self) -> Result<()> {
216 0 : let uri = format!("{}/v1/status", self.mgmt_api_endpoint);
217 0 : self.get(&uri).await?;
218 0 : Ok(())
219 0 : }
220 :
221 : /// The tenant deletion API can return 202 if deletion is incomplete, or
222 : /// 404 if it is complete. Callers are responsible for checking the status
223 : /// code and retrying. Error codes other than 404 will return Err().
224 0 : pub async fn tenant_delete(&self, tenant_shard_id: TenantShardId) -> Result<StatusCode> {
225 0 : let uri = format!("{}/v1/tenant/{tenant_shard_id}", self.mgmt_api_endpoint);
226 :
227 0 : match self.request(Method::DELETE, &uri, ()).await {
228 0 : Err(Error::ApiError(status_code, msg)) => {
229 0 : if status_code == StatusCode::NOT_FOUND {
230 0 : Ok(StatusCode::NOT_FOUND)
231 : } else {
232 0 : Err(Error::ApiError(status_code, msg))
233 : }
234 : }
235 0 : Err(e) => Err(e),
236 0 : Ok(response) => Ok(response.status()),
237 : }
238 0 : }
239 :
240 0 : pub async fn tenant_time_travel_remote_storage(
241 0 : &self,
242 0 : tenant_shard_id: TenantShardId,
243 0 : timestamp: &str,
244 0 : done_if_after: &str,
245 0 : ) -> Result<()> {
246 0 : let uri = format!(
247 0 : "{}/v1/tenant/{tenant_shard_id}/time_travel_remote_storage?travel_to={timestamp}&done_if_after={done_if_after}",
248 : self.mgmt_api_endpoint
249 : );
250 0 : self.request(Method::PUT, &uri, ()).await?;
251 0 : Ok(())
252 0 : }
253 :
254 0 : pub async fn tenant_scan_remote_storage(
255 0 : &self,
256 0 : tenant_id: TenantId,
257 0 : ) -> Result<TenantScanRemoteStorageResponse> {
258 0 : let uri = format!(
259 0 : "{}/v1/tenant/{tenant_id}/scan_remote_storage",
260 : self.mgmt_api_endpoint
261 : );
262 0 : let response = self.request(Method::GET, &uri, ()).await?;
263 0 : let body = response.json().await.map_err(Error::ReceiveBody)?;
264 0 : Ok(body)
265 0 : }
266 :
267 0 : pub async fn set_tenant_config(&self, req: &TenantConfigRequest) -> Result<()> {
268 0 : let uri = format!("{}/v1/tenant/config", self.mgmt_api_endpoint);
269 0 : self.request(Method::PUT, &uri, req).await?;
270 0 : Ok(())
271 0 : }
272 :
273 0 : pub async fn patch_tenant_config(&self, req: &TenantConfigPatchRequest) -> Result<()> {
274 0 : let uri = format!("{}/v1/tenant/config", self.mgmt_api_endpoint);
275 0 : self.request(Method::PATCH, &uri, req).await?;
276 0 : Ok(())
277 0 : }
278 :
279 0 : pub async fn tenant_secondary_download(
280 0 : &self,
281 0 : tenant_id: TenantShardId,
282 0 : wait: Option<std::time::Duration>,
283 0 : ) -> Result<(StatusCode, SecondaryProgress)> {
284 0 : let mut path = reqwest::Url::parse(&format!(
285 0 : "{}/v1/tenant/{}/secondary/download",
286 0 : self.mgmt_api_endpoint, tenant_id
287 0 : ))
288 0 : .expect("Cannot build URL");
289 :
290 0 : if let Some(wait) = wait {
291 0 : path.query_pairs_mut()
292 0 : .append_pair("wait_ms", &format!("{}", wait.as_millis()));
293 0 : }
294 :
295 0 : let response = self.request(Method::POST, path, ()).await?;
296 0 : let status = response.status();
297 0 : let progress: SecondaryProgress = response.json().await.map_err(Error::ReceiveBody)?;
298 0 : Ok((status, progress))
299 0 : }
300 :
301 0 : pub async fn tenant_secondary_status(
302 0 : &self,
303 0 : tenant_shard_id: TenantShardId,
304 0 : ) -> Result<SecondaryProgress> {
305 0 : let path = reqwest::Url::parse(&format!(
306 0 : "{}/v1/tenant/{}/secondary/status",
307 0 : self.mgmt_api_endpoint, tenant_shard_id
308 0 : ))
309 0 : .expect("Cannot build URL");
310 :
311 0 : self.request(Method::GET, path, ())
312 0 : .await?
313 0 : .json()
314 0 : .await
315 0 : .map_err(Error::ReceiveBody)
316 0 : }
317 :
318 0 : pub async fn tenant_heatmap_upload(&self, tenant_id: TenantShardId) -> Result<()> {
319 0 : let path = reqwest::Url::parse(&format!(
320 0 : "{}/v1/tenant/{}/heatmap_upload",
321 0 : self.mgmt_api_endpoint, tenant_id
322 0 : ))
323 0 : .expect("Cannot build URL");
324 :
325 0 : self.request(Method::POST, path, ()).await?;
326 0 : Ok(())
327 0 : }
328 :
329 0 : pub async fn location_config(
330 0 : &self,
331 0 : tenant_shard_id: TenantShardId,
332 0 : config: LocationConfig,
333 0 : flush_ms: Option<std::time::Duration>,
334 0 : lazy: bool,
335 0 : ) -> Result<()> {
336 0 : let req_body = TenantLocationConfigRequest { config };
337 :
338 0 : let mut path = reqwest::Url::parse(&format!(
339 0 : "{}/v1/tenant/{}/location_config",
340 0 : self.mgmt_api_endpoint, tenant_shard_id
341 0 : ))
342 : // Should always work: mgmt_api_endpoint is configuration, not user input.
343 0 : .expect("Cannot build URL");
344 :
345 0 : if lazy {
346 0 : path.query_pairs_mut().append_pair("lazy", "true");
347 0 : }
348 :
349 0 : if let Some(flush_ms) = flush_ms {
350 0 : path.query_pairs_mut()
351 0 : .append_pair("flush_ms", &format!("{}", flush_ms.as_millis()));
352 0 : }
353 :
354 0 : self.request(Method::PUT, path, &req_body).await?;
355 0 : Ok(())
356 0 : }
357 :
358 0 : pub async fn list_location_config(&self) -> Result<LocationConfigListResponse> {
359 0 : let path = format!("{}/v1/location_config", self.mgmt_api_endpoint);
360 0 : self.request(Method::GET, &path, ())
361 0 : .await?
362 0 : .json()
363 0 : .await
364 0 : .map_err(Error::ReceiveBody)
365 0 : }
366 :
367 0 : pub async fn get_location_config(
368 0 : &self,
369 0 : tenant_shard_id: TenantShardId,
370 0 : ) -> Result<Option<LocationConfig>> {
371 0 : let path = format!(
372 0 : "{}/v1/location_config/{tenant_shard_id}",
373 : self.mgmt_api_endpoint
374 : );
375 0 : self.request(Method::GET, &path, ())
376 0 : .await?
377 0 : .json()
378 0 : .await
379 0 : .map_err(Error::ReceiveBody)
380 0 : }
381 :
382 0 : pub async fn timeline_create(
383 0 : &self,
384 0 : tenant_shard_id: TenantShardId,
385 0 : req: &TimelineCreateRequest,
386 0 : ) -> Result<TimelineInfo> {
387 0 : let uri = format!(
388 0 : "{}/v1/tenant/{}/timeline",
389 : self.mgmt_api_endpoint, tenant_shard_id
390 : );
391 0 : self.request(Method::POST, &uri, req)
392 0 : .await?
393 0 : .json()
394 0 : .await
395 0 : .map_err(Error::ReceiveBody)
396 0 : }
397 :
398 : /// The timeline deletion API can return 201 if deletion is incomplete, or
399 : /// 403 if it is complete. Callers are responsible for checking the status
400 : /// code and retrying. Error codes other than 403 will return Err().
401 0 : pub async fn timeline_delete(
402 0 : &self,
403 0 : tenant_shard_id: TenantShardId,
404 0 : timeline_id: TimelineId,
405 0 : ) -> Result<StatusCode> {
406 0 : let uri = format!(
407 0 : "{}/v1/tenant/{tenant_shard_id}/timeline/{timeline_id}",
408 : self.mgmt_api_endpoint
409 : );
410 :
411 0 : match self.request(Method::DELETE, &uri, ()).await {
412 0 : Err(Error::ApiError(status_code, msg)) => {
413 0 : if status_code == StatusCode::NOT_FOUND {
414 0 : Ok(StatusCode::NOT_FOUND)
415 : } else {
416 0 : Err(Error::ApiError(status_code, msg))
417 : }
418 : }
419 0 : Err(e) => Err(e),
420 0 : Ok(response) => Ok(response.status()),
421 : }
422 0 : }
423 :
424 0 : pub async fn timeline_detail(
425 0 : &self,
426 0 : tenant_shard_id: TenantShardId,
427 0 : timeline_id: TimelineId,
428 0 : ) -> Result<TimelineInfo> {
429 0 : let uri = format!(
430 0 : "{}/v1/tenant/{tenant_shard_id}/timeline/{timeline_id}",
431 : self.mgmt_api_endpoint
432 : );
433 :
434 0 : self.request(Method::GET, &uri, ())
435 0 : .await?
436 0 : .json()
437 0 : .await
438 0 : .map_err(Error::ReceiveBody)
439 0 : }
440 :
441 0 : pub async fn timeline_archival_config(
442 0 : &self,
443 0 : tenant_shard_id: TenantShardId,
444 0 : timeline_id: TimelineId,
445 0 : req: &TimelineArchivalConfigRequest,
446 0 : ) -> Result<()> {
447 0 : let uri = format!(
448 0 : "{}/v1/tenant/{tenant_shard_id}/timeline/{timeline_id}/archival_config",
449 : self.mgmt_api_endpoint
450 : );
451 :
452 0 : self.request(Method::PUT, &uri, req)
453 0 : .await?
454 0 : .json()
455 0 : .await
456 0 : .map_err(Error::ReceiveBody)
457 0 : }
458 :
459 0 : pub async fn timeline_detach_ancestor(
460 0 : &self,
461 0 : tenant_shard_id: TenantShardId,
462 0 : timeline_id: TimelineId,
463 0 : behavior: Option<DetachBehavior>,
464 0 : ) -> Result<AncestorDetached> {
465 0 : let uri = format!(
466 0 : "{}/v1/tenant/{tenant_shard_id}/timeline/{timeline_id}/detach_ancestor",
467 : self.mgmt_api_endpoint
468 : );
469 0 : let mut uri = Url::parse(&uri)
470 0 : .map_err(|e| Error::ApiError(StatusCode::INTERNAL_SERVER_ERROR, format!("{e}")))?;
471 :
472 0 : if let Some(behavior) = behavior {
473 0 : uri.query_pairs_mut()
474 0 : .append_pair("detach_behavior", &behavior.to_string());
475 0 : }
476 :
477 0 : self.request(Method::PUT, uri, ())
478 0 : .await?
479 0 : .json()
480 0 : .await
481 0 : .map_err(Error::ReceiveBody)
482 0 : }
483 :
484 0 : pub async fn timeline_block_unblock_gc(
485 0 : &self,
486 0 : tenant_shard_id: TenantShardId,
487 0 : timeline_id: TimelineId,
488 0 : dir: BlockUnblock,
489 0 : ) -> Result<()> {
490 0 : let uri = format!(
491 0 : "{}/v1/tenant/{tenant_shard_id}/timeline/{timeline_id}/{dir}_gc",
492 : self.mgmt_api_endpoint,
493 : );
494 :
495 0 : self.request(Method::POST, &uri, ()).await.map(|_| ())
496 0 : }
497 :
498 0 : pub async fn timeline_download_heatmap_layers(
499 0 : &self,
500 0 : tenant_shard_id: TenantShardId,
501 0 : timeline_id: TimelineId,
502 0 : concurrency: Option<usize>,
503 0 : recurse: bool,
504 0 : ) -> Result<()> {
505 0 : let mut path = reqwest::Url::parse(&format!(
506 0 : "{}/v1/tenant/{}/timeline/{}/download_heatmap_layers",
507 0 : self.mgmt_api_endpoint, tenant_shard_id, timeline_id
508 0 : ))
509 0 : .expect("Cannot build URL");
510 :
511 0 : path.query_pairs_mut()
512 0 : .append_pair("recurse", &format!("{recurse}"));
513 :
514 0 : if let Some(concurrency) = concurrency {
515 0 : path.query_pairs_mut()
516 0 : .append_pair("concurrency", &format!("{concurrency}"));
517 0 : }
518 :
519 0 : self.request(Method::POST, path, ()).await.map(|_| ())
520 0 : }
521 :
522 0 : pub async fn tenant_reset(&self, tenant_shard_id: TenantShardId) -> Result<()> {
523 0 : let uri = format!(
524 0 : "{}/v1/tenant/{}/reset",
525 : self.mgmt_api_endpoint, tenant_shard_id
526 : );
527 0 : self.request(Method::POST, &uri, ())
528 0 : .await?
529 0 : .json()
530 0 : .await
531 0 : .map_err(Error::ReceiveBody)
532 0 : }
533 :
534 0 : pub async fn tenant_shard_split(
535 0 : &self,
536 0 : tenant_shard_id: TenantShardId,
537 0 : req: TenantShardSplitRequest,
538 0 : ) -> Result<TenantShardSplitResponse> {
539 0 : let uri = format!(
540 0 : "{}/v1/tenant/{}/shard_split",
541 : self.mgmt_api_endpoint, tenant_shard_id
542 : );
543 0 : self.request(Method::PUT, &uri, req)
544 0 : .await?
545 0 : .json()
546 0 : .await
547 0 : .map_err(Error::ReceiveBody)
548 0 : }
549 :
550 0 : pub async fn timeline_list(
551 0 : &self,
552 0 : tenant_shard_id: &TenantShardId,
553 0 : ) -> Result<Vec<TimelineInfo>> {
554 0 : let uri = format!(
555 0 : "{}/v1/tenant/{}/timeline",
556 : self.mgmt_api_endpoint, tenant_shard_id
557 : );
558 0 : self.get(&uri)
559 0 : .await?
560 0 : .json()
561 0 : .await
562 0 : .map_err(Error::ReceiveBody)
563 0 : }
564 :
565 0 : pub async fn tenant_synthetic_size(
566 0 : &self,
567 0 : tenant_shard_id: TenantShardId,
568 0 : ) -> Result<TenantHistorySize> {
569 0 : let uri = format!(
570 0 : "{}/v1/tenant/{}/synthetic_size",
571 : self.mgmt_api_endpoint, tenant_shard_id
572 : );
573 0 : self.get(&uri)
574 0 : .await?
575 0 : .json()
576 0 : .await
577 0 : .map_err(Error::ReceiveBody)
578 0 : }
579 :
580 0 : pub async fn put_io_engine(
581 0 : &self,
582 0 : engine: &pageserver_api::models::virtual_file::IoEngineKind,
583 0 : ) -> Result<()> {
584 0 : let uri = format!("{}/v1/io_engine", self.mgmt_api_endpoint);
585 0 : self.request(Method::PUT, uri, engine)
586 0 : .await?
587 0 : .json()
588 0 : .await
589 0 : .map_err(Error::ReceiveBody)
590 0 : }
591 :
592 : /// Configs io mode at runtime.
593 0 : pub async fn put_io_mode(
594 0 : &self,
595 0 : mode: &pageserver_api::models::virtual_file::IoMode,
596 0 : ) -> Result<()> {
597 0 : let uri = format!("{}/v1/io_mode", self.mgmt_api_endpoint);
598 0 : self.request(Method::PUT, uri, mode)
599 0 : .await?
600 0 : .json()
601 0 : .await
602 0 : .map_err(Error::ReceiveBody)
603 0 : }
604 :
605 0 : pub async fn get_utilization(&self) -> Result<PageserverUtilization> {
606 0 : let uri = format!("{}/v1/utilization", self.mgmt_api_endpoint);
607 0 : self.get(uri)
608 0 : .await?
609 0 : .json()
610 0 : .await
611 0 : .map_err(Error::ReceiveBody)
612 0 : }
613 :
614 0 : pub async fn top_tenant_shards(
615 0 : &self,
616 0 : request: TopTenantShardsRequest,
617 0 : ) -> Result<TopTenantShardsResponse> {
618 0 : let uri = format!("{}/v1/top_tenants", self.mgmt_api_endpoint);
619 0 : self.request(Method::POST, uri, request)
620 0 : .await?
621 0 : .json()
622 0 : .await
623 0 : .map_err(Error::ReceiveBody)
624 0 : }
625 :
626 0 : pub async fn layer_map_info(
627 0 : &self,
628 0 : tenant_shard_id: TenantShardId,
629 0 : timeline_id: TimelineId,
630 0 : ) -> Result<LayerMapInfo> {
631 0 : let uri = format!(
632 0 : "{}/v1/tenant/{}/timeline/{}/layer",
633 : self.mgmt_api_endpoint, tenant_shard_id, timeline_id,
634 : );
635 0 : self.get(&uri)
636 0 : .await?
637 0 : .json()
638 0 : .await
639 0 : .map_err(Error::ReceiveBody)
640 0 : }
641 :
642 0 : pub async fn layer_evict(
643 0 : &self,
644 0 : tenant_shard_id: TenantShardId,
645 0 : timeline_id: TimelineId,
646 0 : layer_file_name: &str,
647 0 : ) -> Result<bool> {
648 0 : let uri = format!(
649 0 : "{}/v1/tenant/{}/timeline/{}/layer/{}",
650 : self.mgmt_api_endpoint, tenant_shard_id, timeline_id, layer_file_name
651 : );
652 0 : let resp = self.request_noerror(Method::DELETE, &uri, ()).await?;
653 0 : match resp.status() {
654 0 : StatusCode::OK => Ok(true),
655 0 : StatusCode::NOT_MODIFIED => Ok(false),
656 : // TODO: dedupe this pattern / introduce separate error variant?
657 0 : status => Err(match resp.json::<HttpErrorBody>().await {
658 0 : Ok(HttpErrorBody { msg }) => Error::ApiError(status, msg),
659 : Err(_) => {
660 0 : Error::ReceiveErrorBody(format!("Http error ({}) at {}.", status.as_u16(), uri))
661 : }
662 : }),
663 : }
664 0 : }
665 :
666 0 : pub async fn layer_ondemand_download(
667 0 : &self,
668 0 : tenant_shard_id: TenantShardId,
669 0 : timeline_id: TimelineId,
670 0 : layer_file_name: &str,
671 0 : ) -> Result<bool> {
672 0 : let uri = format!(
673 0 : "{}/v1/tenant/{}/timeline/{}/layer/{}",
674 : self.mgmt_api_endpoint, tenant_shard_id, timeline_id, layer_file_name
675 : );
676 0 : let resp = self.request_noerror(Method::GET, &uri, ()).await?;
677 0 : match resp.status() {
678 0 : StatusCode::OK => Ok(true),
679 0 : StatusCode::NOT_MODIFIED => Ok(false),
680 : // TODO: dedupe this pattern / introduce separate error variant?
681 0 : status => Err(match resp.json::<HttpErrorBody>().await {
682 0 : Ok(HttpErrorBody { msg }) => Error::ApiError(status, msg),
683 : Err(_) => {
684 0 : Error::ReceiveErrorBody(format!("Http error ({}) at {}.", status.as_u16(), uri))
685 : }
686 : }),
687 : }
688 0 : }
689 :
690 0 : pub async fn ingest_aux_files(
691 0 : &self,
692 0 : tenant_shard_id: TenantShardId,
693 0 : timeline_id: TimelineId,
694 0 : aux_files: HashMap<String, String>,
695 0 : ) -> Result<bool> {
696 0 : let uri = format!(
697 0 : "{}/v1/tenant/{}/timeline/{}/ingest_aux_files",
698 : self.mgmt_api_endpoint, tenant_shard_id, timeline_id
699 : );
700 0 : let resp = self
701 0 : .request_noerror(Method::POST, &uri, IngestAuxFilesRequest { aux_files })
702 0 : .await?;
703 0 : match resp.status() {
704 0 : StatusCode::OK => Ok(true),
705 0 : status => Err(match resp.json::<HttpErrorBody>().await {
706 0 : Ok(HttpErrorBody { msg }) => Error::ApiError(status, msg),
707 : Err(_) => {
708 0 : Error::ReceiveErrorBody(format!("Http error ({}) at {}.", status.as_u16(), uri))
709 : }
710 : }),
711 : }
712 0 : }
713 :
714 0 : pub async fn list_aux_files(
715 0 : &self,
716 0 : tenant_shard_id: TenantShardId,
717 0 : timeline_id: TimelineId,
718 0 : lsn: Lsn,
719 0 : ) -> Result<HashMap<String, Bytes>> {
720 0 : let uri = format!(
721 0 : "{}/v1/tenant/{}/timeline/{}/list_aux_files",
722 : self.mgmt_api_endpoint, tenant_shard_id, timeline_id
723 : );
724 0 : let resp = self
725 0 : .request_noerror(Method::POST, &uri, ListAuxFilesRequest { lsn })
726 0 : .await?;
727 0 : match resp.status() {
728 : StatusCode::OK => {
729 0 : let resp: HashMap<String, Bytes> = resp.json().await.map_err(|e| {
730 0 : Error::ApiError(StatusCode::INTERNAL_SERVER_ERROR, format!("{e}"))
731 0 : })?;
732 0 : Ok(resp)
733 : }
734 0 : status => Err(match resp.json::<HttpErrorBody>().await {
735 0 : Ok(HttpErrorBody { msg }) => Error::ApiError(status, msg),
736 : Err(_) => {
737 0 : Error::ReceiveErrorBody(format!("Http error ({}) at {}.", status.as_u16(), uri))
738 : }
739 : }),
740 : }
741 0 : }
742 :
743 0 : pub async fn import_basebackup(
744 0 : &self,
745 0 : tenant_id: TenantId,
746 0 : timeline_id: TimelineId,
747 0 : base_lsn: Lsn,
748 0 : end_lsn: Lsn,
749 0 : pg_version: PgMajorVersion,
750 0 : basebackup_tarball: ReqwestBody,
751 0 : ) -> Result<()> {
752 0 : let pg_version = pg_version.major_version_num();
753 :
754 0 : let uri = format!(
755 0 : "{}/v1/tenant/{tenant_id}/timeline/{timeline_id}/import_basebackup?base_lsn={base_lsn}&end_lsn={end_lsn}&pg_version={pg_version}",
756 : self.mgmt_api_endpoint,
757 : );
758 0 : self.start_request(Method::PUT, uri)
759 0 : .body(basebackup_tarball)
760 0 : .send()
761 0 : .await
762 0 : .map_err(Error::SendRequest)?
763 0 : .error_from_body()
764 0 : .await?
765 0 : .json()
766 0 : .await
767 0 : .map_err(Error::ReceiveBody)
768 0 : }
769 :
770 0 : pub async fn import_wal(
771 0 : &self,
772 0 : tenant_id: TenantId,
773 0 : timeline_id: TimelineId,
774 0 : start_lsn: Lsn,
775 0 : end_lsn: Lsn,
776 0 : wal_tarball: ReqwestBody,
777 0 : ) -> Result<()> {
778 0 : let uri = format!(
779 0 : "{}/v1/tenant/{tenant_id}/timeline/{timeline_id}/import_wal?start_lsn={start_lsn}&end_lsn={end_lsn}",
780 : self.mgmt_api_endpoint,
781 : );
782 0 : self.start_request(Method::PUT, uri)
783 0 : .body(wal_tarball)
784 0 : .send()
785 0 : .await
786 0 : .map_err(Error::SendRequest)?
787 0 : .error_from_body()
788 0 : .await?
789 0 : .json()
790 0 : .await
791 0 : .map_err(Error::ReceiveBody)
792 0 : }
793 :
794 0 : pub async fn timeline_init_lsn_lease(
795 0 : &self,
796 0 : tenant_shard_id: TenantShardId,
797 0 : timeline_id: TimelineId,
798 0 : lsn: Lsn,
799 0 : ) -> Result<LsnLease> {
800 0 : let uri = format!(
801 0 : "{}/v1/tenant/{tenant_shard_id}/timeline/{timeline_id}/lsn_lease",
802 : self.mgmt_api_endpoint,
803 : );
804 :
805 0 : self.request(Method::POST, &uri, LsnLeaseRequest { lsn })
806 0 : .await?
807 0 : .json()
808 0 : .await
809 0 : .map_err(Error::ReceiveBody)
810 0 : }
811 :
812 0 : pub async fn wait_lsn(
813 0 : &self,
814 0 : tenant_shard_id: TenantShardId,
815 0 : request: TenantWaitLsnRequest,
816 0 : ) -> Result<StatusCode> {
817 0 : let uri = format!(
818 0 : "{}/v1/tenant/{tenant_shard_id}/wait_lsn",
819 : self.mgmt_api_endpoint,
820 : );
821 :
822 0 : self.request_noerror(Method::POST, uri, request)
823 0 : .await
824 0 : .map(|resp| resp.status())
825 0 : }
826 :
827 0 : pub async fn activate_post_import(
828 0 : &self,
829 0 : tenant_shard_id: TenantShardId,
830 0 : timeline_id: TimelineId,
831 0 : activate_timeline_timeout: Duration,
832 0 : ) -> Result<TimelineInfo> {
833 0 : let uri = format!(
834 0 : "{}/v1/tenant/{}/timeline/{}/activate_post_import?timeline_activate_timeout_ms={}",
835 : self.mgmt_api_endpoint,
836 : tenant_shard_id,
837 : timeline_id,
838 0 : activate_timeline_timeout.as_millis()
839 : );
840 :
841 0 : self.request(Method::PUT, uri, ())
842 0 : .await?
843 0 : .json()
844 0 : .await
845 0 : .map_err(Error::ReceiveBody)
846 0 : }
847 :
848 0 : pub async fn update_feature_flag_spec(&self, spec: String) -> Result<()> {
849 0 : let uri = format!("{}/v1/feature_flag_spec", self.mgmt_api_endpoint);
850 0 : self.request(Method::POST, uri, spec)
851 0 : .await?
852 0 : .json()
853 0 : .await
854 0 : .map_err(Error::ReceiveBody)
855 0 : }
856 : }
|