LCOV - code coverage report
Current view: top level - storage_controller/src - http.rs (source / functions) Coverage Total Hit
Test: ccf45ed1c149555259baec52d6229a81013dcd6a.info Lines: 0.0 % 919 0
Test Date: 2024-08-21 17:32:46 Functions: 0.0 % 319 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 :             .external_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_get_leader(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 leader = state.service.get_leader().await.map_err(|err| {
     528            0 :         ApiError::InternalServerError(anyhow::anyhow!(
     529            0 :             "Failed to read leader from database: {err}"
     530            0 :         ))
     531            0 :     })?;
     532              : 
     533            0 :     json_response(StatusCode::OK, leader)
     534            0 : }
     535              : 
     536            0 : async fn handle_node_drain(req: Request<Body>) -> Result<Response<Body>, ApiError> {
     537            0 :     check_permissions(&req, Scope::Admin)?;
     538              : 
     539            0 :     let state = get_state(&req);
     540            0 :     let node_id: NodeId = parse_request_param(&req, "node_id")?;
     541              : 
     542            0 :     state.service.start_node_drain(node_id).await?;
     543              : 
     544            0 :     json_response(StatusCode::ACCEPTED, ())
     545            0 : }
     546              : 
     547            0 : async fn handle_cancel_node_drain(req: Request<Body>) -> Result<Response<Body>, ApiError> {
     548            0 :     check_permissions(&req, Scope::Admin)?;
     549              : 
     550            0 :     let state = get_state(&req);
     551            0 :     let node_id: NodeId = parse_request_param(&req, "node_id")?;
     552              : 
     553            0 :     state.service.cancel_node_drain(node_id).await?;
     554              : 
     555            0 :     json_response(StatusCode::ACCEPTED, ())
     556            0 : }
     557              : 
     558            0 : async fn handle_node_fill(req: Request<Body>) -> Result<Response<Body>, ApiError> {
     559            0 :     check_permissions(&req, Scope::Admin)?;
     560              : 
     561            0 :     let state = get_state(&req);
     562            0 :     let node_id: NodeId = parse_request_param(&req, "node_id")?;
     563              : 
     564            0 :     state.service.start_node_fill(node_id).await?;
     565              : 
     566            0 :     json_response(StatusCode::ACCEPTED, ())
     567            0 : }
     568              : 
     569            0 : async fn handle_cancel_node_fill(req: Request<Body>) -> Result<Response<Body>, ApiError> {
     570            0 :     check_permissions(&req, Scope::Admin)?;
     571              : 
     572            0 :     let state = get_state(&req);
     573            0 :     let node_id: NodeId = parse_request_param(&req, "node_id")?;
     574              : 
     575            0 :     state.service.cancel_node_fill(node_id).await?;
     576              : 
     577            0 :     json_response(StatusCode::ACCEPTED, ())
     578            0 : }
     579              : 
     580            0 : async fn handle_metadata_health_update(mut req: Request<Body>) -> Result<Response<Body>, ApiError> {
     581            0 :     check_permissions(&req, Scope::Scrubber)?;
     582              : 
     583            0 :     let update_req = json_request::<MetadataHealthUpdateRequest>(&mut req).await?;
     584            0 :     let state = get_state(&req);
     585            0 : 
     586            0 :     state.service.metadata_health_update(update_req).await?;
     587              : 
     588            0 :     json_response(StatusCode::OK, MetadataHealthUpdateResponse {})
     589            0 : }
     590              : 
     591            0 : async fn handle_metadata_health_list_unhealthy(
     592            0 :     req: Request<Body>,
     593            0 : ) -> Result<Response<Body>, ApiError> {
     594            0 :     check_permissions(&req, Scope::Admin)?;
     595              : 
     596            0 :     let state = get_state(&req);
     597            0 :     let unhealthy_tenant_shards = state.service.metadata_health_list_unhealthy().await?;
     598              : 
     599            0 :     json_response(
     600            0 :         StatusCode::OK,
     601            0 :         MetadataHealthListUnhealthyResponse {
     602            0 :             unhealthy_tenant_shards,
     603            0 :         },
     604            0 :     )
     605            0 : }
     606              : 
     607            0 : async fn handle_metadata_health_list_outdated(
     608            0 :     mut req: Request<Body>,
     609            0 : ) -> Result<Response<Body>, ApiError> {
     610            0 :     check_permissions(&req, Scope::Admin)?;
     611              : 
     612            0 :     let list_outdated_req = json_request::<MetadataHealthListOutdatedRequest>(&mut req).await?;
     613            0 :     let state = get_state(&req);
     614            0 :     let health_records = state
     615            0 :         .service
     616            0 :         .metadata_health_list_outdated(list_outdated_req.not_scrubbed_for)
     617            0 :         .await?;
     618              : 
     619            0 :     json_response(
     620            0 :         StatusCode::OK,
     621            0 :         MetadataHealthListOutdatedResponse { health_records },
     622            0 :     )
     623            0 : }
     624              : 
     625            0 : async fn handle_tenant_shard_split(
     626            0 :     service: Arc<Service>,
     627            0 :     mut req: Request<Body>,
     628            0 : ) -> Result<Response<Body>, ApiError> {
     629            0 :     check_permissions(&req, Scope::Admin)?;
     630              : 
     631            0 :     let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
     632            0 :     let split_req = json_request::<TenantShardSplitRequest>(&mut req).await?;
     633              : 
     634              :     json_response(
     635              :         StatusCode::OK,
     636            0 :         service.tenant_shard_split(tenant_id, split_req).await?,
     637              :     )
     638            0 : }
     639              : 
     640            0 : async fn handle_tenant_shard_migrate(
     641            0 :     service: Arc<Service>,
     642            0 :     mut req: Request<Body>,
     643            0 : ) -> Result<Response<Body>, ApiError> {
     644            0 :     check_permissions(&req, Scope::Admin)?;
     645              : 
     646            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&req, "tenant_shard_id")?;
     647            0 :     let migrate_req = json_request::<TenantShardMigrateRequest>(&mut req).await?;
     648              :     json_response(
     649              :         StatusCode::OK,
     650            0 :         service
     651            0 :             .tenant_shard_migrate(tenant_shard_id, migrate_req)
     652            0 :             .await?,
     653              :     )
     654            0 : }
     655              : 
     656            0 : async fn handle_tenant_update_policy(mut req: Request<Body>) -> Result<Response<Body>, ApiError> {
     657            0 :     check_permissions(&req, Scope::Admin)?;
     658              : 
     659            0 :     let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
     660            0 :     let update_req = json_request::<TenantPolicyRequest>(&mut req).await?;
     661            0 :     let state = get_state(&req);
     662            0 : 
     663            0 :     json_response(
     664            0 :         StatusCode::OK,
     665            0 :         state
     666            0 :             .service
     667            0 :             .tenant_update_policy(tenant_id, update_req)
     668            0 :             .await?,
     669              :     )
     670            0 : }
     671              : 
     672            0 : async fn handle_step_down(req: Request<Body>) -> Result<Response<Body>, ApiError> {
     673            0 :     check_permissions(&req, Scope::Admin)?;
     674              : 
     675            0 :     let state = get_state(&req);
     676            0 :     json_response(StatusCode::OK, state.service.step_down().await)
     677            0 : }
     678              : 
     679            0 : async fn handle_tenant_drop(req: Request<Body>) -> Result<Response<Body>, ApiError> {
     680            0 :     let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
     681            0 :     check_permissions(&req, Scope::PageServerApi)?;
     682              : 
     683            0 :     let state = get_state(&req);
     684            0 : 
     685            0 :     json_response(StatusCode::OK, state.service.tenant_drop(tenant_id).await?)
     686            0 : }
     687              : 
     688            0 : async fn handle_tenant_import(req: Request<Body>) -> Result<Response<Body>, ApiError> {
     689            0 :     let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
     690            0 :     check_permissions(&req, Scope::PageServerApi)?;
     691              : 
     692            0 :     let state = get_state(&req);
     693            0 : 
     694            0 :     json_response(
     695            0 :         StatusCode::OK,
     696            0 :         state.service.tenant_import(tenant_id).await?,
     697              :     )
     698            0 : }
     699              : 
     700            0 : async fn handle_tenants_dump(req: Request<Body>) -> Result<Response<Body>, ApiError> {
     701            0 :     check_permissions(&req, Scope::Admin)?;
     702              : 
     703            0 :     let state = get_state(&req);
     704            0 :     state.service.tenants_dump()
     705            0 : }
     706              : 
     707            0 : async fn handle_scheduler_dump(req: Request<Body>) -> Result<Response<Body>, ApiError> {
     708            0 :     check_permissions(&req, Scope::Admin)?;
     709              : 
     710            0 :     let state = get_state(&req);
     711            0 :     state.service.scheduler_dump()
     712            0 : }
     713              : 
     714            0 : async fn handle_consistency_check(req: Request<Body>) -> Result<Response<Body>, ApiError> {
     715            0 :     check_permissions(&req, Scope::Admin)?;
     716              : 
     717            0 :     let state = get_state(&req);
     718            0 : 
     719            0 :     json_response(StatusCode::OK, state.service.consistency_check().await?)
     720            0 : }
     721              : 
     722            0 : async fn handle_reconcile_all(req: Request<Body>) -> Result<Response<Body>, ApiError> {
     723            0 :     check_permissions(&req, Scope::Admin)?;
     724              : 
     725            0 :     let state = get_state(&req);
     726            0 : 
     727            0 :     json_response(StatusCode::OK, state.service.reconcile_all_now().await?)
     728            0 : }
     729              : 
     730              : /// Status endpoint is just used for checking that our HTTP listener is up
     731            0 : async fn handle_status(_req: Request<Body>) -> Result<Response<Body>, ApiError> {
     732            0 :     json_response(StatusCode::OK, ())
     733            0 : }
     734              : 
     735              : /// Readiness endpoint indicates when we're done doing startup I/O (e.g. reconciling
     736              : /// with remote pageserver nodes).  This is intended for use as a kubernetes readiness probe.
     737            0 : async fn handle_ready(req: Request<Body>) -> Result<Response<Body>, ApiError> {
     738            0 :     let state = get_state(&req);
     739            0 :     if state.service.startup_complete.is_ready() {
     740            0 :         json_response(StatusCode::OK, ())
     741              :     } else {
     742            0 :         json_response(StatusCode::SERVICE_UNAVAILABLE, ())
     743              :     }
     744            0 : }
     745              : 
     746              : impl From<ReconcileError> for ApiError {
     747            0 :     fn from(value: ReconcileError) -> Self {
     748            0 :         ApiError::Conflict(format!("Reconciliation error: {}", value))
     749            0 :     }
     750              : }
     751              : 
     752              : /// Common wrapper for request handlers that call into Service and will operate on tenants: they must only
     753              : /// be allowed to run if Service has finished its initial reconciliation.
     754            0 : async fn tenant_service_handler<R, H>(
     755            0 :     request: Request<Body>,
     756            0 :     handler: H,
     757            0 :     request_name: RequestName,
     758            0 : ) -> R::Output
     759            0 : where
     760            0 :     R: std::future::Future<Output = Result<Response<Body>, ApiError>> + Send + 'static,
     761            0 :     H: FnOnce(Arc<Service>, Request<Body>) -> R + Send + Sync + 'static,
     762            0 : {
     763            0 :     let state = get_state(&request);
     764            0 :     let service = state.service.clone();
     765            0 : 
     766            0 :     let startup_complete = service.startup_complete.clone();
     767            0 :     if tokio::time::timeout(STARTUP_RECONCILE_TIMEOUT, startup_complete.wait())
     768            0 :         .await
     769            0 :         .is_err()
     770              :     {
     771              :         // This shouldn't happen: it is the responsibilty of [`Service::startup_reconcile`] to use appropriate
     772              :         // timeouts around its remote calls, to bound its runtime.
     773            0 :         return Err(ApiError::Timeout(
     774            0 :             "Timed out waiting for service readiness".into(),
     775            0 :         ));
     776            0 :     }
     777            0 : 
     778            0 :     named_request_span(
     779            0 :         request,
     780            0 :         |request| async move { handler(service, request).await },
     781            0 :         request_name,
     782            0 :     )
     783            0 :     .await
     784            0 : }
     785              : 
     786              : /// Check if the required scope is held in the request's token, or if the request has
     787              : /// a token with 'admin' scope then always permit it.
     788            0 : fn check_permissions(request: &Request<Body>, required_scope: Scope) -> Result<(), ApiError> {
     789            0 :     check_permission_with(request, |claims| {
     790            0 :         match crate::auth::check_permission(claims, required_scope) {
     791            0 :             Err(e) => match crate::auth::check_permission(claims, Scope::Admin) {
     792            0 :                 Ok(()) => Ok(()),
     793            0 :                 Err(_) => Err(e),
     794              :             },
     795            0 :             Ok(()) => Ok(()),
     796              :         }
     797            0 :     })
     798            0 : }
     799              : 
     800              : #[derive(Clone, Debug)]
     801              : struct RequestMeta {
     802              :     method: hyper::http::Method,
     803              :     at: Instant,
     804              : }
     805              : 
     806            0 : pub fn prologue_leadership_status_check_middleware<
     807            0 :     B: hyper::body::HttpBody + Send + Sync + 'static,
     808            0 : >() -> Middleware<B, ApiError> {
     809            0 :     Middleware::pre(move |req| async move {
     810            0 :         let state = get_state(&req);
     811            0 :         let leadership_status = state.service.get_leadership_status();
     812            0 : 
     813            0 :         enum AllowedRoutes<'a> {
     814            0 :             All,
     815            0 :             Some(Vec<&'a str>),
     816            0 :         }
     817            0 : 
     818            0 :         let allowed_routes = match leadership_status {
     819            0 :             LeadershipStatus::Leader => AllowedRoutes::All,
     820            0 :             LeadershipStatus::SteppedDown => {
     821            0 :                 // TODO: does it make sense to allow /status here?
     822            0 :                 AllowedRoutes::Some(["/control/v1/step_down", "/status", "/metrics"].to_vec())
     823            0 :             }
     824            0 :             LeadershipStatus::Candidate => {
     825            0 :                 AllowedRoutes::Some(["/ready", "/status", "/metrics"].to_vec())
     826            0 :             }
     827            0 :         };
     828            0 : 
     829            0 :         let uri = req.uri().to_string();
     830            0 :         match allowed_routes {
     831            0 :             AllowedRoutes::All => Ok(req),
     832            0 :             AllowedRoutes::Some(allowed) if allowed.contains(&uri.as_str()) => Ok(req),
     833            0 :             _ => {
     834            0 :                 tracing::info!(
     835            0 :                     "Request {} not allowed due to current leadership state",
     836            0 :                     req.uri()
     837            0 :                 );
     838            0 : 
     839            0 :                 Err(ApiError::ResourceUnavailable(
     840            0 :                     format!("Current leadership status is {leadership_status}").into(),
     841            0 :                 ))
     842            0 :             }
     843            0 :         }
     844            0 :     })
     845            0 : }
     846              : 
     847            0 : fn prologue_metrics_middleware<B: hyper::body::HttpBody + Send + Sync + 'static>(
     848            0 : ) -> Middleware<B, ApiError> {
     849            0 :     Middleware::pre(move |req| async move {
     850            0 :         let meta = RequestMeta {
     851            0 :             method: req.method().clone(),
     852            0 :             at: Instant::now(),
     853            0 :         };
     854            0 : 
     855            0 :         req.set_context(meta);
     856            0 : 
     857            0 :         Ok(req)
     858            0 :     })
     859            0 : }
     860              : 
     861            0 : fn epilogue_metrics_middleware<B: hyper::body::HttpBody + Send + Sync + 'static>(
     862            0 : ) -> Middleware<B, ApiError> {
     863            0 :     Middleware::post_with_info(move |resp, req_info| async move {
     864            0 :         let request_name = match req_info.context::<RequestName>() {
     865            0 :             Some(name) => name,
     866            0 :             None => {
     867            0 :                 return Ok(resp);
     868            0 :             }
     869            0 :         };
     870            0 : 
     871            0 :         if let Some(meta) = req_info.context::<RequestMeta>() {
     872            0 :             let status = &crate::metrics::METRICS_REGISTRY
     873            0 :                 .metrics_group
     874            0 :                 .storage_controller_http_request_status;
     875            0 :             let latency = &crate::metrics::METRICS_REGISTRY
     876            0 :                 .metrics_group
     877            0 :                 .storage_controller_http_request_latency;
     878            0 : 
     879            0 :             status.inc(HttpRequestStatusLabelGroup {
     880            0 :                 path: request_name.0,
     881            0 :                 method: meta.method.clone().into(),
     882            0 :                 status: crate::metrics::StatusCode(resp.status()),
     883            0 :             });
     884            0 : 
     885            0 :             latency.observe(
     886            0 :                 HttpRequestLatencyLabelGroup {
     887            0 :                     path: request_name.0,
     888            0 :                     method: meta.method.into(),
     889            0 :                 },
     890            0 :                 meta.at.elapsed().as_secs_f64(),
     891            0 :             );
     892            0 :         }
     893            0 :         Ok(resp)
     894            0 :     })
     895            0 : }
     896              : 
     897            0 : pub async fn measured_metrics_handler(req: Request<Body>) -> Result<Response<Body>, ApiError> {
     898            0 :     pub const TEXT_FORMAT: &str = "text/plain; version=0.0.4";
     899            0 : 
     900            0 :     let state = get_state(&req);
     901            0 :     let payload = crate::metrics::METRICS_REGISTRY.encode(&state.neon_metrics);
     902            0 :     let response = Response::builder()
     903            0 :         .status(200)
     904            0 :         .header(CONTENT_TYPE, TEXT_FORMAT)
     905            0 :         .body(payload.into())
     906            0 :         .unwrap();
     907            0 : 
     908            0 :     Ok(response)
     909            0 : }
     910              : 
     911              : #[derive(Clone)]
     912              : struct RequestName(&'static str);
     913              : 
     914            0 : async fn named_request_span<R, H>(
     915            0 :     request: Request<Body>,
     916            0 :     handler: H,
     917            0 :     name: RequestName,
     918            0 : ) -> R::Output
     919            0 : where
     920            0 :     R: Future<Output = Result<Response<Body>, ApiError>> + Send + 'static,
     921            0 :     H: FnOnce(Request<Body>) -> R + Send + Sync + 'static,
     922            0 : {
     923            0 :     request.set_context(name);
     924            0 :     request_span(request, handler).await
     925            0 : }
     926              : 
     927            0 : pub fn make_router(
     928            0 :     service: Arc<Service>,
     929            0 :     auth: Option<Arc<SwappableJwtAuth>>,
     930            0 :     build_info: BuildInfo,
     931            0 : ) -> RouterBuilder<hyper::Body, ApiError> {
     932            0 :     let mut router = endpoint::make_router()
     933            0 :         .middleware(prologue_leadership_status_check_middleware())
     934            0 :         .middleware(prologue_metrics_middleware())
     935            0 :         .middleware(epilogue_metrics_middleware());
     936            0 :     if auth.is_some() {
     937            0 :         router = router.middleware(auth_middleware(|request| {
     938            0 :             let state = get_state(request);
     939            0 :             if state.allowlist_routes.contains(request.uri()) {
     940            0 :                 None
     941              :             } else {
     942            0 :                 state.auth.as_deref()
     943              :             }
     944            0 :         }));
     945            0 :     }
     946              : 
     947            0 :     router
     948            0 :         .data(Arc::new(HttpState::new(service, auth, build_info)))
     949            0 :         .get("/metrics", |r| {
     950            0 :             named_request_span(r, measured_metrics_handler, RequestName("metrics"))
     951            0 :         })
     952            0 :         // Non-prefixed generic endpoints (status, metrics)
     953            0 :         .get("/status", |r| {
     954            0 :             named_request_span(r, handle_status, RequestName("status"))
     955            0 :         })
     956            0 :         .get("/ready", |r| {
     957            0 :             named_request_span(r, handle_ready, RequestName("ready"))
     958            0 :         })
     959            0 :         // Upcalls for the pageserver: point the pageserver's `control_plane_api` config to this prefix
     960            0 :         .post("/upcall/v1/re-attach", |r| {
     961            0 :             named_request_span(r, handle_re_attach, RequestName("upcall_v1_reattach"))
     962            0 :         })
     963            0 :         .post("/upcall/v1/validate", |r| {
     964            0 :             named_request_span(r, handle_validate, RequestName("upcall_v1_validate"))
     965            0 :         })
     966            0 :         // Test/dev/debug endpoints
     967            0 :         .post("/debug/v1/attach-hook", |r| {
     968            0 :             named_request_span(r, handle_attach_hook, RequestName("debug_v1_attach_hook"))
     969            0 :         })
     970            0 :         .post("/debug/v1/inspect", |r| {
     971            0 :             named_request_span(r, handle_inspect, RequestName("debug_v1_inspect"))
     972            0 :         })
     973            0 :         .post("/debug/v1/tenant/:tenant_id/drop", |r| {
     974            0 :             named_request_span(r, handle_tenant_drop, RequestName("debug_v1_tenant_drop"))
     975            0 :         })
     976            0 :         .post("/debug/v1/node/:node_id/drop", |r| {
     977            0 :             named_request_span(r, handle_node_drop, RequestName("debug_v1_node_drop"))
     978            0 :         })
     979            0 :         .post("/debug/v1/tenant/:tenant_id/import", |r| {
     980            0 :             named_request_span(
     981            0 :                 r,
     982            0 :                 handle_tenant_import,
     983            0 :                 RequestName("debug_v1_tenant_import"),
     984            0 :             )
     985            0 :         })
     986            0 :         .get("/debug/v1/tenant", |r| {
     987            0 :             named_request_span(r, handle_tenants_dump, RequestName("debug_v1_tenant"))
     988            0 :         })
     989            0 :         .get("/debug/v1/tenant/:tenant_id/locate", |r| {
     990            0 :             tenant_service_handler(
     991            0 :                 r,
     992            0 :                 handle_tenant_locate,
     993            0 :                 RequestName("debug_v1_tenant_locate"),
     994            0 :             )
     995            0 :         })
     996            0 :         .get("/debug/v1/scheduler", |r| {
     997            0 :             named_request_span(r, handle_scheduler_dump, RequestName("debug_v1_scheduler"))
     998            0 :         })
     999            0 :         .post("/debug/v1/consistency_check", |r| {
    1000            0 :             named_request_span(
    1001            0 :                 r,
    1002            0 :                 handle_consistency_check,
    1003            0 :                 RequestName("debug_v1_consistency_check"),
    1004            0 :             )
    1005            0 :         })
    1006            0 :         .post("/debug/v1/reconcile_all", |r| {
    1007            0 :             request_span(r, handle_reconcile_all)
    1008            0 :         })
    1009            0 :         .put("/debug/v1/failpoints", |r| {
    1010            0 :             request_span(r, |r| failpoints_handler(r, CancellationToken::new()))
    1011            0 :         })
    1012            0 :         // Node operations
    1013            0 :         .post("/control/v1/node", |r| {
    1014            0 :             named_request_span(r, handle_node_register, RequestName("control_v1_node"))
    1015            0 :         })
    1016            0 :         .delete("/control/v1/node/:node_id", |r| {
    1017            0 :             named_request_span(r, handle_node_delete, RequestName("control_v1_node_delete"))
    1018            0 :         })
    1019            0 :         .get("/control/v1/node", |r| {
    1020            0 :             named_request_span(r, handle_node_list, RequestName("control_v1_node"))
    1021            0 :         })
    1022            0 :         .put("/control/v1/node/:node_id/config", |r| {
    1023            0 :             named_request_span(
    1024            0 :                 r,
    1025            0 :                 handle_node_configure,
    1026            0 :                 RequestName("control_v1_node_config"),
    1027            0 :             )
    1028            0 :         })
    1029            0 :         .get("/control/v1/node/:node_id", |r| {
    1030            0 :             named_request_span(r, handle_node_status, RequestName("control_v1_node_status"))
    1031            0 :         })
    1032            0 :         .get("/control/v1/leader", |r| {
    1033            0 :             named_request_span(r, handle_get_leader, RequestName("control_v1_get_leader"))
    1034            0 :         })
    1035            0 :         .put("/control/v1/node/:node_id/drain", |r| {
    1036            0 :             named_request_span(r, handle_node_drain, RequestName("control_v1_node_drain"))
    1037            0 :         })
    1038            0 :         .delete("/control/v1/node/:node_id/drain", |r| {
    1039            0 :             named_request_span(
    1040            0 :                 r,
    1041            0 :                 handle_cancel_node_drain,
    1042            0 :                 RequestName("control_v1_cancel_node_drain"),
    1043            0 :             )
    1044            0 :         })
    1045            0 :         .put("/control/v1/node/:node_id/fill", |r| {
    1046            0 :             named_request_span(r, handle_node_fill, RequestName("control_v1_node_fill"))
    1047            0 :         })
    1048            0 :         .delete("/control/v1/node/:node_id/fill", |r| {
    1049            0 :             named_request_span(
    1050            0 :                 r,
    1051            0 :                 handle_cancel_node_fill,
    1052            0 :                 RequestName("control_v1_cancel_node_fill"),
    1053            0 :             )
    1054            0 :         })
    1055            0 :         // Metadata health operations
    1056            0 :         .post("/control/v1/metadata_health/update", |r| {
    1057            0 :             named_request_span(
    1058            0 :                 r,
    1059            0 :                 handle_metadata_health_update,
    1060            0 :                 RequestName("control_v1_metadata_health_update"),
    1061            0 :             )
    1062            0 :         })
    1063            0 :         .get("/control/v1/metadata_health/unhealthy", |r| {
    1064            0 :             named_request_span(
    1065            0 :                 r,
    1066            0 :                 handle_metadata_health_list_unhealthy,
    1067            0 :                 RequestName("control_v1_metadata_health_list_unhealthy"),
    1068            0 :             )
    1069            0 :         })
    1070            0 :         .post("/control/v1/metadata_health/outdated", |r| {
    1071            0 :             named_request_span(
    1072            0 :                 r,
    1073            0 :                 handle_metadata_health_list_outdated,
    1074            0 :                 RequestName("control_v1_metadata_health_list_outdated"),
    1075            0 :             )
    1076            0 :         })
    1077            0 :         // TODO(vlad): endpoint for cancelling drain and fill
    1078            0 :         // Tenant Shard operations
    1079            0 :         .put("/control/v1/tenant/:tenant_shard_id/migrate", |r| {
    1080            0 :             tenant_service_handler(
    1081            0 :                 r,
    1082            0 :                 handle_tenant_shard_migrate,
    1083            0 :                 RequestName("control_v1_tenant_migrate"),
    1084            0 :             )
    1085            0 :         })
    1086            0 :         .put("/control/v1/tenant/:tenant_id/shard_split", |r| {
    1087            0 :             tenant_service_handler(
    1088            0 :                 r,
    1089            0 :                 handle_tenant_shard_split,
    1090            0 :                 RequestName("control_v1_tenant_shard_split"),
    1091            0 :             )
    1092            0 :         })
    1093            0 :         .get("/control/v1/tenant/:tenant_id", |r| {
    1094            0 :             tenant_service_handler(
    1095            0 :                 r,
    1096            0 :                 handle_tenant_describe,
    1097            0 :                 RequestName("control_v1_tenant_describe"),
    1098            0 :             )
    1099            0 :         })
    1100            0 :         .get("/control/v1/tenant", |r| {
    1101            0 :             tenant_service_handler(r, handle_tenant_list, RequestName("control_v1_tenant_list"))
    1102            0 :         })
    1103            0 :         .put("/control/v1/tenant/:tenant_id/policy", |r| {
    1104            0 :             named_request_span(
    1105            0 :                 r,
    1106            0 :                 handle_tenant_update_policy,
    1107            0 :                 RequestName("control_v1_tenant_policy"),
    1108            0 :             )
    1109            0 :         })
    1110            0 :         .put("/control/v1/step_down", |r| {
    1111            0 :             named_request_span(r, handle_step_down, RequestName("control_v1_step_down"))
    1112            0 :         })
    1113            0 :         // Tenant operations
    1114            0 :         // The ^/v1/ endpoints act as a "Virtual Pageserver", enabling shard-naive clients to call into
    1115            0 :         // this service to manage tenants that actually consist of many tenant shards, as if they are a single entity.
    1116            0 :         .post("/v1/tenant", |r| {
    1117            0 :             tenant_service_handler(r, handle_tenant_create, RequestName("v1_tenant"))
    1118            0 :         })
    1119            0 :         .delete("/v1/tenant/:tenant_id", |r| {
    1120            0 :             tenant_service_handler(r, handle_tenant_delete, RequestName("v1_tenant"))
    1121            0 :         })
    1122            0 :         .put("/v1/tenant/config", |r| {
    1123            0 :             tenant_service_handler(r, handle_tenant_config_set, RequestName("v1_tenant_config"))
    1124            0 :         })
    1125            0 :         .get("/v1/tenant/:tenant_id/config", |r| {
    1126            0 :             tenant_service_handler(r, handle_tenant_config_get, RequestName("v1_tenant_config"))
    1127            0 :         })
    1128            0 :         .put("/v1/tenant/:tenant_shard_id/location_config", |r| {
    1129            0 :             tenant_service_handler(
    1130            0 :                 r,
    1131            0 :                 handle_tenant_location_config,
    1132            0 :                 RequestName("v1_tenant_location_config"),
    1133            0 :             )
    1134            0 :         })
    1135            0 :         .put("/v1/tenant/:tenant_id/time_travel_remote_storage", |r| {
    1136            0 :             tenant_service_handler(
    1137            0 :                 r,
    1138            0 :                 handle_tenant_time_travel_remote_storage,
    1139            0 :                 RequestName("v1_tenant_time_travel_remote_storage"),
    1140            0 :             )
    1141            0 :         })
    1142            0 :         .post("/v1/tenant/:tenant_id/secondary/download", |r| {
    1143            0 :             tenant_service_handler(
    1144            0 :                 r,
    1145            0 :                 handle_tenant_secondary_download,
    1146            0 :                 RequestName("v1_tenant_secondary_download"),
    1147            0 :             )
    1148            0 :         })
    1149            0 :         // Timeline operations
    1150            0 :         .delete("/v1/tenant/:tenant_id/timeline/:timeline_id", |r| {
    1151            0 :             tenant_service_handler(
    1152            0 :                 r,
    1153            0 :                 handle_tenant_timeline_delete,
    1154            0 :                 RequestName("v1_tenant_timeline"),
    1155            0 :             )
    1156            0 :         })
    1157            0 :         .post("/v1/tenant/:tenant_id/timeline", |r| {
    1158            0 :             tenant_service_handler(
    1159            0 :                 r,
    1160            0 :                 handle_tenant_timeline_create,
    1161            0 :                 RequestName("v1_tenant_timeline"),
    1162            0 :             )
    1163            0 :         })
    1164            0 :         .put(
    1165            0 :             "/v1/tenant/:tenant_id/timeline/:timeline_id/detach_ancestor",
    1166            0 :             |r| {
    1167            0 :                 tenant_service_handler(
    1168            0 :                     r,
    1169            0 :                     handle_tenant_timeline_detach_ancestor,
    1170            0 :                     RequestName("v1_tenant_timeline_detach_ancestor"),
    1171            0 :                 )
    1172            0 :             },
    1173            0 :         )
    1174            0 :         // Tenant detail GET passthrough to shard zero:
    1175            0 :         .get("/v1/tenant/:tenant_id", |r| {
    1176            0 :             tenant_service_handler(
    1177            0 :                 r,
    1178            0 :                 handle_tenant_timeline_passthrough,
    1179            0 :                 RequestName("v1_tenant_passthrough"),
    1180            0 :             )
    1181            0 :         })
    1182            0 :         // The `*` in the  URL is a wildcard: any tenant/timeline GET APIs on the pageserver
    1183            0 :         // are implicitly exposed here.  This must be last in the list to avoid
    1184            0 :         // taking precedence over other GET methods we might implement by hand.
    1185            0 :         .get("/v1/tenant/:tenant_id/*", |r| {
    1186            0 :             tenant_service_handler(
    1187            0 :                 r,
    1188            0 :                 handle_tenant_timeline_passthrough,
    1189            0 :                 RequestName("v1_tenant_passthrough"),
    1190            0 :             )
    1191            0 :         })
    1192            0 : }
        

Generated by: LCOV version 2.1-beta