LCOV - code coverage report
Current view: top level - storage_controller/src - http.rs (source / functions) Coverage Total Hit
Test: 42f947419473a288706e86ecdf7c2863d760d5d7.info Lines: 0.0 % 906 0
Test Date: 2024-08-02 21:34:27 Functions: 0.0 % 313 0

            Line data    Source code
       1              : use crate::metrics::{
       2              :     HttpRequestLatencyLabelGroup, HttpRequestStatusLabelGroup, PageserverRequestLabelGroup,
       3              :     METRICS_REGISTRY,
       4              : };
       5              : use crate::reconciler::ReconcileError;
       6              : use crate::service::{LeadershipStatus, Service, STARTUP_RECONCILE_TIMEOUT};
       7              : use anyhow::Context;
       8              : use futures::Future;
       9              : use hyper::header::CONTENT_TYPE;
      10              : use hyper::{Body, Request, Response};
      11              : use hyper::{StatusCode, Uri};
      12              : use metrics::{BuildInfo, NeonMetrics};
      13              : use pageserver_api::controller_api::{
      14              :     MetadataHealthListOutdatedRequest, MetadataHealthListOutdatedResponse,
      15              :     MetadataHealthListUnhealthyResponse, MetadataHealthUpdateRequest, MetadataHealthUpdateResponse,
      16              :     TenantCreateRequest,
      17              : };
      18              : use pageserver_api::models::{
      19              :     TenantConfigRequest, TenantLocationConfigRequest, TenantShardSplitRequest,
      20              :     TenantTimeTravelRequest, TimelineCreateRequest,
      21              : };
      22              : use pageserver_api::shard::TenantShardId;
      23              : use pageserver_client::mgmt_api;
      24              : use std::sync::Arc;
      25              : use std::time::{Duration, Instant};
      26              : use tokio_util::sync::CancellationToken;
      27              : use utils::auth::{Scope, SwappableJwtAuth};
      28              : use utils::failpoint_support::failpoints_handler;
      29              : use utils::http::endpoint::{auth_middleware, check_permission_with, request_span};
      30              : use utils::http::request::{must_get_query_param, parse_query_param, parse_request_param};
      31              : use utils::id::{TenantId, TimelineId};
      32              : 
      33              : use utils::{
      34              :     http::{
      35              :         endpoint::{self},
      36              :         error::ApiError,
      37              :         json::{json_request, json_response},
      38              :         RequestExt, RouterBuilder,
      39              :     },
      40              :     id::NodeId,
      41              : };
      42              : 
      43              : use pageserver_api::controller_api::{
      44              :     NodeAvailability, NodeConfigureRequest, NodeRegisterRequest, TenantPolicyRequest,
      45              :     TenantShardMigrateRequest,
      46              : };
      47              : use pageserver_api::upcall_api::{ReAttachRequest, ValidateRequest};
      48              : 
      49              : use control_plane::storage_controller::{AttachHookRequest, InspectRequest};
      50              : 
      51              : use routerify::Middleware;
      52              : 
      53              : /// State available to HTTP request handlers
      54              : pub struct HttpState {
      55              :     service: Arc<crate::service::Service>,
      56              :     auth: Option<Arc<SwappableJwtAuth>>,
      57              :     neon_metrics: NeonMetrics,
      58              :     allowlist_routes: Vec<Uri>,
      59              : }
      60              : 
      61              : impl HttpState {
      62            0 :     pub fn new(
      63            0 :         service: Arc<crate::service::Service>,
      64            0 :         auth: Option<Arc<SwappableJwtAuth>>,
      65            0 :         build_info: BuildInfo,
      66            0 :     ) -> Self {
      67            0 :         let allowlist_routes = ["/status", "/ready", "/metrics"]
      68            0 :             .iter()
      69            0 :             .map(|v| v.parse().unwrap())
      70            0 :             .collect::<Vec<_>>();
      71            0 :         Self {
      72            0 :             service,
      73            0 :             auth,
      74            0 :             neon_metrics: NeonMetrics::new(build_info),
      75            0 :             allowlist_routes,
      76            0 :         }
      77            0 :     }
      78              : }
      79              : 
      80              : #[inline(always)]
      81            0 : fn get_state(request: &Request<Body>) -> &HttpState {
      82            0 :     request
      83            0 :         .data::<Arc<HttpState>>()
      84            0 :         .expect("unknown state type")
      85            0 :         .as_ref()
      86            0 : }
      87              : 
      88              : /// Pageserver calls into this on startup, to learn which tenants it should attach
      89            0 : async fn handle_re_attach(mut req: Request<Body>) -> Result<Response<Body>, ApiError> {
      90            0 :     check_permissions(&req, Scope::GenerationsApi)?;
      91              : 
      92            0 :     let reattach_req = json_request::<ReAttachRequest>(&mut req).await?;
      93            0 :     let state = get_state(&req);
      94            0 :     json_response(StatusCode::OK, state.service.re_attach(reattach_req).await?)
      95            0 : }
      96              : 
      97              : /// Pageserver calls into this before doing deletions, to confirm that it still
      98              : /// holds the latest generation for the tenants with deletions enqueued
      99            0 : async fn handle_validate(mut req: Request<Body>) -> Result<Response<Body>, ApiError> {
     100            0 :     check_permissions(&req, Scope::GenerationsApi)?;
     101              : 
     102            0 :     let validate_req = json_request::<ValidateRequest>(&mut req).await?;
     103            0 :     let state = get_state(&req);
     104            0 :     json_response(StatusCode::OK, state.service.validate(validate_req))
     105            0 : }
     106              : 
     107              : /// Call into this before attaching a tenant to a pageserver, to acquire a generation number
     108              : /// (in the real control plane this is unnecessary, because the same program is managing
     109              : ///  generation numbers and doing attachments).
     110            0 : async fn handle_attach_hook(mut req: Request<Body>) -> Result<Response<Body>, ApiError> {
     111            0 :     check_permissions(&req, Scope::Admin)?;
     112              : 
     113            0 :     let attach_req = json_request::<AttachHookRequest>(&mut req).await?;
     114            0 :     let state = get_state(&req);
     115            0 : 
     116            0 :     json_response(
     117            0 :         StatusCode::OK,
     118            0 :         state
     119            0 :             .service
     120            0 :             .attach_hook(attach_req)
     121            0 :             .await
     122            0 :             .map_err(ApiError::InternalServerError)?,
     123              :     )
     124            0 : }
     125              : 
     126            0 : async fn handle_inspect(mut req: Request<Body>) -> Result<Response<Body>, ApiError> {
     127            0 :     check_permissions(&req, Scope::Admin)?;
     128              : 
     129            0 :     let inspect_req = json_request::<InspectRequest>(&mut req).await?;
     130              : 
     131            0 :     let state = get_state(&req);
     132            0 : 
     133            0 :     json_response(StatusCode::OK, state.service.inspect(inspect_req))
     134            0 : }
     135              : 
     136            0 : async fn handle_tenant_create(
     137            0 :     service: Arc<Service>,
     138            0 :     mut req: Request<Body>,
     139            0 : ) -> Result<Response<Body>, ApiError> {
     140            0 :     check_permissions(&req, Scope::PageServerApi)?;
     141              : 
     142            0 :     let create_req = json_request::<TenantCreateRequest>(&mut req).await?;
     143              : 
     144              :     json_response(
     145              :         StatusCode::CREATED,
     146            0 :         service.tenant_create(create_req).await?,
     147              :     )
     148            0 : }
     149              : 
     150            0 : async fn handle_tenant_location_config(
     151            0 :     service: Arc<Service>,
     152            0 :     mut req: Request<Body>,
     153            0 : ) -> Result<Response<Body>, ApiError> {
     154            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&req, "tenant_shard_id")?;
     155            0 :     check_permissions(&req, Scope::PageServerApi)?;
     156              : 
     157            0 :     let config_req = json_request::<TenantLocationConfigRequest>(&mut req).await?;
     158              :     json_response(
     159              :         StatusCode::OK,
     160            0 :         service
     161            0 :             .tenant_location_config(tenant_shard_id, config_req)
     162            0 :             .await?,
     163              :     )
     164            0 : }
     165              : 
     166            0 : async fn handle_tenant_config_set(
     167            0 :     service: Arc<Service>,
     168            0 :     mut req: Request<Body>,
     169            0 : ) -> Result<Response<Body>, ApiError> {
     170            0 :     check_permissions(&req, Scope::PageServerApi)?;
     171              : 
     172            0 :     let config_req = json_request::<TenantConfigRequest>(&mut req).await?;
     173              : 
     174            0 :     json_response(StatusCode::OK, service.tenant_config_set(config_req).await?)
     175            0 : }
     176              : 
     177            0 : async fn handle_tenant_config_get(
     178            0 :     service: Arc<Service>,
     179            0 :     req: Request<Body>,
     180            0 : ) -> Result<Response<Body>, ApiError> {
     181            0 :     let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
     182            0 :     check_permissions(&req, Scope::PageServerApi)?;
     183              : 
     184            0 :     json_response(StatusCode::OK, service.tenant_config_get(tenant_id)?)
     185            0 : }
     186              : 
     187            0 : async fn handle_tenant_time_travel_remote_storage(
     188            0 :     service: Arc<Service>,
     189            0 :     mut req: Request<Body>,
     190            0 : ) -> Result<Response<Body>, ApiError> {
     191            0 :     let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
     192            0 :     check_permissions(&req, Scope::PageServerApi)?;
     193              : 
     194            0 :     let time_travel_req = json_request::<TenantTimeTravelRequest>(&mut req).await?;
     195              : 
     196            0 :     let timestamp_raw = must_get_query_param(&req, "travel_to")?;
     197            0 :     let _timestamp = humantime::parse_rfc3339(&timestamp_raw).map_err(|_e| {
     198            0 :         ApiError::BadRequest(anyhow::anyhow!(
     199            0 :             "Invalid time for travel_to: {timestamp_raw:?}"
     200            0 :         ))
     201            0 :     })?;
     202              : 
     203            0 :     let done_if_after_raw = must_get_query_param(&req, "done_if_after")?;
     204            0 :     let _done_if_after = humantime::parse_rfc3339(&done_if_after_raw).map_err(|_e| {
     205            0 :         ApiError::BadRequest(anyhow::anyhow!(
     206            0 :             "Invalid time for done_if_after: {done_if_after_raw:?}"
     207            0 :         ))
     208            0 :     })?;
     209              : 
     210            0 :     service
     211            0 :         .tenant_time_travel_remote_storage(
     212            0 :             &time_travel_req,
     213            0 :             tenant_id,
     214            0 :             timestamp_raw,
     215            0 :             done_if_after_raw,
     216            0 :         )
     217            0 :         .await?;
     218            0 :     json_response(StatusCode::OK, ())
     219            0 : }
     220              : 
     221            0 : fn map_reqwest_hyper_status(status: reqwest::StatusCode) -> Result<hyper::StatusCode, ApiError> {
     222            0 :     hyper::StatusCode::from_u16(status.as_u16())
     223            0 :         .context("invalid status code")
     224            0 :         .map_err(ApiError::InternalServerError)
     225            0 : }
     226              : 
     227            0 : async fn handle_tenant_secondary_download(
     228            0 :     service: Arc<Service>,
     229            0 :     req: Request<Body>,
     230            0 : ) -> Result<Response<Body>, ApiError> {
     231            0 :     let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
     232            0 :     let wait = parse_query_param(&req, "wait_ms")?.map(Duration::from_millis);
     233              : 
     234            0 :     let (status, progress) = service.tenant_secondary_download(tenant_id, wait).await?;
     235            0 :     json_response(map_reqwest_hyper_status(status)?, progress)
     236            0 : }
     237              : 
     238            0 : async fn handle_tenant_delete(
     239            0 :     service: Arc<Service>,
     240            0 :     req: Request<Body>,
     241            0 : ) -> Result<Response<Body>, ApiError> {
     242            0 :     let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
     243            0 :     check_permissions(&req, Scope::PageServerApi)?;
     244              : 
     245            0 :     let status_code = service
     246            0 :         .tenant_delete(tenant_id)
     247            0 :         .await
     248            0 :         .and_then(map_reqwest_hyper_status)?;
     249              : 
     250            0 :     if status_code == StatusCode::NOT_FOUND {
     251              :         // The pageserver uses 404 for successful deletion, but we use 200
     252            0 :         json_response(StatusCode::OK, ())
     253              :     } else {
     254            0 :         json_response(status_code, ())
     255              :     }
     256            0 : }
     257              : 
     258            0 : async fn handle_tenant_timeline_create(
     259            0 :     service: Arc<Service>,
     260            0 :     mut req: Request<Body>,
     261            0 : ) -> Result<Response<Body>, ApiError> {
     262            0 :     let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
     263            0 :     check_permissions(&req, Scope::PageServerApi)?;
     264              : 
     265            0 :     let create_req = json_request::<TimelineCreateRequest>(&mut req).await?;
     266              :     json_response(
     267              :         StatusCode::CREATED,
     268            0 :         service
     269            0 :             .tenant_timeline_create(tenant_id, create_req)
     270            0 :             .await?,
     271              :     )
     272            0 : }
     273              : 
     274            0 : async fn handle_tenant_timeline_delete(
     275            0 :     service: Arc<Service>,
     276            0 :     req: Request<Body>,
     277            0 : ) -> Result<Response<Body>, ApiError> {
     278            0 :     let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
     279            0 :     check_permissions(&req, Scope::PageServerApi)?;
     280              : 
     281            0 :     let timeline_id: TimelineId = parse_request_param(&req, "timeline_id")?;
     282              : 
     283              :     // For timeline deletions, which both implement an "initially return 202, then 404 once
     284              :     // we're done" semantic, we wrap with a retry loop to expose a simpler API upstream.
     285            0 :     async fn deletion_wrapper<R, F>(service: Arc<Service>, f: F) -> Result<Response<Body>, ApiError>
     286            0 :     where
     287            0 :         R: std::future::Future<Output = Result<StatusCode, ApiError>> + Send + 'static,
     288            0 :         F: Fn(Arc<Service>) -> R + Send + Sync + 'static,
     289            0 :     {
     290            0 :         let started_at = Instant::now();
     291            0 :         // To keep deletion reasonably snappy for small tenants, initially check after 1 second if deletion
     292            0 :         // completed.
     293            0 :         let mut retry_period = Duration::from_secs(1);
     294            0 :         // On subsequent retries, wait longer.
     295            0 :         let max_retry_period = Duration::from_secs(5);
     296            0 :         // Enable callers with a 30 second request timeout to reliably get a response
     297            0 :         let max_wait = Duration::from_secs(25);
     298              : 
     299              :         loop {
     300            0 :             let status = f(service.clone()).await?;
     301            0 :             match status {
     302              :                 StatusCode::ACCEPTED => {
     303            0 :                     tracing::info!("Deletion accepted, waiting to try again...");
     304            0 :                     tokio::time::sleep(retry_period).await;
     305            0 :                     retry_period = max_retry_period;
     306              :                 }
     307              :                 StatusCode::NOT_FOUND => {
     308            0 :                     tracing::info!("Deletion complete");
     309            0 :                     return json_response(StatusCode::OK, ());
     310              :                 }
     311              :                 _ => {
     312            0 :                     tracing::warn!("Unexpected status {status}");
     313            0 :                     return json_response(status, ());
     314              :                 }
     315              :             }
     316              : 
     317            0 :             let now = Instant::now();
     318            0 :             if now + retry_period > started_at + max_wait {
     319            0 :                 tracing::info!("Deletion timed out waiting for 404");
     320              :                 // REQUEST_TIMEOUT would be more appropriate, but CONFLICT is already part of
     321              :                 // the pageserver's swagger definition for this endpoint, and has the same desired
     322              :                 // effect of causing the control plane to retry later.
     323            0 :                 return json_response(StatusCode::CONFLICT, ());
     324            0 :             }
     325              :         }
     326            0 :     }
     327              : 
     328            0 :     deletion_wrapper(service, move |service| async move {
     329            0 :         service
     330            0 :             .tenant_timeline_delete(tenant_id, timeline_id)
     331            0 :             .await
     332            0 :             .and_then(map_reqwest_hyper_status)
     333            0 :     })
     334            0 :     .await
     335            0 : }
     336              : 
     337            0 : async fn handle_tenant_timeline_detach_ancestor(
     338            0 :     service: Arc<Service>,
     339            0 :     req: Request<Body>,
     340            0 : ) -> Result<Response<Body>, ApiError> {
     341            0 :     let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
     342            0 :     check_permissions(&req, Scope::PageServerApi)?;
     343              : 
     344            0 :     let timeline_id: TimelineId = parse_request_param(&req, "timeline_id")?;
     345              : 
     346            0 :     let res = service
     347            0 :         .tenant_timeline_detach_ancestor(tenant_id, timeline_id)
     348            0 :         .await?;
     349              : 
     350            0 :     json_response(StatusCode::OK, res)
     351            0 : }
     352              : 
     353            0 : async fn handle_tenant_timeline_passthrough(
     354            0 :     service: Arc<Service>,
     355            0 :     req: Request<Body>,
     356            0 : ) -> Result<Response<Body>, ApiError> {
     357            0 :     let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
     358            0 :     check_permissions(&req, Scope::PageServerApi)?;
     359              : 
     360            0 :     let Some(path) = req.uri().path_and_query() else {
     361              :         // This should never happen, our request router only calls us if there is a path
     362            0 :         return Err(ApiError::BadRequest(anyhow::anyhow!("Missing path")));
     363              :     };
     364              : 
     365            0 :     tracing::info!("Proxying request for tenant {} ({})", tenant_id, path);
     366              : 
     367              :     // Find the node that holds shard zero
     368            0 :     let (node, tenant_shard_id) = service.tenant_shard0_node(tenant_id)?;
     369              : 
     370              :     // Callers will always pass an unsharded tenant ID.  Before proxying, we must
     371              :     // rewrite this to a shard-aware shard zero ID.
     372            0 :     let path = format!("{}", path);
     373            0 :     let tenant_str = tenant_id.to_string();
     374            0 :     let tenant_shard_str = format!("{}", tenant_shard_id);
     375            0 :     let path = path.replace(&tenant_str, &tenant_shard_str);
     376            0 : 
     377            0 :     let latency = &METRICS_REGISTRY
     378            0 :         .metrics_group
     379            0 :         .storage_controller_passthrough_request_latency;
     380            0 : 
     381            0 :     // This is a bit awkward. We remove the param from the request
     382            0 :     // and join the words by '_' to get a label for the request.
     383            0 :     let just_path = path.replace(&tenant_shard_str, "");
     384            0 :     let path_label = just_path
     385            0 :         .split('/')
     386            0 :         .filter(|token| !token.is_empty())
     387            0 :         .collect::<Vec<_>>()
     388            0 :         .join("_");
     389            0 :     let labels = PageserverRequestLabelGroup {
     390            0 :         pageserver_id: &node.get_id().to_string(),
     391            0 :         path: &path_label,
     392            0 :         method: crate::metrics::Method::Get,
     393            0 :     };
     394            0 : 
     395            0 :     let _timer = latency.start_timer(labels.clone());
     396            0 : 
     397            0 :     let client = mgmt_api::Client::new(node.base_url(), service.get_config().jwt_token.as_deref());
     398            0 :     let resp = client.get_raw(path).await.map_err(|_e|
     399              :         // FIXME: give APiError a proper Unavailable variant.  We return 503 here because
     400              :         // if we can't successfully send a request to the pageserver, we aren't available.
     401            0 :         ApiError::ShuttingDown)?;
     402              : 
     403            0 :     if !resp.status().is_success() {
     404            0 :         let error_counter = &METRICS_REGISTRY
     405            0 :             .metrics_group
     406            0 :             .storage_controller_passthrough_request_error;
     407            0 :         error_counter.inc(labels);
     408            0 :     }
     409              : 
     410              :     // We have a reqest::Response, would like a http::Response
     411            0 :     let mut builder = hyper::Response::builder().status(map_reqwest_hyper_status(resp.status())?);
     412            0 :     for (k, v) in resp.headers() {
     413            0 :         builder = builder.header(k.as_str(), v.as_bytes());
     414            0 :     }
     415              : 
     416            0 :     let response = builder
     417            0 :         .body(Body::wrap_stream(resp.bytes_stream()))
     418            0 :         .map_err(|e| ApiError::InternalServerError(e.into()))?;
     419              : 
     420            0 :     Ok(response)
     421            0 : }
     422              : 
     423            0 : async fn handle_tenant_locate(
     424            0 :     service: Arc<Service>,
     425            0 :     req: Request<Body>,
     426            0 : ) -> Result<Response<Body>, ApiError> {
     427            0 :     check_permissions(&req, Scope::Admin)?;
     428              : 
     429            0 :     let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
     430            0 :     json_response(StatusCode::OK, service.tenant_locate(tenant_id)?)
     431            0 : }
     432              : 
     433            0 : async fn handle_tenant_describe(
     434            0 :     service: Arc<Service>,
     435            0 :     req: Request<Body>,
     436            0 : ) -> Result<Response<Body>, ApiError> {
     437            0 :     check_permissions(&req, Scope::Scrubber)?;
     438              : 
     439            0 :     let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
     440            0 :     json_response(StatusCode::OK, service.tenant_describe(tenant_id)?)
     441            0 : }
     442              : 
     443            0 : async fn handle_tenant_list(
     444            0 :     service: Arc<Service>,
     445            0 :     req: Request<Body>,
     446            0 : ) -> Result<Response<Body>, ApiError> {
     447            0 :     check_permissions(&req, Scope::Admin)?;
     448              : 
     449            0 :     json_response(StatusCode::OK, service.tenant_list())
     450            0 : }
     451              : 
     452            0 : async fn handle_node_register(mut req: Request<Body>) -> Result<Response<Body>, ApiError> {
     453            0 :     check_permissions(&req, Scope::Admin)?;
     454              : 
     455            0 :     let register_req = json_request::<NodeRegisterRequest>(&mut req).await?;
     456            0 :     let state = get_state(&req);
     457            0 :     state.service.node_register(register_req).await?;
     458            0 :     json_response(StatusCode::OK, ())
     459            0 : }
     460              : 
     461            0 : async fn handle_node_list(req: Request<Body>) -> Result<Response<Body>, ApiError> {
     462            0 :     check_permissions(&req, Scope::Admin)?;
     463              : 
     464            0 :     let state = get_state(&req);
     465            0 :     let nodes = state.service.node_list().await?;
     466            0 :     let api_nodes = nodes.into_iter().map(|n| n.describe()).collect::<Vec<_>>();
     467            0 : 
     468            0 :     json_response(StatusCode::OK, api_nodes)
     469            0 : }
     470              : 
     471            0 : async fn handle_node_drop(req: Request<Body>) -> Result<Response<Body>, ApiError> {
     472            0 :     check_permissions(&req, Scope::Admin)?;
     473              : 
     474            0 :     let state = get_state(&req);
     475            0 :     let node_id: NodeId = parse_request_param(&req, "node_id")?;
     476            0 :     json_response(StatusCode::OK, state.service.node_drop(node_id).await?)
     477            0 : }
     478              : 
     479            0 : async fn handle_node_delete(req: Request<Body>) -> Result<Response<Body>, ApiError> {
     480            0 :     check_permissions(&req, Scope::Admin)?;
     481              : 
     482            0 :     let state = get_state(&req);
     483            0 :     let node_id: NodeId = parse_request_param(&req, "node_id")?;
     484            0 :     json_response(StatusCode::OK, state.service.node_delete(node_id).await?)
     485            0 : }
     486              : 
     487            0 : async fn handle_node_configure(mut req: Request<Body>) -> Result<Response<Body>, ApiError> {
     488            0 :     check_permissions(&req, Scope::Admin)?;
     489              : 
     490            0 :     let node_id: NodeId = parse_request_param(&req, "node_id")?;
     491            0 :     let config_req = json_request::<NodeConfigureRequest>(&mut req).await?;
     492            0 :     if node_id != config_req.node_id {
     493            0 :         return Err(ApiError::BadRequest(anyhow::anyhow!(
     494            0 :             "Path and body node_id differ"
     495            0 :         )));
     496            0 :     }
     497            0 :     let state = get_state(&req);
     498            0 : 
     499            0 :     json_response(
     500            0 :         StatusCode::OK,
     501            0 :         state
     502            0 :             .service
     503            0 :             .node_configure(
     504            0 :                 config_req.node_id,
     505            0 :                 config_req.availability.map(NodeAvailability::from),
     506            0 :                 config_req.scheduling,
     507            0 :             )
     508            0 :             .await?,
     509              :     )
     510            0 : }
     511              : 
     512            0 : async fn handle_node_status(req: Request<Body>) -> Result<Response<Body>, ApiError> {
     513            0 :     check_permissions(&req, Scope::Admin)?;
     514              : 
     515            0 :     let state = get_state(&req);
     516            0 :     let node_id: NodeId = parse_request_param(&req, "node_id")?;
     517              : 
     518            0 :     let node_status = state.service.get_node(node_id).await?;
     519              : 
     520            0 :     json_response(StatusCode::OK, node_status)
     521            0 : }
     522              : 
     523            0 : async fn handle_node_drain(req: Request<Body>) -> Result<Response<Body>, ApiError> {
     524            0 :     check_permissions(&req, Scope::Admin)?;
     525              : 
     526            0 :     let state = get_state(&req);
     527            0 :     let node_id: NodeId = parse_request_param(&req, "node_id")?;
     528              : 
     529            0 :     state.service.start_node_drain(node_id).await?;
     530              : 
     531            0 :     json_response(StatusCode::ACCEPTED, ())
     532            0 : }
     533              : 
     534            0 : async fn handle_cancel_node_drain(req: Request<Body>) -> Result<Response<Body>, ApiError> {
     535            0 :     check_permissions(&req, Scope::Admin)?;
     536              : 
     537            0 :     let state = get_state(&req);
     538            0 :     let node_id: NodeId = parse_request_param(&req, "node_id")?;
     539              : 
     540            0 :     state.service.cancel_node_drain(node_id).await?;
     541              : 
     542            0 :     json_response(StatusCode::ACCEPTED, ())
     543            0 : }
     544              : 
     545            0 : async fn handle_node_fill(req: Request<Body>) -> Result<Response<Body>, ApiError> {
     546            0 :     check_permissions(&req, Scope::Admin)?;
     547              : 
     548            0 :     let state = get_state(&req);
     549            0 :     let node_id: NodeId = parse_request_param(&req, "node_id")?;
     550              : 
     551            0 :     state.service.start_node_fill(node_id).await?;
     552              : 
     553            0 :     json_response(StatusCode::ACCEPTED, ())
     554            0 : }
     555              : 
     556            0 : async fn handle_cancel_node_fill(req: Request<Body>) -> Result<Response<Body>, ApiError> {
     557            0 :     check_permissions(&req, Scope::Admin)?;
     558              : 
     559            0 :     let state = get_state(&req);
     560            0 :     let node_id: NodeId = parse_request_param(&req, "node_id")?;
     561              : 
     562            0 :     state.service.cancel_node_fill(node_id).await?;
     563              : 
     564            0 :     json_response(StatusCode::ACCEPTED, ())
     565            0 : }
     566              : 
     567            0 : async fn handle_metadata_health_update(mut req: Request<Body>) -> Result<Response<Body>, ApiError> {
     568            0 :     check_permissions(&req, Scope::Scrubber)?;
     569              : 
     570            0 :     let update_req = json_request::<MetadataHealthUpdateRequest>(&mut req).await?;
     571            0 :     let state = get_state(&req);
     572            0 : 
     573            0 :     state.service.metadata_health_update(update_req).await?;
     574              : 
     575            0 :     json_response(StatusCode::OK, MetadataHealthUpdateResponse {})
     576            0 : }
     577              : 
     578            0 : async fn handle_metadata_health_list_unhealthy(
     579            0 :     req: Request<Body>,
     580            0 : ) -> Result<Response<Body>, ApiError> {
     581            0 :     check_permissions(&req, Scope::Admin)?;
     582              : 
     583            0 :     let state = get_state(&req);
     584            0 :     let unhealthy_tenant_shards = state.service.metadata_health_list_unhealthy().await?;
     585              : 
     586            0 :     json_response(
     587            0 :         StatusCode::OK,
     588            0 :         MetadataHealthListUnhealthyResponse {
     589            0 :             unhealthy_tenant_shards,
     590            0 :         },
     591            0 :     )
     592            0 : }
     593              : 
     594            0 : async fn handle_metadata_health_list_outdated(
     595            0 :     mut req: Request<Body>,
     596            0 : ) -> Result<Response<Body>, ApiError> {
     597            0 :     check_permissions(&req, Scope::Admin)?;
     598              : 
     599            0 :     let list_outdated_req = json_request::<MetadataHealthListOutdatedRequest>(&mut req).await?;
     600            0 :     let state = get_state(&req);
     601            0 :     let health_records = state
     602            0 :         .service
     603            0 :         .metadata_health_list_outdated(list_outdated_req.not_scrubbed_for)
     604            0 :         .await?;
     605              : 
     606            0 :     json_response(
     607            0 :         StatusCode::OK,
     608            0 :         MetadataHealthListOutdatedResponse { health_records },
     609            0 :     )
     610            0 : }
     611              : 
     612            0 : async fn handle_tenant_shard_split(
     613            0 :     service: Arc<Service>,
     614            0 :     mut req: Request<Body>,
     615            0 : ) -> Result<Response<Body>, ApiError> {
     616            0 :     check_permissions(&req, Scope::Admin)?;
     617              : 
     618            0 :     let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
     619            0 :     let split_req = json_request::<TenantShardSplitRequest>(&mut req).await?;
     620              : 
     621              :     json_response(
     622              :         StatusCode::OK,
     623            0 :         service.tenant_shard_split(tenant_id, split_req).await?,
     624              :     )
     625            0 : }
     626              : 
     627            0 : async fn handle_tenant_shard_migrate(
     628            0 :     service: Arc<Service>,
     629            0 :     mut req: Request<Body>,
     630            0 : ) -> Result<Response<Body>, ApiError> {
     631            0 :     check_permissions(&req, Scope::Admin)?;
     632              : 
     633            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&req, "tenant_shard_id")?;
     634            0 :     let migrate_req = json_request::<TenantShardMigrateRequest>(&mut req).await?;
     635              :     json_response(
     636              :         StatusCode::OK,
     637            0 :         service
     638            0 :             .tenant_shard_migrate(tenant_shard_id, migrate_req)
     639            0 :             .await?,
     640              :     )
     641            0 : }
     642              : 
     643            0 : async fn handle_tenant_update_policy(mut req: Request<Body>) -> Result<Response<Body>, ApiError> {
     644            0 :     check_permissions(&req, Scope::Admin)?;
     645              : 
     646            0 :     let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
     647            0 :     let update_req = json_request::<TenantPolicyRequest>(&mut req).await?;
     648            0 :     let state = get_state(&req);
     649            0 : 
     650            0 :     json_response(
     651            0 :         StatusCode::OK,
     652            0 :         state
     653            0 :             .service
     654            0 :             .tenant_update_policy(tenant_id, update_req)
     655            0 :             .await?,
     656              :     )
     657            0 : }
     658              : 
     659            0 : async fn handle_step_down(req: Request<Body>) -> Result<Response<Body>, ApiError> {
     660            0 :     check_permissions(&req, Scope::Admin)?;
     661              : 
     662            0 :     let state = get_state(&req);
     663            0 :     json_response(StatusCode::OK, state.service.step_down().await)
     664            0 : }
     665              : 
     666            0 : async fn handle_tenant_drop(req: Request<Body>) -> Result<Response<Body>, ApiError> {
     667            0 :     let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
     668            0 :     check_permissions(&req, Scope::PageServerApi)?;
     669              : 
     670            0 :     let state = get_state(&req);
     671            0 : 
     672            0 :     json_response(StatusCode::OK, state.service.tenant_drop(tenant_id).await?)
     673            0 : }
     674              : 
     675            0 : async fn handle_tenant_import(req: Request<Body>) -> Result<Response<Body>, ApiError> {
     676            0 :     let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
     677            0 :     check_permissions(&req, Scope::PageServerApi)?;
     678              : 
     679            0 :     let state = get_state(&req);
     680            0 : 
     681            0 :     json_response(
     682            0 :         StatusCode::OK,
     683            0 :         state.service.tenant_import(tenant_id).await?,
     684              :     )
     685            0 : }
     686              : 
     687            0 : async fn handle_tenants_dump(req: Request<Body>) -> Result<Response<Body>, ApiError> {
     688            0 :     check_permissions(&req, Scope::Admin)?;
     689              : 
     690            0 :     let state = get_state(&req);
     691            0 :     state.service.tenants_dump()
     692            0 : }
     693              : 
     694            0 : async fn handle_scheduler_dump(req: Request<Body>) -> Result<Response<Body>, ApiError> {
     695            0 :     check_permissions(&req, Scope::Admin)?;
     696              : 
     697            0 :     let state = get_state(&req);
     698            0 :     state.service.scheduler_dump()
     699            0 : }
     700              : 
     701            0 : async fn handle_consistency_check(req: Request<Body>) -> Result<Response<Body>, ApiError> {
     702            0 :     check_permissions(&req, Scope::Admin)?;
     703              : 
     704            0 :     let state = get_state(&req);
     705            0 : 
     706            0 :     json_response(StatusCode::OK, state.service.consistency_check().await?)
     707            0 : }
     708              : 
     709            0 : async fn handle_reconcile_all(req: Request<Body>) -> Result<Response<Body>, ApiError> {
     710            0 :     check_permissions(&req, Scope::Admin)?;
     711              : 
     712            0 :     let state = get_state(&req);
     713            0 : 
     714            0 :     json_response(StatusCode::OK, state.service.reconcile_all_now().await?)
     715            0 : }
     716              : 
     717              : /// Status endpoint is just used for checking that our HTTP listener is up
     718            0 : async fn handle_status(_req: Request<Body>) -> Result<Response<Body>, ApiError> {
     719            0 :     json_response(StatusCode::OK, ())
     720            0 : }
     721              : 
     722              : /// Readiness endpoint indicates when we're done doing startup I/O (e.g. reconciling
     723              : /// with remote pageserver nodes).  This is intended for use as a kubernetes readiness probe.
     724            0 : async fn handle_ready(req: Request<Body>) -> Result<Response<Body>, ApiError> {
     725            0 :     let state = get_state(&req);
     726            0 :     if state.service.startup_complete.is_ready() {
     727            0 :         json_response(StatusCode::OK, ())
     728              :     } else {
     729            0 :         json_response(StatusCode::SERVICE_UNAVAILABLE, ())
     730              :     }
     731            0 : }
     732              : 
     733              : impl From<ReconcileError> for ApiError {
     734            0 :     fn from(value: ReconcileError) -> Self {
     735            0 :         ApiError::Conflict(format!("Reconciliation error: {}", value))
     736            0 :     }
     737              : }
     738              : 
     739              : /// Common wrapper for request handlers that call into Service and will operate on tenants: they must only
     740              : /// be allowed to run if Service has finished its initial reconciliation.
     741            0 : async fn tenant_service_handler<R, H>(
     742            0 :     request: Request<Body>,
     743            0 :     handler: H,
     744            0 :     request_name: RequestName,
     745            0 : ) -> R::Output
     746            0 : where
     747            0 :     R: std::future::Future<Output = Result<Response<Body>, ApiError>> + Send + 'static,
     748            0 :     H: FnOnce(Arc<Service>, Request<Body>) -> R + Send + Sync + 'static,
     749            0 : {
     750            0 :     let state = get_state(&request);
     751            0 :     let service = state.service.clone();
     752            0 : 
     753            0 :     let startup_complete = service.startup_complete.clone();
     754            0 :     if tokio::time::timeout(STARTUP_RECONCILE_TIMEOUT, startup_complete.wait())
     755            0 :         .await
     756            0 :         .is_err()
     757              :     {
     758              :         // This shouldn't happen: it is the responsibilty of [`Service::startup_reconcile`] to use appropriate
     759              :         // timeouts around its remote calls, to bound its runtime.
     760            0 :         return Err(ApiError::Timeout(
     761            0 :             "Timed out waiting for service readiness".into(),
     762            0 :         ));
     763            0 :     }
     764            0 : 
     765            0 :     named_request_span(
     766            0 :         request,
     767            0 :         |request| async move { handler(service, request).await },
     768            0 :         request_name,
     769            0 :     )
     770            0 :     .await
     771            0 : }
     772              : 
     773              : /// Check if the required scope is held in the request's token, or if the request has
     774              : /// a token with 'admin' scope then always permit it.
     775            0 : fn check_permissions(request: &Request<Body>, required_scope: Scope) -> Result<(), ApiError> {
     776            0 :     check_permission_with(request, |claims| {
     777            0 :         match crate::auth::check_permission(claims, required_scope) {
     778            0 :             Err(e) => match crate::auth::check_permission(claims, Scope::Admin) {
     779            0 :                 Ok(()) => Ok(()),
     780            0 :                 Err(_) => Err(e),
     781              :             },
     782            0 :             Ok(()) => Ok(()),
     783              :         }
     784            0 :     })
     785            0 : }
     786              : 
     787              : #[derive(Clone, Debug)]
     788              : struct RequestMeta {
     789              :     method: hyper::http::Method,
     790              :     at: Instant,
     791              : }
     792              : 
     793            0 : pub fn prologue_leadership_status_check_middleware<
     794            0 :     B: hyper::body::HttpBody + Send + Sync + 'static,
     795            0 : >() -> Middleware<B, ApiError> {
     796            0 :     Middleware::pre(move |req| async move {
     797            0 :         let state = get_state(&req);
     798            0 :         let leadership_status = state.service.get_leadership_status();
     799            0 : 
     800            0 :         enum AllowedRoutes<'a> {
     801            0 :             All,
     802            0 :             Some(Vec<&'a str>),
     803            0 :         }
     804            0 : 
     805            0 :         let allowed_routes = match leadership_status {
     806            0 :             LeadershipStatus::Leader => AllowedRoutes::All,
     807            0 :             LeadershipStatus::SteppedDown => {
     808            0 :                 // TODO: does it make sense to allow /status here?
     809            0 :                 AllowedRoutes::Some(["/control/v1/step_down", "/status", "/metrics"].to_vec())
     810            0 :             }
     811            0 :             LeadershipStatus::Candidate => {
     812            0 :                 AllowedRoutes::Some(["/ready", "/status", "/metrics"].to_vec())
     813            0 :             }
     814            0 :         };
     815            0 : 
     816            0 :         let uri = req.uri().to_string();
     817            0 :         match allowed_routes {
     818            0 :             AllowedRoutes::All => Ok(req),
     819            0 :             AllowedRoutes::Some(allowed) if allowed.contains(&uri.as_str()) => Ok(req),
     820            0 :             _ => {
     821            0 :                 tracing::info!(
     822            0 :                     "Request {} not allowed due to current leadership state",
     823            0 :                     req.uri()
     824            0 :                 );
     825            0 : 
     826            0 :                 Err(ApiError::ResourceUnavailable(
     827            0 :                     format!("Current leadership status is {leadership_status}").into(),
     828            0 :                 ))
     829            0 :             }
     830            0 :         }
     831            0 :     })
     832            0 : }
     833              : 
     834            0 : fn prologue_metrics_middleware<B: hyper::body::HttpBody + Send + Sync + 'static>(
     835            0 : ) -> Middleware<B, ApiError> {
     836            0 :     Middleware::pre(move |req| async move {
     837            0 :         let meta = RequestMeta {
     838            0 :             method: req.method().clone(),
     839            0 :             at: Instant::now(),
     840            0 :         };
     841            0 : 
     842            0 :         req.set_context(meta);
     843            0 : 
     844            0 :         Ok(req)
     845            0 :     })
     846            0 : }
     847              : 
     848            0 : fn epilogue_metrics_middleware<B: hyper::body::HttpBody + Send + Sync + 'static>(
     849            0 : ) -> Middleware<B, ApiError> {
     850            0 :     Middleware::post_with_info(move |resp, req_info| async move {
     851            0 :         let request_name = match req_info.context::<RequestName>() {
     852            0 :             Some(name) => name,
     853            0 :             None => {
     854            0 :                 return Ok(resp);
     855            0 :             }
     856            0 :         };
     857            0 : 
     858            0 :         if let Some(meta) = req_info.context::<RequestMeta>() {
     859            0 :             let status = &crate::metrics::METRICS_REGISTRY
     860            0 :                 .metrics_group
     861            0 :                 .storage_controller_http_request_status;
     862            0 :             let latency = &crate::metrics::METRICS_REGISTRY
     863            0 :                 .metrics_group
     864            0 :                 .storage_controller_http_request_latency;
     865            0 : 
     866            0 :             status.inc(HttpRequestStatusLabelGroup {
     867            0 :                 path: request_name.0,
     868            0 :                 method: meta.method.clone().into(),
     869            0 :                 status: crate::metrics::StatusCode(resp.status()),
     870            0 :             });
     871            0 : 
     872            0 :             latency.observe(
     873            0 :                 HttpRequestLatencyLabelGroup {
     874            0 :                     path: request_name.0,
     875            0 :                     method: meta.method.into(),
     876            0 :                 },
     877            0 :                 meta.at.elapsed().as_secs_f64(),
     878            0 :             );
     879            0 :         }
     880            0 :         Ok(resp)
     881            0 :     })
     882            0 : }
     883              : 
     884            0 : pub async fn measured_metrics_handler(req: Request<Body>) -> Result<Response<Body>, ApiError> {
     885            0 :     pub const TEXT_FORMAT: &str = "text/plain; version=0.0.4";
     886            0 : 
     887            0 :     let state = get_state(&req);
     888            0 :     let payload = crate::metrics::METRICS_REGISTRY.encode(&state.neon_metrics);
     889            0 :     let response = Response::builder()
     890            0 :         .status(200)
     891            0 :         .header(CONTENT_TYPE, TEXT_FORMAT)
     892            0 :         .body(payload.into())
     893            0 :         .unwrap();
     894            0 : 
     895            0 :     Ok(response)
     896            0 : }
     897              : 
     898              : #[derive(Clone)]
     899              : struct RequestName(&'static str);
     900              : 
     901            0 : async fn named_request_span<R, H>(
     902            0 :     request: Request<Body>,
     903            0 :     handler: H,
     904            0 :     name: RequestName,
     905            0 : ) -> R::Output
     906            0 : where
     907            0 :     R: Future<Output = Result<Response<Body>, ApiError>> + Send + 'static,
     908            0 :     H: FnOnce(Request<Body>) -> R + Send + Sync + 'static,
     909            0 : {
     910            0 :     request.set_context(name);
     911            0 :     request_span(request, handler).await
     912            0 : }
     913              : 
     914            0 : pub fn make_router(
     915            0 :     service: Arc<Service>,
     916            0 :     auth: Option<Arc<SwappableJwtAuth>>,
     917            0 :     build_info: BuildInfo,
     918            0 : ) -> RouterBuilder<hyper::Body, ApiError> {
     919            0 :     let mut router = endpoint::make_router()
     920            0 :         .middleware(prologue_leadership_status_check_middleware())
     921            0 :         .middleware(prologue_metrics_middleware())
     922            0 :         .middleware(epilogue_metrics_middleware());
     923            0 :     if auth.is_some() {
     924            0 :         router = router.middleware(auth_middleware(|request| {
     925            0 :             let state = get_state(request);
     926            0 :             if state.allowlist_routes.contains(request.uri()) {
     927            0 :                 None
     928              :             } else {
     929            0 :                 state.auth.as_deref()
     930              :             }
     931            0 :         }));
     932            0 :     }
     933              : 
     934            0 :     router
     935            0 :         .data(Arc::new(HttpState::new(service, auth, build_info)))
     936            0 :         .get("/metrics", |r| {
     937            0 :             named_request_span(r, measured_metrics_handler, RequestName("metrics"))
     938            0 :         })
     939            0 :         // Non-prefixed generic endpoints (status, metrics)
     940            0 :         .get("/status", |r| {
     941            0 :             named_request_span(r, handle_status, RequestName("status"))
     942            0 :         })
     943            0 :         .get("/ready", |r| {
     944            0 :             named_request_span(r, handle_ready, RequestName("ready"))
     945            0 :         })
     946            0 :         // Upcalls for the pageserver: point the pageserver's `control_plane_api` config to this prefix
     947            0 :         .post("/upcall/v1/re-attach", |r| {
     948            0 :             named_request_span(r, handle_re_attach, RequestName("upcall_v1_reattach"))
     949            0 :         })
     950            0 :         .post("/upcall/v1/validate", |r| {
     951            0 :             named_request_span(r, handle_validate, RequestName("upcall_v1_validate"))
     952            0 :         })
     953            0 :         // Test/dev/debug endpoints
     954            0 :         .post("/debug/v1/attach-hook", |r| {
     955            0 :             named_request_span(r, handle_attach_hook, RequestName("debug_v1_attach_hook"))
     956            0 :         })
     957            0 :         .post("/debug/v1/inspect", |r| {
     958            0 :             named_request_span(r, handle_inspect, RequestName("debug_v1_inspect"))
     959            0 :         })
     960            0 :         .post("/debug/v1/tenant/:tenant_id/drop", |r| {
     961            0 :             named_request_span(r, handle_tenant_drop, RequestName("debug_v1_tenant_drop"))
     962            0 :         })
     963            0 :         .post("/debug/v1/node/:node_id/drop", |r| {
     964            0 :             named_request_span(r, handle_node_drop, RequestName("debug_v1_node_drop"))
     965            0 :         })
     966            0 :         .post("/debug/v1/tenant/:tenant_id/import", |r| {
     967            0 :             named_request_span(
     968            0 :                 r,
     969            0 :                 handle_tenant_import,
     970            0 :                 RequestName("debug_v1_tenant_import"),
     971            0 :             )
     972            0 :         })
     973            0 :         .get("/debug/v1/tenant", |r| {
     974            0 :             named_request_span(r, handle_tenants_dump, RequestName("debug_v1_tenant"))
     975            0 :         })
     976            0 :         .get("/debug/v1/tenant/:tenant_id/locate", |r| {
     977            0 :             tenant_service_handler(
     978            0 :                 r,
     979            0 :                 handle_tenant_locate,
     980            0 :                 RequestName("debug_v1_tenant_locate"),
     981            0 :             )
     982            0 :         })
     983            0 :         .get("/debug/v1/scheduler", |r| {
     984            0 :             named_request_span(r, handle_scheduler_dump, RequestName("debug_v1_scheduler"))
     985            0 :         })
     986            0 :         .post("/debug/v1/consistency_check", |r| {
     987            0 :             named_request_span(
     988            0 :                 r,
     989            0 :                 handle_consistency_check,
     990            0 :                 RequestName("debug_v1_consistency_check"),
     991            0 :             )
     992            0 :         })
     993            0 :         .post("/debug/v1/reconcile_all", |r| {
     994            0 :             request_span(r, handle_reconcile_all)
     995            0 :         })
     996            0 :         .put("/debug/v1/failpoints", |r| {
     997            0 :             request_span(r, |r| failpoints_handler(r, CancellationToken::new()))
     998            0 :         })
     999            0 :         // Node operations
    1000            0 :         .post("/control/v1/node", |r| {
    1001            0 :             named_request_span(r, handle_node_register, RequestName("control_v1_node"))
    1002            0 :         })
    1003            0 :         .delete("/control/v1/node/:node_id", |r| {
    1004            0 :             named_request_span(r, handle_node_delete, RequestName("control_v1_node_delete"))
    1005            0 :         })
    1006            0 :         .get("/control/v1/node", |r| {
    1007            0 :             named_request_span(r, handle_node_list, RequestName("control_v1_node"))
    1008            0 :         })
    1009            0 :         .put("/control/v1/node/:node_id/config", |r| {
    1010            0 :             named_request_span(
    1011            0 :                 r,
    1012            0 :                 handle_node_configure,
    1013            0 :                 RequestName("control_v1_node_config"),
    1014            0 :             )
    1015            0 :         })
    1016            0 :         .get("/control/v1/node/:node_id", |r| {
    1017            0 :             named_request_span(r, handle_node_status, RequestName("control_v1_node_status"))
    1018            0 :         })
    1019            0 :         .put("/control/v1/node/:node_id/drain", |r| {
    1020            0 :             named_request_span(r, handle_node_drain, RequestName("control_v1_node_drain"))
    1021            0 :         })
    1022            0 :         .delete("/control/v1/node/:node_id/drain", |r| {
    1023            0 :             named_request_span(
    1024            0 :                 r,
    1025            0 :                 handle_cancel_node_drain,
    1026            0 :                 RequestName("control_v1_cancel_node_drain"),
    1027            0 :             )
    1028            0 :         })
    1029            0 :         .put("/control/v1/node/:node_id/fill", |r| {
    1030            0 :             named_request_span(r, handle_node_fill, RequestName("control_v1_node_fill"))
    1031            0 :         })
    1032            0 :         .delete("/control/v1/node/:node_id/fill", |r| {
    1033            0 :             named_request_span(
    1034            0 :                 r,
    1035            0 :                 handle_cancel_node_fill,
    1036            0 :                 RequestName("control_v1_cancel_node_fill"),
    1037            0 :             )
    1038            0 :         })
    1039            0 :         // Metadata health operations
    1040            0 :         .post("/control/v1/metadata_health/update", |r| {
    1041            0 :             named_request_span(
    1042            0 :                 r,
    1043            0 :                 handle_metadata_health_update,
    1044            0 :                 RequestName("control_v1_metadata_health_update"),
    1045            0 :             )
    1046            0 :         })
    1047            0 :         .get("/control/v1/metadata_health/unhealthy", |r| {
    1048            0 :             named_request_span(
    1049            0 :                 r,
    1050            0 :                 handle_metadata_health_list_unhealthy,
    1051            0 :                 RequestName("control_v1_metadata_health_list_unhealthy"),
    1052            0 :             )
    1053            0 :         })
    1054            0 :         .post("/control/v1/metadata_health/outdated", |r| {
    1055            0 :             named_request_span(
    1056            0 :                 r,
    1057            0 :                 handle_metadata_health_list_outdated,
    1058            0 :                 RequestName("control_v1_metadata_health_list_outdated"),
    1059            0 :             )
    1060            0 :         })
    1061            0 :         // TODO(vlad): endpoint for cancelling drain and fill
    1062            0 :         // Tenant Shard operations
    1063            0 :         .put("/control/v1/tenant/:tenant_shard_id/migrate", |r| {
    1064            0 :             tenant_service_handler(
    1065            0 :                 r,
    1066            0 :                 handle_tenant_shard_migrate,
    1067            0 :                 RequestName("control_v1_tenant_migrate"),
    1068            0 :             )
    1069            0 :         })
    1070            0 :         .put("/control/v1/tenant/:tenant_id/shard_split", |r| {
    1071            0 :             tenant_service_handler(
    1072            0 :                 r,
    1073            0 :                 handle_tenant_shard_split,
    1074            0 :                 RequestName("control_v1_tenant_shard_split"),
    1075            0 :             )
    1076            0 :         })
    1077            0 :         .get("/control/v1/tenant/:tenant_id", |r| {
    1078            0 :             tenant_service_handler(
    1079            0 :                 r,
    1080            0 :                 handle_tenant_describe,
    1081            0 :                 RequestName("control_v1_tenant_describe"),
    1082            0 :             )
    1083            0 :         })
    1084            0 :         .get("/control/v1/tenant", |r| {
    1085            0 :             tenant_service_handler(r, handle_tenant_list, RequestName("control_v1_tenant_list"))
    1086            0 :         })
    1087            0 :         .put("/control/v1/tenant/:tenant_id/policy", |r| {
    1088            0 :             named_request_span(
    1089            0 :                 r,
    1090            0 :                 handle_tenant_update_policy,
    1091            0 :                 RequestName("control_v1_tenant_policy"),
    1092            0 :             )
    1093            0 :         })
    1094            0 :         .put("/control/v1/step_down", |r| {
    1095            0 :             named_request_span(r, handle_step_down, RequestName("control_v1_step_down"))
    1096            0 :         })
    1097            0 :         // Tenant operations
    1098            0 :         // The ^/v1/ endpoints act as a "Virtual Pageserver", enabling shard-naive clients to call into
    1099            0 :         // this service to manage tenants that actually consist of many tenant shards, as if they are a single entity.
    1100            0 :         .post("/v1/tenant", |r| {
    1101            0 :             tenant_service_handler(r, handle_tenant_create, RequestName("v1_tenant"))
    1102            0 :         })
    1103            0 :         .delete("/v1/tenant/:tenant_id", |r| {
    1104            0 :             tenant_service_handler(r, handle_tenant_delete, RequestName("v1_tenant"))
    1105            0 :         })
    1106            0 :         .put("/v1/tenant/config", |r| {
    1107            0 :             tenant_service_handler(r, handle_tenant_config_set, RequestName("v1_tenant_config"))
    1108            0 :         })
    1109            0 :         .get("/v1/tenant/:tenant_id/config", |r| {
    1110            0 :             tenant_service_handler(r, handle_tenant_config_get, RequestName("v1_tenant_config"))
    1111            0 :         })
    1112            0 :         .put("/v1/tenant/:tenant_shard_id/location_config", |r| {
    1113            0 :             tenant_service_handler(
    1114            0 :                 r,
    1115            0 :                 handle_tenant_location_config,
    1116            0 :                 RequestName("v1_tenant_location_config"),
    1117            0 :             )
    1118            0 :         })
    1119            0 :         .put("/v1/tenant/:tenant_id/time_travel_remote_storage", |r| {
    1120            0 :             tenant_service_handler(
    1121            0 :                 r,
    1122            0 :                 handle_tenant_time_travel_remote_storage,
    1123            0 :                 RequestName("v1_tenant_time_travel_remote_storage"),
    1124            0 :             )
    1125            0 :         })
    1126            0 :         .post("/v1/tenant/:tenant_id/secondary/download", |r| {
    1127            0 :             tenant_service_handler(
    1128            0 :                 r,
    1129            0 :                 handle_tenant_secondary_download,
    1130            0 :                 RequestName("v1_tenant_secondary_download"),
    1131            0 :             )
    1132            0 :         })
    1133            0 :         // Timeline operations
    1134            0 :         .delete("/v1/tenant/:tenant_id/timeline/:timeline_id", |r| {
    1135            0 :             tenant_service_handler(
    1136            0 :                 r,
    1137            0 :                 handle_tenant_timeline_delete,
    1138            0 :                 RequestName("v1_tenant_timeline"),
    1139            0 :             )
    1140            0 :         })
    1141            0 :         .post("/v1/tenant/:tenant_id/timeline", |r| {
    1142            0 :             tenant_service_handler(
    1143            0 :                 r,
    1144            0 :                 handle_tenant_timeline_create,
    1145            0 :                 RequestName("v1_tenant_timeline"),
    1146            0 :             )
    1147            0 :         })
    1148            0 :         .put(
    1149            0 :             "/v1/tenant/:tenant_id/timeline/:timeline_id/detach_ancestor",
    1150            0 :             |r| {
    1151            0 :                 tenant_service_handler(
    1152            0 :                     r,
    1153            0 :                     handle_tenant_timeline_detach_ancestor,
    1154            0 :                     RequestName("v1_tenant_timeline_detach_ancestor"),
    1155            0 :                 )
    1156            0 :             },
    1157            0 :         )
    1158            0 :         // Tenant detail GET passthrough to shard zero:
    1159            0 :         .get("/v1/tenant/:tenant_id", |r| {
    1160            0 :             tenant_service_handler(
    1161            0 :                 r,
    1162            0 :                 handle_tenant_timeline_passthrough,
    1163            0 :                 RequestName("v1_tenant_passthrough"),
    1164            0 :             )
    1165            0 :         })
    1166            0 :         // The `*` in the  URL is a wildcard: any tenant/timeline GET APIs on the pageserver
    1167            0 :         // are implicitly exposed here.  This must be last in the list to avoid
    1168            0 :         // taking precedence over other GET methods we might implement by hand.
    1169            0 :         .get("/v1/tenant/:tenant_id/*", |r| {
    1170            0 :             tenant_service_handler(
    1171            0 :                 r,
    1172            0 :                 handle_tenant_timeline_passthrough,
    1173            0 :                 RequestName("v1_tenant_passthrough"),
    1174            0 :             )
    1175            0 :         })
    1176            0 : }
        

Generated by: LCOV version 2.1-beta