LCOV - code coverage report
Current view: top level - storage_controller/src - http.rs (source / functions) Coverage Total Hit
Test: 2b0730d767f560e20b6748f57465922aa8bb805e.info Lines: 0.0 % 1400 0
Test Date: 2024-09-25 14:04:07 Functions: 0.0 % 382 0

            Line data    Source code
       1              : use crate::http;
       2              : use crate::metrics::{
       3              :     HttpRequestLatencyLabelGroup, HttpRequestStatusLabelGroup, PageserverRequestLabelGroup,
       4              :     METRICS_REGISTRY,
       5              : };
       6              : use crate::persistence::SafekeeperPersistence;
       7              : use crate::reconciler::ReconcileError;
       8              : use crate::service::{LeadershipStatus, Service, RECONCILE_TIMEOUT, STARTUP_RECONCILE_TIMEOUT};
       9              : use anyhow::Context;
      10              : use futures::Future;
      11              : use hyper::header::CONTENT_TYPE;
      12              : use hyper::{Body, Request, Response};
      13              : use hyper::{StatusCode, Uri};
      14              : use metrics::{BuildInfo, NeonMetrics};
      15              : use pageserver_api::controller_api::{
      16              :     MetadataHealthListOutdatedRequest, MetadataHealthListOutdatedResponse,
      17              :     MetadataHealthListUnhealthyResponse, MetadataHealthUpdateRequest, MetadataHealthUpdateResponse,
      18              :     ShardsPreferredAzsRequest, TenantCreateRequest,
      19              : };
      20              : use pageserver_api::models::{
      21              :     TenantConfigRequest, TenantLocationConfigRequest, TenantShardSplitRequest,
      22              :     TenantTimeTravelRequest, TimelineArchivalConfigRequest, TimelineCreateRequest,
      23              : };
      24              : use pageserver_api::shard::TenantShardId;
      25              : use pageserver_client::{mgmt_api, BlockUnblock};
      26              : use std::str::FromStr;
      27              : use std::sync::Arc;
      28              : use std::time::{Duration, Instant};
      29              : use tokio_util::sync::CancellationToken;
      30              : use utils::auth::{Scope, SwappableJwtAuth};
      31              : use utils::failpoint_support::failpoints_handler;
      32              : use utils::http::endpoint::{auth_middleware, check_permission_with, request_span};
      33              : use utils::http::request::{must_get_query_param, parse_query_param, parse_request_param};
      34              : use utils::id::{TenantId, TimelineId};
      35              : 
      36              : use utils::{
      37              :     http::{
      38              :         endpoint::{self},
      39              :         error::ApiError,
      40              :         json::{json_request, json_response},
      41              :         RequestExt, RouterBuilder,
      42              :     },
      43              :     id::NodeId,
      44              : };
      45              : 
      46              : use pageserver_api::controller_api::{
      47              :     NodeAvailability, NodeConfigureRequest, NodeRegisterRequest, TenantPolicyRequest,
      48              :     TenantShardMigrateRequest,
      49              : };
      50              : use pageserver_api::upcall_api::{ReAttachRequest, ValidateRequest};
      51              : 
      52              : use control_plane::storage_controller::{AttachHookRequest, InspectRequest};
      53              : 
      54              : use routerify::Middleware;
      55              : 
      56              : /// State available to HTTP request handlers
      57              : pub struct HttpState {
      58              :     service: Arc<crate::service::Service>,
      59              :     auth: Option<Arc<SwappableJwtAuth>>,
      60              :     neon_metrics: NeonMetrics,
      61              :     allowlist_routes: Vec<Uri>,
      62              : }
      63              : 
      64              : impl HttpState {
      65            0 :     pub fn new(
      66            0 :         service: Arc<crate::service::Service>,
      67            0 :         auth: Option<Arc<SwappableJwtAuth>>,
      68            0 :         build_info: BuildInfo,
      69            0 :     ) -> Self {
      70            0 :         let allowlist_routes = ["/status", "/ready", "/metrics"]
      71            0 :             .iter()
      72            0 :             .map(|v| v.parse().unwrap())
      73            0 :             .collect::<Vec<_>>();
      74            0 :         Self {
      75            0 :             service,
      76            0 :             auth,
      77            0 :             neon_metrics: NeonMetrics::new(build_info),
      78            0 :             allowlist_routes,
      79            0 :         }
      80            0 :     }
      81              : }
      82              : 
      83              : #[inline(always)]
      84            0 : fn get_state(request: &Request<Body>) -> &HttpState {
      85            0 :     request
      86            0 :         .data::<Arc<HttpState>>()
      87            0 :         .expect("unknown state type")
      88            0 :         .as_ref()
      89            0 : }
      90              : 
      91              : /// Pageserver calls into this on startup, to learn which tenants it should attach
      92            0 : async fn handle_re_attach(req: Request<Body>) -> Result<Response<Body>, ApiError> {
      93            0 :     check_permissions(&req, Scope::GenerationsApi)?;
      94              : 
      95            0 :     let mut req = match maybe_forward(req).await {
      96            0 :         ForwardOutcome::Forwarded(res) => {
      97            0 :             return res;
      98              :         }
      99            0 :         ForwardOutcome::NotForwarded(req) => req,
     100              :     };
     101              : 
     102            0 :     let reattach_req = json_request::<ReAttachRequest>(&mut req).await?;
     103            0 :     let state = get_state(&req);
     104            0 :     json_response(StatusCode::OK, state.service.re_attach(reattach_req).await?)
     105            0 : }
     106              : 
     107              : /// Pageserver calls into this before doing deletions, to confirm that it still
     108              : /// holds the latest generation for the tenants with deletions enqueued
     109            0 : async fn handle_validate(req: Request<Body>) -> Result<Response<Body>, ApiError> {
     110            0 :     check_permissions(&req, Scope::GenerationsApi)?;
     111              : 
     112            0 :     let mut req = match maybe_forward(req).await {
     113            0 :         ForwardOutcome::Forwarded(res) => {
     114            0 :             return res;
     115              :         }
     116            0 :         ForwardOutcome::NotForwarded(req) => req,
     117              :     };
     118              : 
     119            0 :     let validate_req = json_request::<ValidateRequest>(&mut req).await?;
     120            0 :     let state = get_state(&req);
     121            0 :     json_response(StatusCode::OK, state.service.validate(validate_req).await?)
     122            0 : }
     123              : 
     124              : /// Call into this before attaching a tenant to a pageserver, to acquire a generation number
     125              : /// (in the real control plane this is unnecessary, because the same program is managing
     126              : ///  generation numbers and doing attachments).
     127            0 : async fn handle_attach_hook(req: Request<Body>) -> Result<Response<Body>, ApiError> {
     128            0 :     check_permissions(&req, Scope::Admin)?;
     129              : 
     130            0 :     let mut req = match maybe_forward(req).await {
     131            0 :         ForwardOutcome::Forwarded(res) => {
     132            0 :             return res;
     133              :         }
     134            0 :         ForwardOutcome::NotForwarded(req) => req,
     135              :     };
     136              : 
     137            0 :     let attach_req = json_request::<AttachHookRequest>(&mut req).await?;
     138            0 :     let state = get_state(&req);
     139            0 : 
     140            0 :     json_response(
     141            0 :         StatusCode::OK,
     142            0 :         state
     143            0 :             .service
     144            0 :             .attach_hook(attach_req)
     145            0 :             .await
     146            0 :             .map_err(ApiError::InternalServerError)?,
     147              :     )
     148            0 : }
     149              : 
     150            0 : async fn handle_inspect(req: Request<Body>) -> Result<Response<Body>, ApiError> {
     151            0 :     check_permissions(&req, Scope::Admin)?;
     152              : 
     153            0 :     let mut req = match maybe_forward(req).await {
     154            0 :         ForwardOutcome::Forwarded(res) => {
     155            0 :             return res;
     156              :         }
     157            0 :         ForwardOutcome::NotForwarded(req) => req,
     158              :     };
     159              : 
     160            0 :     let inspect_req = json_request::<InspectRequest>(&mut req).await?;
     161              : 
     162            0 :     let state = get_state(&req);
     163            0 : 
     164            0 :     json_response(StatusCode::OK, state.service.inspect(inspect_req))
     165            0 : }
     166              : 
     167            0 : async fn handle_tenant_create(
     168            0 :     service: Arc<Service>,
     169            0 :     req: Request<Body>,
     170            0 : ) -> Result<Response<Body>, ApiError> {
     171            0 :     check_permissions(&req, Scope::PageServerApi)?;
     172              : 
     173            0 :     let mut req = match maybe_forward(req).await {
     174            0 :         ForwardOutcome::Forwarded(res) => {
     175            0 :             return res;
     176              :         }
     177            0 :         ForwardOutcome::NotForwarded(req) => req,
     178              :     };
     179              : 
     180            0 :     let create_req = json_request::<TenantCreateRequest>(&mut req).await?;
     181              : 
     182              :     json_response(
     183              :         StatusCode::CREATED,
     184            0 :         service.tenant_create(create_req).await?,
     185              :     )
     186            0 : }
     187              : 
     188            0 : async fn handle_tenant_location_config(
     189            0 :     service: Arc<Service>,
     190            0 :     req: Request<Body>,
     191            0 : ) -> Result<Response<Body>, ApiError> {
     192            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&req, "tenant_shard_id")?;
     193            0 :     check_permissions(&req, Scope::PageServerApi)?;
     194              : 
     195            0 :     let mut req = match maybe_forward(req).await {
     196            0 :         ForwardOutcome::Forwarded(res) => {
     197            0 :             return res;
     198              :         }
     199            0 :         ForwardOutcome::NotForwarded(req) => req,
     200              :     };
     201              : 
     202            0 :     let config_req = json_request::<TenantLocationConfigRequest>(&mut req).await?;
     203              :     json_response(
     204              :         StatusCode::OK,
     205            0 :         service
     206            0 :             .tenant_location_config(tenant_shard_id, config_req)
     207            0 :             .await?,
     208              :     )
     209            0 : }
     210              : 
     211            0 : async fn handle_tenant_config_set(
     212            0 :     service: Arc<Service>,
     213            0 :     req: Request<Body>,
     214            0 : ) -> Result<Response<Body>, ApiError> {
     215            0 :     check_permissions(&req, Scope::PageServerApi)?;
     216              : 
     217            0 :     let mut req = match maybe_forward(req).await {
     218            0 :         ForwardOutcome::Forwarded(res) => {
     219            0 :             return res;
     220              :         }
     221            0 :         ForwardOutcome::NotForwarded(req) => req,
     222              :     };
     223              : 
     224            0 :     let config_req = json_request::<TenantConfigRequest>(&mut req).await?;
     225              : 
     226            0 :     json_response(StatusCode::OK, service.tenant_config_set(config_req).await?)
     227            0 : }
     228              : 
     229            0 : async fn handle_tenant_config_get(
     230            0 :     service: Arc<Service>,
     231            0 :     req: Request<Body>,
     232            0 : ) -> Result<Response<Body>, ApiError> {
     233            0 :     let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
     234            0 :     check_permissions(&req, Scope::PageServerApi)?;
     235              : 
     236            0 :     match maybe_forward(req).await {
     237            0 :         ForwardOutcome::Forwarded(res) => {
     238            0 :             return res;
     239              :         }
     240            0 :         ForwardOutcome::NotForwarded(_req) => {}
     241            0 :     };
     242            0 : 
     243            0 :     json_response(StatusCode::OK, service.tenant_config_get(tenant_id)?)
     244            0 : }
     245              : 
     246            0 : async fn handle_tenant_time_travel_remote_storage(
     247            0 :     service: Arc<Service>,
     248            0 :     req: Request<Body>,
     249            0 : ) -> Result<Response<Body>, ApiError> {
     250            0 :     let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
     251            0 :     check_permissions(&req, Scope::PageServerApi)?;
     252              : 
     253            0 :     let mut req = match maybe_forward(req).await {
     254            0 :         ForwardOutcome::Forwarded(res) => {
     255            0 :             return res;
     256              :         }
     257            0 :         ForwardOutcome::NotForwarded(req) => req,
     258              :     };
     259              : 
     260            0 :     let time_travel_req = json_request::<TenantTimeTravelRequest>(&mut req).await?;
     261              : 
     262            0 :     let timestamp_raw = must_get_query_param(&req, "travel_to")?;
     263            0 :     let _timestamp = humantime::parse_rfc3339(&timestamp_raw).map_err(|_e| {
     264            0 :         ApiError::BadRequest(anyhow::anyhow!(
     265            0 :             "Invalid time for travel_to: {timestamp_raw:?}"
     266            0 :         ))
     267            0 :     })?;
     268              : 
     269            0 :     let done_if_after_raw = must_get_query_param(&req, "done_if_after")?;
     270            0 :     let _done_if_after = humantime::parse_rfc3339(&done_if_after_raw).map_err(|_e| {
     271            0 :         ApiError::BadRequest(anyhow::anyhow!(
     272            0 :             "Invalid time for done_if_after: {done_if_after_raw:?}"
     273            0 :         ))
     274            0 :     })?;
     275              : 
     276            0 :     service
     277            0 :         .tenant_time_travel_remote_storage(
     278            0 :             &time_travel_req,
     279            0 :             tenant_id,
     280            0 :             timestamp_raw,
     281            0 :             done_if_after_raw,
     282            0 :         )
     283            0 :         .await?;
     284            0 :     json_response(StatusCode::OK, ())
     285            0 : }
     286              : 
     287            0 : fn map_reqwest_hyper_status(status: reqwest::StatusCode) -> Result<hyper::StatusCode, ApiError> {
     288            0 :     hyper::StatusCode::from_u16(status.as_u16())
     289            0 :         .context("invalid status code")
     290            0 :         .map_err(ApiError::InternalServerError)
     291            0 : }
     292              : 
     293            0 : async fn handle_tenant_secondary_download(
     294            0 :     service: Arc<Service>,
     295            0 :     req: Request<Body>,
     296            0 : ) -> Result<Response<Body>, ApiError> {
     297            0 :     let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
     298            0 :     let wait = parse_query_param(&req, "wait_ms")?.map(Duration::from_millis);
     299            0 : 
     300            0 :     match maybe_forward(req).await {
     301            0 :         ForwardOutcome::Forwarded(res) => {
     302            0 :             return res;
     303              :         }
     304            0 :         ForwardOutcome::NotForwarded(_req) => {}
     305              :     };
     306              : 
     307            0 :     let (status, progress) = service.tenant_secondary_download(tenant_id, wait).await?;
     308            0 :     json_response(map_reqwest_hyper_status(status)?, progress)
     309            0 : }
     310              : 
     311            0 : async fn handle_tenant_delete(
     312            0 :     service: Arc<Service>,
     313            0 :     req: Request<Body>,
     314            0 : ) -> Result<Response<Body>, ApiError> {
     315            0 :     let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
     316            0 :     check_permissions(&req, Scope::PageServerApi)?;
     317              : 
     318            0 :     match maybe_forward(req).await {
     319            0 :         ForwardOutcome::Forwarded(res) => {
     320            0 :             return res;
     321              :         }
     322            0 :         ForwardOutcome::NotForwarded(_req) => {}
     323              :     };
     324              : 
     325            0 :     let status_code = service
     326            0 :         .tenant_delete(tenant_id)
     327            0 :         .await
     328            0 :         .and_then(map_reqwest_hyper_status)?;
     329              : 
     330            0 :     if status_code == StatusCode::NOT_FOUND {
     331              :         // The pageserver uses 404 for successful deletion, but we use 200
     332            0 :         json_response(StatusCode::OK, ())
     333              :     } else {
     334            0 :         json_response(status_code, ())
     335              :     }
     336            0 : }
     337              : 
     338            0 : async fn handle_tenant_timeline_create(
     339            0 :     service: Arc<Service>,
     340            0 :     req: Request<Body>,
     341            0 : ) -> Result<Response<Body>, ApiError> {
     342            0 :     let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
     343            0 :     check_permissions(&req, Scope::PageServerApi)?;
     344              : 
     345            0 :     let mut req = match maybe_forward(req).await {
     346            0 :         ForwardOutcome::Forwarded(res) => {
     347            0 :             return res;
     348              :         }
     349            0 :         ForwardOutcome::NotForwarded(req) => req,
     350              :     };
     351              : 
     352            0 :     let create_req = json_request::<TimelineCreateRequest>(&mut req).await?;
     353              :     json_response(
     354              :         StatusCode::CREATED,
     355            0 :         service
     356            0 :             .tenant_timeline_create(tenant_id, create_req)
     357            0 :             .await?,
     358              :     )
     359            0 : }
     360              : 
     361            0 : async fn handle_tenant_timeline_delete(
     362            0 :     service: Arc<Service>,
     363            0 :     req: Request<Body>,
     364            0 : ) -> Result<Response<Body>, ApiError> {
     365            0 :     let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
     366            0 :     let timeline_id: TimelineId = parse_request_param(&req, "timeline_id")?;
     367              : 
     368            0 :     check_permissions(&req, Scope::PageServerApi)?;
     369              : 
     370            0 :     match maybe_forward(req).await {
     371            0 :         ForwardOutcome::Forwarded(res) => {
     372            0 :             return res;
     373              :         }
     374            0 :         ForwardOutcome::NotForwarded(_req) => {}
     375              :     };
     376              : 
     377              :     // For timeline deletions, which both implement an "initially return 202, then 404 once
     378              :     // we're done" semantic, we wrap with a retry loop to expose a simpler API upstream.
     379            0 :     async fn deletion_wrapper<R, F>(service: Arc<Service>, f: F) -> Result<Response<Body>, ApiError>
     380            0 :     where
     381            0 :         R: std::future::Future<Output = Result<StatusCode, ApiError>> + Send + 'static,
     382            0 :         F: Fn(Arc<Service>) -> R + Send + Sync + 'static,
     383            0 :     {
     384            0 :         let started_at = Instant::now();
     385            0 :         // To keep deletion reasonably snappy for small tenants, initially check after 1 second if deletion
     386            0 :         // completed.
     387            0 :         let mut retry_period = Duration::from_secs(1);
     388            0 :         // On subsequent retries, wait longer.
     389            0 :         let max_retry_period = Duration::from_secs(5);
     390            0 :         // Enable callers with a 30 second request timeout to reliably get a response
     391            0 :         let max_wait = Duration::from_secs(25);
     392              : 
     393              :         loop {
     394            0 :             let status = f(service.clone()).await?;
     395            0 :             match status {
     396              :                 StatusCode::ACCEPTED => {
     397            0 :                     tracing::info!("Deletion accepted, waiting to try again...");
     398            0 :                     tokio::time::sleep(retry_period).await;
     399            0 :                     retry_period = max_retry_period;
     400              :                 }
     401              :                 StatusCode::NOT_FOUND => {
     402            0 :                     tracing::info!("Deletion complete");
     403            0 :                     return json_response(StatusCode::OK, ());
     404              :                 }
     405              :                 _ => {
     406            0 :                     tracing::warn!("Unexpected status {status}");
     407            0 :                     return json_response(status, ());
     408              :                 }
     409              :             }
     410              : 
     411            0 :             let now = Instant::now();
     412            0 :             if now + retry_period > started_at + max_wait {
     413            0 :                 tracing::info!("Deletion timed out waiting for 404");
     414              :                 // REQUEST_TIMEOUT would be more appropriate, but CONFLICT is already part of
     415              :                 // the pageserver's swagger definition for this endpoint, and has the same desired
     416              :                 // effect of causing the control plane to retry later.
     417            0 :                 return json_response(StatusCode::CONFLICT, ());
     418            0 :             }
     419              :         }
     420            0 :     }
     421              : 
     422            0 :     deletion_wrapper(service, move |service| async move {
     423            0 :         service
     424            0 :             .tenant_timeline_delete(tenant_id, timeline_id)
     425            0 :             .await
     426            0 :             .and_then(map_reqwest_hyper_status)
     427            0 :     })
     428            0 :     .await
     429            0 : }
     430              : 
     431            0 : async fn handle_tenant_timeline_archival_config(
     432            0 :     service: Arc<Service>,
     433            0 :     req: Request<Body>,
     434            0 : ) -> Result<Response<Body>, ApiError> {
     435            0 :     let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
     436            0 :     let timeline_id: TimelineId = parse_request_param(&req, "timeline_id")?;
     437              : 
     438            0 :     check_permissions(&req, Scope::PageServerApi)?;
     439              : 
     440            0 :     let mut req = match maybe_forward(req).await {
     441            0 :         ForwardOutcome::Forwarded(res) => {
     442            0 :             return res;
     443              :         }
     444            0 :         ForwardOutcome::NotForwarded(req) => req,
     445              :     };
     446              : 
     447            0 :     let create_req = json_request::<TimelineArchivalConfigRequest>(&mut req).await?;
     448              : 
     449            0 :     service
     450            0 :         .tenant_timeline_archival_config(tenant_id, timeline_id, create_req)
     451            0 :         .await?;
     452              : 
     453            0 :     json_response(StatusCode::OK, ())
     454            0 : }
     455              : 
     456            0 : async fn handle_tenant_timeline_detach_ancestor(
     457            0 :     service: Arc<Service>,
     458            0 :     req: Request<Body>,
     459            0 : ) -> Result<Response<Body>, ApiError> {
     460            0 :     let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
     461            0 :     let timeline_id: TimelineId = parse_request_param(&req, "timeline_id")?;
     462              : 
     463            0 :     check_permissions(&req, Scope::PageServerApi)?;
     464              : 
     465            0 :     match maybe_forward(req).await {
     466            0 :         ForwardOutcome::Forwarded(res) => {
     467            0 :             return res;
     468              :         }
     469            0 :         ForwardOutcome::NotForwarded(_req) => {}
     470              :     };
     471              : 
     472            0 :     let res = service
     473            0 :         .tenant_timeline_detach_ancestor(tenant_id, timeline_id)
     474            0 :         .await?;
     475              : 
     476            0 :     json_response(StatusCode::OK, res)
     477            0 : }
     478              : 
     479            0 : async fn handle_tenant_timeline_block_unblock_gc(
     480            0 :     service: Arc<Service>,
     481            0 :     req: Request<Body>,
     482            0 :     dir: BlockUnblock,
     483            0 : ) -> Result<Response<Body>, ApiError> {
     484            0 :     let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
     485            0 :     check_permissions(&req, Scope::PageServerApi)?;
     486              : 
     487            0 :     let timeline_id: TimelineId = parse_request_param(&req, "timeline_id")?;
     488              : 
     489            0 :     service
     490            0 :         .tenant_timeline_block_unblock_gc(tenant_id, timeline_id, dir)
     491            0 :         .await?;
     492              : 
     493            0 :     json_response(StatusCode::OK, ())
     494            0 : }
     495              : 
     496            0 : async fn handle_tenant_timeline_passthrough(
     497            0 :     service: Arc<Service>,
     498            0 :     req: Request<Body>,
     499            0 : ) -> Result<Response<Body>, ApiError> {
     500            0 :     let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
     501            0 :     check_permissions(&req, Scope::PageServerApi)?;
     502              : 
     503            0 :     let req = match maybe_forward(req).await {
     504            0 :         ForwardOutcome::Forwarded(res) => {
     505            0 :             return res;
     506              :         }
     507            0 :         ForwardOutcome::NotForwarded(req) => req,
     508              :     };
     509              : 
     510            0 :     let Some(path) = req.uri().path_and_query() else {
     511              :         // This should never happen, our request router only calls us if there is a path
     512            0 :         return Err(ApiError::BadRequest(anyhow::anyhow!("Missing path")));
     513              :     };
     514              : 
     515            0 :     tracing::info!("Proxying request for tenant {} ({})", tenant_id, path);
     516              : 
     517              :     // Find the node that holds shard zero
     518            0 :     let (node, tenant_shard_id) = service.tenant_shard0_node(tenant_id).await?;
     519              : 
     520              :     // Callers will always pass an unsharded tenant ID.  Before proxying, we must
     521              :     // rewrite this to a shard-aware shard zero ID.
     522            0 :     let path = format!("{}", path);
     523            0 :     let tenant_str = tenant_id.to_string();
     524            0 :     let tenant_shard_str = format!("{}", tenant_shard_id);
     525            0 :     let path = path.replace(&tenant_str, &tenant_shard_str);
     526            0 : 
     527            0 :     let latency = &METRICS_REGISTRY
     528            0 :         .metrics_group
     529            0 :         .storage_controller_passthrough_request_latency;
     530            0 : 
     531            0 :     // This is a bit awkward. We remove the param from the request
     532            0 :     // and join the words by '_' to get a label for the request.
     533            0 :     let just_path = path.replace(&tenant_shard_str, "");
     534            0 :     let path_label = just_path
     535            0 :         .split('/')
     536            0 :         .filter(|token| !token.is_empty())
     537            0 :         .collect::<Vec<_>>()
     538            0 :         .join("_");
     539            0 :     let labels = PageserverRequestLabelGroup {
     540            0 :         pageserver_id: &node.get_id().to_string(),
     541            0 :         path: &path_label,
     542            0 :         method: crate::metrics::Method::Get,
     543            0 :     };
     544            0 : 
     545            0 :     let _timer = latency.start_timer(labels.clone());
     546            0 : 
     547            0 :     let client = mgmt_api::Client::new(node.base_url(), service.get_config().jwt_token.as_deref());
     548            0 :     let resp = client.get_raw(path).await.map_err(|e|
     549              :         // We return 503 here because if we can't successfully send a request to the pageserver,
     550              :         // either we aren't available or the pageserver is unavailable.
     551            0 :         ApiError::ResourceUnavailable(format!("Error sending pageserver API request to {node}: {e}").into()))?;
     552              : 
     553            0 :     if !resp.status().is_success() {
     554            0 :         let error_counter = &METRICS_REGISTRY
     555            0 :             .metrics_group
     556            0 :             .storage_controller_passthrough_request_error;
     557            0 :         error_counter.inc(labels);
     558            0 :     }
     559              : 
     560              :     // Transform 404 into 503 if we raced with a migration
     561            0 :     if resp.status() == reqwest::StatusCode::NOT_FOUND {
     562              :         // Look up node again: if we migrated it will be different
     563            0 :         let (new_node, _tenant_shard_id) = service.tenant_shard0_node(tenant_id).await?;
     564            0 :         if new_node.get_id() != node.get_id() {
     565              :             // Rather than retry here, send the client a 503 to prompt a retry: this matches
     566              :             // the pageserver's use of 503, and all clients calling this API should retry on 503.
     567            0 :             return Err(ApiError::ResourceUnavailable(
     568            0 :                 format!("Pageserver {node} returned 404, was migrated to {new_node}").into(),
     569            0 :             ));
     570            0 :         }
     571            0 :     }
     572              : 
     573              :     // We have a reqest::Response, would like a http::Response
     574            0 :     let mut builder = hyper::Response::builder().status(map_reqwest_hyper_status(resp.status())?);
     575            0 :     for (k, v) in resp.headers() {
     576            0 :         builder = builder.header(k.as_str(), v.as_bytes());
     577            0 :     }
     578              : 
     579            0 :     let response = builder
     580            0 :         .body(Body::wrap_stream(resp.bytes_stream()))
     581            0 :         .map_err(|e| ApiError::InternalServerError(e.into()))?;
     582              : 
     583            0 :     Ok(response)
     584            0 : }
     585              : 
     586            0 : async fn handle_tenant_locate(
     587            0 :     service: Arc<Service>,
     588            0 :     req: Request<Body>,
     589            0 : ) -> Result<Response<Body>, ApiError> {
     590            0 :     let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
     591              : 
     592            0 :     check_permissions(&req, Scope::Admin)?;
     593              : 
     594            0 :     match maybe_forward(req).await {
     595            0 :         ForwardOutcome::Forwarded(res) => {
     596            0 :             return res;
     597              :         }
     598            0 :         ForwardOutcome::NotForwarded(_req) => {}
     599            0 :     };
     600            0 : 
     601            0 :     json_response(StatusCode::OK, service.tenant_locate(tenant_id)?)
     602            0 : }
     603              : 
     604            0 : async fn handle_tenant_describe(
     605            0 :     service: Arc<Service>,
     606            0 :     req: Request<Body>,
     607            0 : ) -> Result<Response<Body>, ApiError> {
     608            0 :     check_permissions(&req, Scope::Scrubber)?;
     609              : 
     610            0 :     let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
     611              : 
     612            0 :     match maybe_forward(req).await {
     613            0 :         ForwardOutcome::Forwarded(res) => {
     614            0 :             return res;
     615              :         }
     616            0 :         ForwardOutcome::NotForwarded(_req) => {}
     617            0 :     };
     618            0 : 
     619            0 :     json_response(StatusCode::OK, service.tenant_describe(tenant_id)?)
     620            0 : }
     621              : 
     622            0 : async fn handle_tenant_list(
     623            0 :     service: Arc<Service>,
     624            0 :     req: Request<Body>,
     625            0 : ) -> Result<Response<Body>, ApiError> {
     626            0 :     check_permissions(&req, Scope::Admin)?;
     627              : 
     628            0 :     match maybe_forward(req).await {
     629            0 :         ForwardOutcome::Forwarded(res) => {
     630            0 :             return res;
     631              :         }
     632            0 :         ForwardOutcome::NotForwarded(_req) => {}
     633            0 :     };
     634            0 : 
     635            0 :     json_response(StatusCode::OK, service.tenant_list())
     636            0 : }
     637              : 
     638            0 : async fn handle_node_register(req: Request<Body>) -> Result<Response<Body>, ApiError> {
     639            0 :     check_permissions(&req, Scope::Admin)?;
     640              : 
     641            0 :     let mut req = match maybe_forward(req).await {
     642            0 :         ForwardOutcome::Forwarded(res) => {
     643            0 :             return res;
     644              :         }
     645            0 :         ForwardOutcome::NotForwarded(req) => req,
     646              :     };
     647              : 
     648            0 :     let register_req = json_request::<NodeRegisterRequest>(&mut req).await?;
     649            0 :     let state = get_state(&req);
     650            0 :     state.service.node_register(register_req).await?;
     651            0 :     json_response(StatusCode::OK, ())
     652            0 : }
     653              : 
     654            0 : async fn handle_node_list(req: Request<Body>) -> Result<Response<Body>, ApiError> {
     655            0 :     check_permissions(&req, Scope::Admin)?;
     656              : 
     657            0 :     let req = match maybe_forward(req).await {
     658            0 :         ForwardOutcome::Forwarded(res) => {
     659            0 :             return res;
     660              :         }
     661            0 :         ForwardOutcome::NotForwarded(req) => req,
     662            0 :     };
     663            0 : 
     664            0 :     let state = get_state(&req);
     665            0 :     let nodes = state.service.node_list().await?;
     666            0 :     let api_nodes = nodes.into_iter().map(|n| n.describe()).collect::<Vec<_>>();
     667            0 : 
     668            0 :     json_response(StatusCode::OK, api_nodes)
     669            0 : }
     670              : 
     671            0 : async fn handle_node_drop(req: Request<Body>) -> Result<Response<Body>, ApiError> {
     672            0 :     check_permissions(&req, Scope::Admin)?;
     673              : 
     674            0 :     let req = match maybe_forward(req).await {
     675            0 :         ForwardOutcome::Forwarded(res) => {
     676            0 :             return res;
     677              :         }
     678            0 :         ForwardOutcome::NotForwarded(req) => req,
     679            0 :     };
     680            0 : 
     681            0 :     let state = get_state(&req);
     682            0 :     let node_id: NodeId = parse_request_param(&req, "node_id")?;
     683            0 :     json_response(StatusCode::OK, state.service.node_drop(node_id).await?)
     684            0 : }
     685              : 
     686            0 : async fn handle_node_delete(req: Request<Body>) -> Result<Response<Body>, ApiError> {
     687            0 :     check_permissions(&req, Scope::Admin)?;
     688              : 
     689            0 :     let req = match maybe_forward(req).await {
     690            0 :         ForwardOutcome::Forwarded(res) => {
     691            0 :             return res;
     692              :         }
     693            0 :         ForwardOutcome::NotForwarded(req) => req,
     694            0 :     };
     695            0 : 
     696            0 :     let state = get_state(&req);
     697            0 :     let node_id: NodeId = parse_request_param(&req, "node_id")?;
     698            0 :     json_response(StatusCode::OK, state.service.node_delete(node_id).await?)
     699            0 : }
     700              : 
     701            0 : async fn handle_node_configure(req: Request<Body>) -> Result<Response<Body>, ApiError> {
     702            0 :     check_permissions(&req, Scope::Admin)?;
     703              : 
     704            0 :     let mut req = match maybe_forward(req).await {
     705            0 :         ForwardOutcome::Forwarded(res) => {
     706            0 :             return res;
     707              :         }
     708            0 :         ForwardOutcome::NotForwarded(req) => req,
     709              :     };
     710              : 
     711            0 :     let node_id: NodeId = parse_request_param(&req, "node_id")?;
     712            0 :     let config_req = json_request::<NodeConfigureRequest>(&mut req).await?;
     713            0 :     if node_id != config_req.node_id {
     714            0 :         return Err(ApiError::BadRequest(anyhow::anyhow!(
     715            0 :             "Path and body node_id differ"
     716            0 :         )));
     717            0 :     }
     718            0 :     let state = get_state(&req);
     719            0 : 
     720            0 :     json_response(
     721            0 :         StatusCode::OK,
     722            0 :         state
     723            0 :             .service
     724            0 :             .external_node_configure(
     725            0 :                 config_req.node_id,
     726            0 :                 config_req.availability.map(NodeAvailability::from),
     727            0 :                 config_req.scheduling,
     728            0 :             )
     729            0 :             .await?,
     730              :     )
     731            0 : }
     732              : 
     733            0 : async fn handle_node_status(req: Request<Body>) -> Result<Response<Body>, ApiError> {
     734            0 :     check_permissions(&req, Scope::Admin)?;
     735              : 
     736            0 :     let req = match maybe_forward(req).await {
     737            0 :         ForwardOutcome::Forwarded(res) => {
     738            0 :             return res;
     739              :         }
     740            0 :         ForwardOutcome::NotForwarded(req) => req,
     741            0 :     };
     742            0 : 
     743            0 :     let state = get_state(&req);
     744            0 :     let node_id: NodeId = parse_request_param(&req, "node_id")?;
     745              : 
     746            0 :     let node_status = state.service.get_node(node_id).await?;
     747              : 
     748            0 :     json_response(StatusCode::OK, node_status)
     749            0 : }
     750              : 
     751            0 : async fn handle_node_shards(req: Request<Body>) -> Result<Response<Body>, ApiError> {
     752            0 :     check_permissions(&req, Scope::Admin)?;
     753              : 
     754            0 :     let state = get_state(&req);
     755            0 :     let node_id: NodeId = parse_request_param(&req, "node_id")?;
     756              : 
     757            0 :     let node_status = state.service.get_node_shards(node_id).await?;
     758              : 
     759            0 :     json_response(StatusCode::OK, node_status)
     760            0 : }
     761              : 
     762            0 : async fn handle_get_leader(req: Request<Body>) -> Result<Response<Body>, ApiError> {
     763            0 :     check_permissions(&req, Scope::Admin)?;
     764              : 
     765            0 :     let req = match maybe_forward(req).await {
     766            0 :         ForwardOutcome::Forwarded(res) => {
     767            0 :             return res;
     768              :         }
     769            0 :         ForwardOutcome::NotForwarded(req) => req,
     770            0 :     };
     771            0 : 
     772            0 :     let state = get_state(&req);
     773            0 :     let leader = state.service.get_leader().await.map_err(|err| {
     774            0 :         ApiError::InternalServerError(anyhow::anyhow!(
     775            0 :             "Failed to read leader from database: {err}"
     776            0 :         ))
     777            0 :     })?;
     778              : 
     779            0 :     json_response(StatusCode::OK, leader)
     780            0 : }
     781              : 
     782            0 : async fn handle_node_drain(req: Request<Body>) -> Result<Response<Body>, ApiError> {
     783            0 :     check_permissions(&req, Scope::Admin)?;
     784              : 
     785            0 :     let req = match maybe_forward(req).await {
     786            0 :         ForwardOutcome::Forwarded(res) => {
     787            0 :             return res;
     788              :         }
     789            0 :         ForwardOutcome::NotForwarded(req) => req,
     790            0 :     };
     791            0 : 
     792            0 :     let state = get_state(&req);
     793            0 :     let node_id: NodeId = parse_request_param(&req, "node_id")?;
     794              : 
     795            0 :     state.service.start_node_drain(node_id).await?;
     796              : 
     797            0 :     json_response(StatusCode::ACCEPTED, ())
     798            0 : }
     799              : 
     800            0 : async fn handle_cancel_node_drain(req: Request<Body>) -> Result<Response<Body>, ApiError> {
     801            0 :     check_permissions(&req, Scope::Admin)?;
     802              : 
     803            0 :     let req = match maybe_forward(req).await {
     804            0 :         ForwardOutcome::Forwarded(res) => {
     805            0 :             return res;
     806              :         }
     807            0 :         ForwardOutcome::NotForwarded(req) => req,
     808            0 :     };
     809            0 : 
     810            0 :     let state = get_state(&req);
     811            0 :     let node_id: NodeId = parse_request_param(&req, "node_id")?;
     812              : 
     813            0 :     state.service.cancel_node_drain(node_id).await?;
     814              : 
     815            0 :     json_response(StatusCode::ACCEPTED, ())
     816            0 : }
     817              : 
     818            0 : async fn handle_node_fill(req: Request<Body>) -> Result<Response<Body>, ApiError> {
     819            0 :     check_permissions(&req, Scope::Admin)?;
     820              : 
     821            0 :     let req = match maybe_forward(req).await {
     822            0 :         ForwardOutcome::Forwarded(res) => {
     823            0 :             return res;
     824              :         }
     825            0 :         ForwardOutcome::NotForwarded(req) => req,
     826            0 :     };
     827            0 : 
     828            0 :     let state = get_state(&req);
     829            0 :     let node_id: NodeId = parse_request_param(&req, "node_id")?;
     830              : 
     831            0 :     state.service.start_node_fill(node_id).await?;
     832              : 
     833            0 :     json_response(StatusCode::ACCEPTED, ())
     834            0 : }
     835              : 
     836            0 : async fn handle_cancel_node_fill(req: Request<Body>) -> Result<Response<Body>, ApiError> {
     837            0 :     check_permissions(&req, Scope::Admin)?;
     838              : 
     839            0 :     let req = match maybe_forward(req).await {
     840            0 :         ForwardOutcome::Forwarded(res) => {
     841            0 :             return res;
     842              :         }
     843            0 :         ForwardOutcome::NotForwarded(req) => req,
     844            0 :     };
     845            0 : 
     846            0 :     let state = get_state(&req);
     847            0 :     let node_id: NodeId = parse_request_param(&req, "node_id")?;
     848              : 
     849            0 :     state.service.cancel_node_fill(node_id).await?;
     850              : 
     851            0 :     json_response(StatusCode::ACCEPTED, ())
     852            0 : }
     853              : 
     854            0 : async fn handle_metadata_health_update(req: Request<Body>) -> Result<Response<Body>, ApiError> {
     855            0 :     check_permissions(&req, Scope::Scrubber)?;
     856              : 
     857            0 :     let mut req = match maybe_forward(req).await {
     858            0 :         ForwardOutcome::Forwarded(res) => {
     859            0 :             return res;
     860              :         }
     861            0 :         ForwardOutcome::NotForwarded(req) => req,
     862              :     };
     863              : 
     864            0 :     let update_req = json_request::<MetadataHealthUpdateRequest>(&mut req).await?;
     865            0 :     let state = get_state(&req);
     866            0 : 
     867            0 :     state.service.metadata_health_update(update_req).await?;
     868              : 
     869            0 :     json_response(StatusCode::OK, MetadataHealthUpdateResponse {})
     870            0 : }
     871              : 
     872            0 : async fn handle_metadata_health_list_unhealthy(
     873            0 :     req: Request<Body>,
     874            0 : ) -> Result<Response<Body>, ApiError> {
     875            0 :     check_permissions(&req, Scope::Admin)?;
     876              : 
     877            0 :     let req = match maybe_forward(req).await {
     878            0 :         ForwardOutcome::Forwarded(res) => {
     879            0 :             return res;
     880              :         }
     881            0 :         ForwardOutcome::NotForwarded(req) => req,
     882            0 :     };
     883            0 : 
     884            0 :     let state = get_state(&req);
     885            0 :     let unhealthy_tenant_shards = state.service.metadata_health_list_unhealthy().await?;
     886              : 
     887            0 :     json_response(
     888            0 :         StatusCode::OK,
     889            0 :         MetadataHealthListUnhealthyResponse {
     890            0 :             unhealthy_tenant_shards,
     891            0 :         },
     892            0 :     )
     893            0 : }
     894              : 
     895            0 : async fn handle_metadata_health_list_outdated(
     896            0 :     req: Request<Body>,
     897            0 : ) -> Result<Response<Body>, ApiError> {
     898            0 :     check_permissions(&req, Scope::Admin)?;
     899              : 
     900            0 :     let mut req = match maybe_forward(req).await {
     901            0 :         ForwardOutcome::Forwarded(res) => {
     902            0 :             return res;
     903              :         }
     904            0 :         ForwardOutcome::NotForwarded(req) => req,
     905              :     };
     906              : 
     907            0 :     let list_outdated_req = json_request::<MetadataHealthListOutdatedRequest>(&mut req).await?;
     908            0 :     let state = get_state(&req);
     909            0 :     let health_records = state
     910            0 :         .service
     911            0 :         .metadata_health_list_outdated(list_outdated_req.not_scrubbed_for)
     912            0 :         .await?;
     913              : 
     914            0 :     json_response(
     915            0 :         StatusCode::OK,
     916            0 :         MetadataHealthListOutdatedResponse { health_records },
     917            0 :     )
     918            0 : }
     919              : 
     920            0 : async fn handle_tenant_shard_split(
     921            0 :     service: Arc<Service>,
     922            0 :     req: Request<Body>,
     923            0 : ) -> Result<Response<Body>, ApiError> {
     924            0 :     check_permissions(&req, Scope::Admin)?;
     925              : 
     926            0 :     let mut req = match maybe_forward(req).await {
     927            0 :         ForwardOutcome::Forwarded(res) => {
     928            0 :             return res;
     929              :         }
     930            0 :         ForwardOutcome::NotForwarded(req) => req,
     931              :     };
     932              : 
     933            0 :     let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
     934            0 :     let split_req = json_request::<TenantShardSplitRequest>(&mut req).await?;
     935              : 
     936              :     json_response(
     937              :         StatusCode::OK,
     938            0 :         service.tenant_shard_split(tenant_id, split_req).await?,
     939              :     )
     940            0 : }
     941              : 
     942            0 : async fn handle_tenant_shard_migrate(
     943            0 :     service: Arc<Service>,
     944            0 :     req: Request<Body>,
     945            0 : ) -> Result<Response<Body>, ApiError> {
     946            0 :     check_permissions(&req, Scope::Admin)?;
     947              : 
     948            0 :     let mut req = match maybe_forward(req).await {
     949            0 :         ForwardOutcome::Forwarded(res) => {
     950            0 :             return res;
     951              :         }
     952            0 :         ForwardOutcome::NotForwarded(req) => req,
     953              :     };
     954              : 
     955            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&req, "tenant_shard_id")?;
     956            0 :     let migrate_req = json_request::<TenantShardMigrateRequest>(&mut req).await?;
     957              :     json_response(
     958              :         StatusCode::OK,
     959            0 :         service
     960            0 :             .tenant_shard_migrate(tenant_shard_id, migrate_req)
     961            0 :             .await?,
     962              :     )
     963            0 : }
     964              : 
     965            0 : async fn handle_tenant_update_policy(req: Request<Body>) -> Result<Response<Body>, ApiError> {
     966            0 :     check_permissions(&req, Scope::Admin)?;
     967              : 
     968            0 :     let mut req = match maybe_forward(req).await {
     969            0 :         ForwardOutcome::Forwarded(res) => {
     970            0 :             return res;
     971              :         }
     972            0 :         ForwardOutcome::NotForwarded(req) => req,
     973              :     };
     974              : 
     975            0 :     let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
     976            0 :     let update_req = json_request::<TenantPolicyRequest>(&mut req).await?;
     977            0 :     let state = get_state(&req);
     978            0 : 
     979            0 :     json_response(
     980            0 :         StatusCode::OK,
     981            0 :         state
     982            0 :             .service
     983            0 :             .tenant_update_policy(tenant_id, update_req)
     984            0 :             .await?,
     985              :     )
     986            0 : }
     987              : 
     988            0 : async fn handle_update_preferred_azs(req: Request<Body>) -> Result<Response<Body>, ApiError> {
     989            0 :     check_permissions(&req, Scope::Admin)?;
     990              : 
     991            0 :     let mut req = match maybe_forward(req).await {
     992            0 :         ForwardOutcome::Forwarded(res) => {
     993            0 :             return res;
     994              :         }
     995            0 :         ForwardOutcome::NotForwarded(req) => req,
     996              :     };
     997              : 
     998            0 :     let azs_req = json_request::<ShardsPreferredAzsRequest>(&mut req).await?;
     999            0 :     let state = get_state(&req);
    1000            0 : 
    1001            0 :     json_response(
    1002            0 :         StatusCode::OK,
    1003            0 :         state.service.update_shards_preferred_azs(azs_req).await?,
    1004              :     )
    1005            0 : }
    1006              : 
    1007            0 : async fn handle_step_down(req: Request<Body>) -> Result<Response<Body>, ApiError> {
    1008            0 :     check_permissions(&req, Scope::Admin)?;
    1009              : 
    1010            0 :     let req = match maybe_forward(req).await {
    1011            0 :         ForwardOutcome::Forwarded(res) => {
    1012            0 :             return res;
    1013              :         }
    1014            0 :         ForwardOutcome::NotForwarded(req) => req,
    1015            0 :     };
    1016            0 : 
    1017            0 :     let state = get_state(&req);
    1018            0 :     json_response(StatusCode::OK, state.service.step_down().await)
    1019            0 : }
    1020              : 
    1021            0 : async fn handle_tenant_drop(req: Request<Body>) -> Result<Response<Body>, ApiError> {
    1022            0 :     check_permissions(&req, Scope::PageServerApi)?;
    1023              : 
    1024            0 :     let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
    1025              : 
    1026            0 :     let req = match maybe_forward(req).await {
    1027            0 :         ForwardOutcome::Forwarded(res) => {
    1028            0 :             return res;
    1029              :         }
    1030            0 :         ForwardOutcome::NotForwarded(req) => req,
    1031            0 :     };
    1032            0 : 
    1033            0 :     let state = get_state(&req);
    1034            0 : 
    1035            0 :     json_response(StatusCode::OK, state.service.tenant_drop(tenant_id).await?)
    1036            0 : }
    1037              : 
    1038            0 : async fn handle_tenant_import(req: Request<Body>) -> Result<Response<Body>, ApiError> {
    1039            0 :     check_permissions(&req, Scope::PageServerApi)?;
    1040              : 
    1041            0 :     let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
    1042              : 
    1043            0 :     let req = match maybe_forward(req).await {
    1044            0 :         ForwardOutcome::Forwarded(res) => {
    1045            0 :             return res;
    1046              :         }
    1047            0 :         ForwardOutcome::NotForwarded(req) => req,
    1048            0 :     };
    1049            0 : 
    1050            0 :     let state = get_state(&req);
    1051            0 : 
    1052            0 :     json_response(
    1053            0 :         StatusCode::OK,
    1054            0 :         state.service.tenant_import(tenant_id).await?,
    1055              :     )
    1056            0 : }
    1057              : 
    1058            0 : async fn handle_tenants_dump(req: Request<Body>) -> Result<Response<Body>, ApiError> {
    1059            0 :     check_permissions(&req, Scope::Admin)?;
    1060              : 
    1061            0 :     let req = match maybe_forward(req).await {
    1062            0 :         ForwardOutcome::Forwarded(res) => {
    1063            0 :             return res;
    1064              :         }
    1065            0 :         ForwardOutcome::NotForwarded(req) => req,
    1066            0 :     };
    1067            0 : 
    1068            0 :     let state = get_state(&req);
    1069            0 :     state.service.tenants_dump()
    1070            0 : }
    1071              : 
    1072            0 : async fn handle_scheduler_dump(req: Request<Body>) -> Result<Response<Body>, ApiError> {
    1073            0 :     check_permissions(&req, Scope::Admin)?;
    1074              : 
    1075            0 :     let req = match maybe_forward(req).await {
    1076            0 :         ForwardOutcome::Forwarded(res) => {
    1077            0 :             return res;
    1078              :         }
    1079            0 :         ForwardOutcome::NotForwarded(req) => req,
    1080            0 :     };
    1081            0 : 
    1082            0 :     let state = get_state(&req);
    1083            0 :     state.service.scheduler_dump()
    1084            0 : }
    1085              : 
    1086            0 : async fn handle_consistency_check(req: Request<Body>) -> Result<Response<Body>, ApiError> {
    1087            0 :     check_permissions(&req, Scope::Admin)?;
    1088              : 
    1089            0 :     let req = match maybe_forward(req).await {
    1090            0 :         ForwardOutcome::Forwarded(res) => {
    1091            0 :             return res;
    1092              :         }
    1093            0 :         ForwardOutcome::NotForwarded(req) => req,
    1094            0 :     };
    1095            0 : 
    1096            0 :     let state = get_state(&req);
    1097            0 : 
    1098            0 :     json_response(StatusCode::OK, state.service.consistency_check().await?)
    1099            0 : }
    1100              : 
    1101            0 : async fn handle_reconcile_all(req: Request<Body>) -> Result<Response<Body>, ApiError> {
    1102            0 :     check_permissions(&req, Scope::Admin)?;
    1103              : 
    1104            0 :     let req = match maybe_forward(req).await {
    1105            0 :         ForwardOutcome::Forwarded(res) => {
    1106            0 :             return res;
    1107              :         }
    1108            0 :         ForwardOutcome::NotForwarded(req) => req,
    1109            0 :     };
    1110            0 : 
    1111            0 :     let state = get_state(&req);
    1112            0 : 
    1113            0 :     json_response(StatusCode::OK, state.service.reconcile_all_now().await?)
    1114            0 : }
    1115              : 
    1116              : /// Status endpoint is just used for checking that our HTTP listener is up
    1117            0 : async fn handle_status(req: Request<Body>) -> Result<Response<Body>, ApiError> {
    1118            0 :     match maybe_forward(req).await {
    1119            0 :         ForwardOutcome::Forwarded(res) => {
    1120            0 :             return res;
    1121              :         }
    1122            0 :         ForwardOutcome::NotForwarded(_req) => {}
    1123            0 :     };
    1124            0 : 
    1125            0 :     json_response(StatusCode::OK, ())
    1126            0 : }
    1127              : 
    1128              : /// Readiness endpoint indicates when we're done doing startup I/O (e.g. reconciling
    1129              : /// with remote pageserver nodes).  This is intended for use as a kubernetes readiness probe.
    1130            0 : async fn handle_ready(req: Request<Body>) -> Result<Response<Body>, ApiError> {
    1131            0 :     let req = match maybe_forward(req).await {
    1132            0 :         ForwardOutcome::Forwarded(res) => {
    1133            0 :             return res;
    1134              :         }
    1135            0 :         ForwardOutcome::NotForwarded(req) => req,
    1136            0 :     };
    1137            0 : 
    1138            0 :     let state = get_state(&req);
    1139            0 :     if state.service.startup_complete.is_ready() {
    1140            0 :         json_response(StatusCode::OK, ())
    1141              :     } else {
    1142            0 :         json_response(StatusCode::SERVICE_UNAVAILABLE, ())
    1143              :     }
    1144            0 : }
    1145              : 
    1146              : impl From<ReconcileError> for ApiError {
    1147            0 :     fn from(value: ReconcileError) -> Self {
    1148            0 :         ApiError::Conflict(format!("Reconciliation error: {}", value))
    1149            0 :     }
    1150              : }
    1151              : 
    1152              : /// Return the safekeeper record by instance id, or 404.
    1153              : ///
    1154              : /// Not used by anything except manual testing.
    1155            0 : async fn handle_get_safekeeper(req: Request<Body>) -> Result<Response<Body>, ApiError> {
    1156            0 :     check_permissions(&req, Scope::Admin)?;
    1157              : 
    1158            0 :     let id = parse_request_param::<i64>(&req, "id")?;
    1159              : 
    1160            0 :     let req = match maybe_forward(req).await {
    1161            0 :         ForwardOutcome::Forwarded(res) => {
    1162            0 :             return res;
    1163              :         }
    1164            0 :         ForwardOutcome::NotForwarded(req) => req,
    1165            0 :     };
    1166            0 : 
    1167            0 :     let state = get_state(&req);
    1168              : 
    1169            0 :     let res = state.service.get_safekeeper(id).await;
    1170              : 
    1171            0 :     match res {
    1172            0 :         Ok(b) => json_response(StatusCode::OK, b),
    1173              :         Err(crate::persistence::DatabaseError::Query(diesel::result::Error::NotFound)) => {
    1174            0 :             Err(ApiError::NotFound("unknown instance_id".into()))
    1175              :         }
    1176            0 :         Err(other) => Err(other.into()),
    1177              :     }
    1178            0 : }
    1179              : 
    1180              : /// Used as part of deployment scripts.
    1181              : ///
    1182              : /// Assumes information is only relayed to storage controller after first selecting an unique id on
    1183              : /// control plane database, which means we have an id field in the request and payload.
    1184            0 : async fn handle_upsert_safekeeper(mut req: Request<Body>) -> Result<Response<Body>, ApiError> {
    1185            0 :     check_permissions(&req, Scope::Admin)?;
    1186              : 
    1187            0 :     let body = json_request::<SafekeeperPersistence>(&mut req).await?;
    1188            0 :     let id = parse_request_param::<i64>(&req, "id")?;
    1189              : 
    1190            0 :     if id != body.id {
    1191              :         // it should be repeated
    1192            0 :         return Err(ApiError::BadRequest(anyhow::anyhow!(
    1193            0 :             "id mismatch: url={id:?}, body={:?}",
    1194            0 :             body.id
    1195            0 :         )));
    1196            0 :     }
    1197              : 
    1198            0 :     let req = match maybe_forward(req).await {
    1199            0 :         ForwardOutcome::Forwarded(res) => {
    1200            0 :             return res;
    1201              :         }
    1202            0 :         ForwardOutcome::NotForwarded(req) => req,
    1203            0 :     };
    1204            0 : 
    1205            0 :     let state = get_state(&req);
    1206            0 : 
    1207            0 :     state.service.upsert_safekeeper(body).await?;
    1208              : 
    1209            0 :     Ok(Response::builder()
    1210            0 :         .status(StatusCode::NO_CONTENT)
    1211            0 :         .body(Body::empty())
    1212            0 :         .unwrap())
    1213            0 : }
    1214              : 
    1215              : /// Common wrapper for request handlers that call into Service and will operate on tenants: they must only
    1216              : /// be allowed to run if Service has finished its initial reconciliation.
    1217            0 : async fn tenant_service_handler<R, H>(
    1218            0 :     request: Request<Body>,
    1219            0 :     handler: H,
    1220            0 :     request_name: RequestName,
    1221            0 : ) -> R::Output
    1222            0 : where
    1223            0 :     R: std::future::Future<Output = Result<Response<Body>, ApiError>> + Send + 'static,
    1224            0 :     H: FnOnce(Arc<Service>, Request<Body>) -> R + Send + Sync + 'static,
    1225            0 : {
    1226            0 :     let state = get_state(&request);
    1227            0 :     let service = state.service.clone();
    1228            0 : 
    1229            0 :     let startup_complete = service.startup_complete.clone();
    1230            0 :     if tokio::time::timeout(STARTUP_RECONCILE_TIMEOUT, startup_complete.wait())
    1231            0 :         .await
    1232            0 :         .is_err()
    1233              :     {
    1234              :         // This shouldn't happen: it is the responsibilty of [`Service::startup_reconcile`] to use appropriate
    1235              :         // timeouts around its remote calls, to bound its runtime.
    1236            0 :         return Err(ApiError::Timeout(
    1237            0 :             "Timed out waiting for service readiness".into(),
    1238            0 :         ));
    1239            0 :     }
    1240            0 : 
    1241            0 :     named_request_span(
    1242            0 :         request,
    1243            0 :         |request| async move { handler(service, request).await },
    1244            0 :         request_name,
    1245            0 :     )
    1246            0 :     .await
    1247            0 : }
    1248              : 
    1249              : /// Check if the required scope is held in the request's token, or if the request has
    1250              : /// a token with 'admin' scope then always permit it.
    1251            0 : fn check_permissions(request: &Request<Body>, required_scope: Scope) -> Result<(), ApiError> {
    1252            0 :     check_permission_with(request, |claims| {
    1253            0 :         match crate::auth::check_permission(claims, required_scope) {
    1254            0 :             Err(e) => match crate::auth::check_permission(claims, Scope::Admin) {
    1255            0 :                 Ok(()) => Ok(()),
    1256            0 :                 Err(_) => Err(e),
    1257              :             },
    1258            0 :             Ok(()) => Ok(()),
    1259              :         }
    1260            0 :     })
    1261            0 : }
    1262              : 
    1263              : #[derive(Clone, Debug)]
    1264              : struct RequestMeta {
    1265              :     method: hyper::http::Method,
    1266              :     at: Instant,
    1267              : }
    1268              : 
    1269            0 : pub fn prologue_leadership_status_check_middleware<
    1270            0 :     B: hyper::body::HttpBody + Send + Sync + 'static,
    1271            0 : >() -> Middleware<B, ApiError> {
    1272            0 :     Middleware::pre(move |req| async move {
    1273            0 :         let state = get_state(&req);
    1274            0 :         let leadership_status = state.service.get_leadership_status();
    1275              : 
    1276              :         enum AllowedRoutes<'a> {
    1277              :             All,
    1278              :             Some(Vec<&'a str>),
    1279              :         }
    1280              : 
    1281            0 :         let allowed_routes = match leadership_status {
    1282            0 :             LeadershipStatus::Leader => AllowedRoutes::All,
    1283            0 :             LeadershipStatus::SteppedDown => AllowedRoutes::All,
    1284              :             LeadershipStatus::Candidate => {
    1285            0 :                 AllowedRoutes::Some(["/ready", "/status", "/metrics"].to_vec())
    1286              :             }
    1287              :         };
    1288              : 
    1289            0 :         let uri = req.uri().to_string();
    1290            0 :         match allowed_routes {
    1291            0 :             AllowedRoutes::All => Ok(req),
    1292            0 :             AllowedRoutes::Some(allowed) if allowed.contains(&uri.as_str()) => Ok(req),
    1293              :             _ => {
    1294            0 :                 tracing::info!(
    1295            0 :                     "Request {} not allowed due to current leadership state",
    1296            0 :                     req.uri()
    1297              :                 );
    1298              : 
    1299            0 :                 Err(ApiError::ResourceUnavailable(
    1300            0 :                     format!("Current leadership status is {leadership_status}").into(),
    1301            0 :                 ))
    1302              :             }
    1303              :         }
    1304            0 :     })
    1305            0 : }
    1306              : 
    1307            0 : fn prologue_metrics_middleware<B: hyper::body::HttpBody + Send + Sync + 'static>(
    1308            0 : ) -> Middleware<B, ApiError> {
    1309            0 :     Middleware::pre(move |req| async move {
    1310            0 :         let meta = RequestMeta {
    1311            0 :             method: req.method().clone(),
    1312            0 :             at: Instant::now(),
    1313            0 :         };
    1314            0 : 
    1315            0 :         req.set_context(meta);
    1316            0 : 
    1317            0 :         Ok(req)
    1318            0 :     })
    1319            0 : }
    1320              : 
    1321            0 : fn epilogue_metrics_middleware<B: hyper::body::HttpBody + Send + Sync + 'static>(
    1322            0 : ) -> Middleware<B, ApiError> {
    1323            0 :     Middleware::post_with_info(move |resp, req_info| async move {
    1324            0 :         let request_name = match req_info.context::<RequestName>() {
    1325            0 :             Some(name) => name,
    1326              :             None => {
    1327            0 :                 return Ok(resp);
    1328              :             }
    1329              :         };
    1330              : 
    1331            0 :         if let Some(meta) = req_info.context::<RequestMeta>() {
    1332            0 :             let status = &crate::metrics::METRICS_REGISTRY
    1333            0 :                 .metrics_group
    1334            0 :                 .storage_controller_http_request_status;
    1335            0 :             let latency = &crate::metrics::METRICS_REGISTRY
    1336            0 :                 .metrics_group
    1337            0 :                 .storage_controller_http_request_latency;
    1338            0 : 
    1339            0 :             status.inc(HttpRequestStatusLabelGroup {
    1340            0 :                 path: request_name.0,
    1341            0 :                 method: meta.method.clone().into(),
    1342            0 :                 status: crate::metrics::StatusCode(resp.status()),
    1343            0 :             });
    1344            0 : 
    1345            0 :             latency.observe(
    1346            0 :                 HttpRequestLatencyLabelGroup {
    1347            0 :                     path: request_name.0,
    1348            0 :                     method: meta.method.into(),
    1349            0 :                 },
    1350            0 :                 meta.at.elapsed().as_secs_f64(),
    1351            0 :             );
    1352            0 :         }
    1353            0 :         Ok(resp)
    1354            0 :     })
    1355            0 : }
    1356              : 
    1357            0 : pub async fn measured_metrics_handler(req: Request<Body>) -> Result<Response<Body>, ApiError> {
    1358              :     pub const TEXT_FORMAT: &str = "text/plain; version=0.0.4";
    1359              : 
    1360            0 :     let req = match maybe_forward(req).await {
    1361            0 :         ForwardOutcome::Forwarded(res) => {
    1362            0 :             return res;
    1363              :         }
    1364            0 :         ForwardOutcome::NotForwarded(req) => req,
    1365            0 :     };
    1366            0 : 
    1367            0 :     let state = get_state(&req);
    1368            0 :     let payload = crate::metrics::METRICS_REGISTRY.encode(&state.neon_metrics);
    1369            0 :     let response = Response::builder()
    1370            0 :         .status(200)
    1371            0 :         .header(CONTENT_TYPE, TEXT_FORMAT)
    1372            0 :         .body(payload.into())
    1373            0 :         .unwrap();
    1374            0 : 
    1375            0 :     Ok(response)
    1376            0 : }
    1377              : 
    1378              : #[derive(Clone)]
    1379              : struct RequestName(&'static str);
    1380              : 
    1381            0 : async fn named_request_span<R, H>(
    1382            0 :     request: Request<Body>,
    1383            0 :     handler: H,
    1384            0 :     name: RequestName,
    1385            0 : ) -> R::Output
    1386            0 : where
    1387            0 :     R: Future<Output = Result<Response<Body>, ApiError>> + Send + 'static,
    1388            0 :     H: FnOnce(Request<Body>) -> R + Send + Sync + 'static,
    1389            0 : {
    1390            0 :     request.set_context(name);
    1391            0 :     request_span(request, handler).await
    1392            0 : }
    1393              : 
    1394              : enum ForwardOutcome {
    1395              :     Forwarded(Result<Response<Body>, ApiError>),
    1396              :     NotForwarded(Request<Body>),
    1397              : }
    1398              : 
    1399              : /// Potentially forward the request to the current storage controler leader.
    1400              : /// More specifically we forward when:
    1401              : /// 1. Request is not one of ["/control/v1/step_down", "/status", "/ready", "/metrics"]
    1402              : /// 2. Current instance is in [`LeadershipStatus::SteppedDown`] state
    1403              : /// 3. There is a leader in the database to forward to
    1404              : /// 4. Leader from step (3) is not the current instance
    1405              : ///
    1406              : /// Why forward?
    1407              : /// It turns out that we can't rely on external orchestration to promptly route trafic to the
    1408              : /// new leader. This is downtime inducing. Forwarding provides a safe way out.
    1409              : ///
    1410              : /// Why is it safe?
    1411              : /// If a storcon instance is persisted in the database, then we know that it is the current leader.
    1412              : /// There's one exception: time between handling step-down request and the new leader updating the
    1413              : /// database.
    1414              : ///
    1415              : /// Let's treat the happy case first. The stepped down node does not produce any side effects,
    1416              : /// since all request handling happens on the leader.
    1417              : ///
    1418              : /// As for the edge case, we are guaranteed to always have a maximum of two running instances.
    1419              : /// Hence, if we are in the edge case scenario the leader persisted in the database is the
    1420              : /// stepped down instance that received the request. Condition (4) above covers this scenario.
    1421            0 : async fn maybe_forward(req: Request<Body>) -> ForwardOutcome {
    1422              :     const NOT_FOR_FORWARD: [&str; 4] = ["/control/v1/step_down", "/status", "/ready", "/metrics"];
    1423              : 
    1424            0 :     let uri = req.uri().to_string();
    1425            0 :     let uri_for_forward = !NOT_FOR_FORWARD.contains(&uri.as_str());
    1426            0 : 
    1427            0 :     let state = get_state(&req);
    1428            0 :     let leadership_status = state.service.get_leadership_status();
    1429            0 : 
    1430            0 :     if leadership_status != LeadershipStatus::SteppedDown || !uri_for_forward {
    1431            0 :         return ForwardOutcome::NotForwarded(req);
    1432            0 :     }
    1433              : 
    1434            0 :     let leader = state.service.get_leader().await;
    1435            0 :     let leader = {
    1436            0 :         match leader {
    1437            0 :             Ok(Some(leader)) => leader,
    1438              :             Ok(None) => {
    1439            0 :                 return ForwardOutcome::Forwarded(Err(ApiError::ResourceUnavailable(
    1440            0 :                     "No leader to forward to while in stepped down state".into(),
    1441            0 :                 )));
    1442              :             }
    1443            0 :             Err(err) => {
    1444            0 :                 return ForwardOutcome::Forwarded(Err(ApiError::InternalServerError(
    1445            0 :                     anyhow::anyhow!(
    1446            0 :                         "Failed to get leader for forwarding while in stepped down state: {err}"
    1447            0 :                     ),
    1448            0 :                 )));
    1449              :             }
    1450              :         }
    1451              :     };
    1452              : 
    1453            0 :     let cfg = state.service.get_config();
    1454            0 :     if let Some(ref self_addr) = cfg.address_for_peers {
    1455            0 :         let leader_addr = match Uri::from_str(leader.address.as_str()) {
    1456            0 :             Ok(uri) => uri,
    1457            0 :             Err(err) => {
    1458            0 :                 return ForwardOutcome::Forwarded(Err(ApiError::InternalServerError(
    1459            0 :                     anyhow::anyhow!(
    1460            0 :                     "Failed to parse leader uri for forwarding while in stepped down state: {err}"
    1461            0 :                 ),
    1462            0 :                 )));
    1463              :             }
    1464              :         };
    1465              : 
    1466            0 :         if *self_addr == leader_addr {
    1467            0 :             return ForwardOutcome::Forwarded(Err(ApiError::InternalServerError(anyhow::anyhow!(
    1468            0 :                 "Leader is stepped down instance"
    1469            0 :             ))));
    1470            0 :         }
    1471            0 :     }
    1472              : 
    1473            0 :     tracing::info!("Forwarding {} to leader at {}", uri, leader.address);
    1474              : 
    1475              :     // Use [`RECONCILE_TIMEOUT`] as the max amount of time a request should block for and
    1476              :     // include some leeway to get the timeout for proxied requests.
    1477              :     const PROXIED_REQUEST_TIMEOUT: Duration = Duration::from_secs(RECONCILE_TIMEOUT.as_secs() + 10);
    1478            0 :     let client = reqwest::ClientBuilder::new()
    1479            0 :         .timeout(PROXIED_REQUEST_TIMEOUT)
    1480            0 :         .build();
    1481            0 :     let client = match client {
    1482            0 :         Ok(client) => client,
    1483            0 :         Err(err) => {
    1484            0 :             return ForwardOutcome::Forwarded(Err(ApiError::InternalServerError(anyhow::anyhow!(
    1485            0 :                 "Failed to build leader client for forwarding while in stepped down state: {err}"
    1486            0 :             ))));
    1487              :         }
    1488              :     };
    1489              : 
    1490            0 :     let request: reqwest::Request = match convert_request(req, &client, leader.address).await {
    1491            0 :         Ok(r) => r,
    1492            0 :         Err(err) => {
    1493            0 :             return ForwardOutcome::Forwarded(Err(ApiError::InternalServerError(anyhow::anyhow!(
    1494            0 :                 "Failed to convert request for forwarding while in stepped down state: {err}"
    1495            0 :             ))));
    1496              :         }
    1497              :     };
    1498              : 
    1499            0 :     let response = match client.execute(request).await {
    1500            0 :         Ok(r) => r,
    1501            0 :         Err(err) => {
    1502            0 :             return ForwardOutcome::Forwarded(Err(ApiError::InternalServerError(anyhow::anyhow!(
    1503            0 :                 "Failed to forward while in stepped down state: {err}"
    1504            0 :             ))));
    1505              :         }
    1506              :     };
    1507              : 
    1508            0 :     ForwardOutcome::Forwarded(convert_response(response).await)
    1509            0 : }
    1510              : 
    1511              : /// Convert a [`reqwest::Response`] to a [hyper::Response`] by passing through
    1512              : /// a stable representation (string, bytes or integer)
    1513              : ///
    1514              : /// Ideally, we would not have to do this since both types use the http crate
    1515              : /// under the hood. However, they use different versions of the crate and keeping
    1516              : /// second order dependencies in sync is difficult.
    1517            0 : async fn convert_response(resp: reqwest::Response) -> Result<hyper::Response<Body>, ApiError> {
    1518              :     use std::str::FromStr;
    1519              : 
    1520            0 :     let mut builder = hyper::Response::builder().status(resp.status().as_u16());
    1521            0 :     for (key, value) in resp.headers().into_iter() {
    1522            0 :         let key = hyper::header::HeaderName::from_str(key.as_str()).map_err(|err| {
    1523            0 :             ApiError::InternalServerError(anyhow::anyhow!("Response conversion failed: {err}"))
    1524            0 :         })?;
    1525              : 
    1526            0 :         let value = hyper::header::HeaderValue::from_bytes(value.as_bytes()).map_err(|err| {
    1527            0 :             ApiError::InternalServerError(anyhow::anyhow!("Response conversion failed: {err}"))
    1528            0 :         })?;
    1529              : 
    1530            0 :         builder = builder.header(key, value);
    1531              :     }
    1532              : 
    1533            0 :     let body = http::Body::wrap_stream(resp.bytes_stream());
    1534            0 : 
    1535            0 :     builder.body(body).map_err(|err| {
    1536            0 :         ApiError::InternalServerError(anyhow::anyhow!("Response conversion failed: {err}"))
    1537            0 :     })
    1538            0 : }
    1539              : 
    1540              : /// Convert a [`reqwest::Request`] to a [hyper::Request`] by passing through
    1541              : /// a stable representation (string, bytes or integer)
    1542              : ///
    1543              : /// See [`convert_response`] for why we are doing it this way.
    1544            0 : async fn convert_request(
    1545            0 :     req: hyper::Request<Body>,
    1546            0 :     client: &reqwest::Client,
    1547            0 :     to_address: String,
    1548            0 : ) -> Result<reqwest::Request, ApiError> {
    1549              :     use std::str::FromStr;
    1550              : 
    1551            0 :     let (parts, body) = req.into_parts();
    1552            0 :     let method = reqwest::Method::from_str(parts.method.as_str()).map_err(|err| {
    1553            0 :         ApiError::InternalServerError(anyhow::anyhow!("Request conversion failed: {err}"))
    1554            0 :     })?;
    1555              : 
    1556            0 :     let path_and_query = parts.uri.path_and_query().ok_or_else(|| {
    1557            0 :         ApiError::InternalServerError(anyhow::anyhow!(
    1558            0 :             "Request conversion failed: no path and query"
    1559            0 :         ))
    1560            0 :     })?;
    1561              : 
    1562            0 :     let uri = reqwest::Url::from_str(
    1563            0 :         format!(
    1564            0 :             "{}{}",
    1565            0 :             to_address.trim_end_matches("/"),
    1566            0 :             path_and_query.as_str()
    1567            0 :         )
    1568            0 :         .as_str(),
    1569            0 :     )
    1570            0 :     .map_err(|err| {
    1571            0 :         ApiError::InternalServerError(anyhow::anyhow!("Request conversion failed: {err}"))
    1572            0 :     })?;
    1573              : 
    1574            0 :     let mut headers = reqwest::header::HeaderMap::new();
    1575            0 :     for (key, value) in parts.headers.into_iter() {
    1576            0 :         let key = match key {
    1577            0 :             Some(k) => k,
    1578              :             None => {
    1579            0 :                 continue;
    1580              :             }
    1581              :         };
    1582              : 
    1583            0 :         let key = reqwest::header::HeaderName::from_str(key.as_str()).map_err(|err| {
    1584            0 :             ApiError::InternalServerError(anyhow::anyhow!("Request conversion failed: {err}"))
    1585            0 :         })?;
    1586              : 
    1587            0 :         let value = reqwest::header::HeaderValue::from_bytes(value.as_bytes()).map_err(|err| {
    1588            0 :             ApiError::InternalServerError(anyhow::anyhow!("Request conversion failed: {err}"))
    1589            0 :         })?;
    1590              : 
    1591            0 :         headers.insert(key, value);
    1592              :     }
    1593              : 
    1594            0 :     let body = hyper::body::to_bytes(body).await.map_err(|err| {
    1595            0 :         ApiError::InternalServerError(anyhow::anyhow!("Request conversion failed: {err}"))
    1596            0 :     })?;
    1597              : 
    1598            0 :     client
    1599            0 :         .request(method, uri)
    1600            0 :         .headers(headers)
    1601            0 :         .body(body)
    1602            0 :         .build()
    1603            0 :         .map_err(|err| {
    1604            0 :             ApiError::InternalServerError(anyhow::anyhow!("Request conversion failed: {err}"))
    1605            0 :         })
    1606            0 : }
    1607              : 
    1608            0 : pub fn make_router(
    1609            0 :     service: Arc<Service>,
    1610            0 :     auth: Option<Arc<SwappableJwtAuth>>,
    1611            0 :     build_info: BuildInfo,
    1612            0 : ) -> RouterBuilder<hyper::Body, ApiError> {
    1613            0 :     let mut router = endpoint::make_router()
    1614            0 :         .middleware(prologue_leadership_status_check_middleware())
    1615            0 :         .middleware(prologue_metrics_middleware())
    1616            0 :         .middleware(epilogue_metrics_middleware());
    1617            0 :     if auth.is_some() {
    1618            0 :         router = router.middleware(auth_middleware(|request| {
    1619            0 :             let state = get_state(request);
    1620            0 :             if state.allowlist_routes.contains(request.uri()) {
    1621            0 :                 None
    1622              :             } else {
    1623            0 :                 state.auth.as_deref()
    1624              :             }
    1625            0 :         }));
    1626            0 :     }
    1627              : 
    1628            0 :     router
    1629            0 :         .data(Arc::new(HttpState::new(service, auth, build_info)))
    1630            0 :         .get("/metrics", |r| {
    1631            0 :             named_request_span(r, measured_metrics_handler, RequestName("metrics"))
    1632            0 :         })
    1633            0 :         // Non-prefixed generic endpoints (status, metrics)
    1634            0 :         .get("/status", |r| {
    1635            0 :             named_request_span(r, handle_status, RequestName("status"))
    1636            0 :         })
    1637            0 :         .get("/ready", |r| {
    1638            0 :             named_request_span(r, handle_ready, RequestName("ready"))
    1639            0 :         })
    1640            0 :         // Upcalls for the pageserver: point the pageserver's `control_plane_api` config to this prefix
    1641            0 :         .post("/upcall/v1/re-attach", |r| {
    1642            0 :             named_request_span(r, handle_re_attach, RequestName("upcall_v1_reattach"))
    1643            0 :         })
    1644            0 :         .post("/upcall/v1/validate", |r| {
    1645            0 :             named_request_span(r, handle_validate, RequestName("upcall_v1_validate"))
    1646            0 :         })
    1647            0 :         // Test/dev/debug endpoints
    1648            0 :         .post("/debug/v1/attach-hook", |r| {
    1649            0 :             named_request_span(r, handle_attach_hook, RequestName("debug_v1_attach_hook"))
    1650            0 :         })
    1651            0 :         .post("/debug/v1/inspect", |r| {
    1652            0 :             named_request_span(r, handle_inspect, RequestName("debug_v1_inspect"))
    1653            0 :         })
    1654            0 :         .post("/debug/v1/tenant/:tenant_id/drop", |r| {
    1655            0 :             named_request_span(r, handle_tenant_drop, RequestName("debug_v1_tenant_drop"))
    1656            0 :         })
    1657            0 :         .post("/debug/v1/node/:node_id/drop", |r| {
    1658            0 :             named_request_span(r, handle_node_drop, RequestName("debug_v1_node_drop"))
    1659            0 :         })
    1660            0 :         .post("/debug/v1/tenant/:tenant_id/import", |r| {
    1661            0 :             named_request_span(
    1662            0 :                 r,
    1663            0 :                 handle_tenant_import,
    1664            0 :                 RequestName("debug_v1_tenant_import"),
    1665            0 :             )
    1666            0 :         })
    1667            0 :         .get("/debug/v1/tenant", |r| {
    1668            0 :             named_request_span(r, handle_tenants_dump, RequestName("debug_v1_tenant"))
    1669            0 :         })
    1670            0 :         .get("/debug/v1/tenant/:tenant_id/locate", |r| {
    1671            0 :             tenant_service_handler(
    1672            0 :                 r,
    1673            0 :                 handle_tenant_locate,
    1674            0 :                 RequestName("debug_v1_tenant_locate"),
    1675            0 :             )
    1676            0 :         })
    1677            0 :         .get("/debug/v1/scheduler", |r| {
    1678            0 :             named_request_span(r, handle_scheduler_dump, RequestName("debug_v1_scheduler"))
    1679            0 :         })
    1680            0 :         .post("/debug/v1/consistency_check", |r| {
    1681            0 :             named_request_span(
    1682            0 :                 r,
    1683            0 :                 handle_consistency_check,
    1684            0 :                 RequestName("debug_v1_consistency_check"),
    1685            0 :             )
    1686            0 :         })
    1687            0 :         .post("/debug/v1/reconcile_all", |r| {
    1688            0 :             request_span(r, handle_reconcile_all)
    1689            0 :         })
    1690            0 :         .put("/debug/v1/failpoints", |r| {
    1691            0 :             request_span(r, |r| failpoints_handler(r, CancellationToken::new()))
    1692            0 :         })
    1693            0 :         // Node operations
    1694            0 :         .post("/control/v1/node", |r| {
    1695            0 :             named_request_span(r, handle_node_register, RequestName("control_v1_node"))
    1696            0 :         })
    1697            0 :         .delete("/control/v1/node/:node_id", |r| {
    1698            0 :             named_request_span(r, handle_node_delete, RequestName("control_v1_node_delete"))
    1699            0 :         })
    1700            0 :         .get("/control/v1/node", |r| {
    1701            0 :             named_request_span(r, handle_node_list, RequestName("control_v1_node"))
    1702            0 :         })
    1703            0 :         .put("/control/v1/node/:node_id/config", |r| {
    1704            0 :             named_request_span(
    1705            0 :                 r,
    1706            0 :                 handle_node_configure,
    1707            0 :                 RequestName("control_v1_node_config"),
    1708            0 :             )
    1709            0 :         })
    1710            0 :         .get("/control/v1/node/:node_id", |r| {
    1711            0 :             named_request_span(r, handle_node_status, RequestName("control_v1_node_status"))
    1712            0 :         })
    1713            0 :         .get("/control/v1/node/:node_id/shards", |r| {
    1714            0 :             named_request_span(
    1715            0 :                 r,
    1716            0 :                 handle_node_shards,
    1717            0 :                 RequestName("control_v1_node_describe"),
    1718            0 :             )
    1719            0 :         })
    1720            0 :         .get("/control/v1/leader", |r| {
    1721            0 :             named_request_span(r, handle_get_leader, RequestName("control_v1_get_leader"))
    1722            0 :         })
    1723            0 :         .put("/control/v1/node/:node_id/drain", |r| {
    1724            0 :             named_request_span(r, handle_node_drain, RequestName("control_v1_node_drain"))
    1725            0 :         })
    1726            0 :         .delete("/control/v1/node/:node_id/drain", |r| {
    1727            0 :             named_request_span(
    1728            0 :                 r,
    1729            0 :                 handle_cancel_node_drain,
    1730            0 :                 RequestName("control_v1_cancel_node_drain"),
    1731            0 :             )
    1732            0 :         })
    1733            0 :         .put("/control/v1/node/:node_id/fill", |r| {
    1734            0 :             named_request_span(r, handle_node_fill, RequestName("control_v1_node_fill"))
    1735            0 :         })
    1736            0 :         .delete("/control/v1/node/:node_id/fill", |r| {
    1737            0 :             named_request_span(
    1738            0 :                 r,
    1739            0 :                 handle_cancel_node_fill,
    1740            0 :                 RequestName("control_v1_cancel_node_fill"),
    1741            0 :             )
    1742            0 :         })
    1743            0 :         // Metadata health operations
    1744            0 :         .post("/control/v1/metadata_health/update", |r| {
    1745            0 :             named_request_span(
    1746            0 :                 r,
    1747            0 :                 handle_metadata_health_update,
    1748            0 :                 RequestName("control_v1_metadata_health_update"),
    1749            0 :             )
    1750            0 :         })
    1751            0 :         .get("/control/v1/metadata_health/unhealthy", |r| {
    1752            0 :             named_request_span(
    1753            0 :                 r,
    1754            0 :                 handle_metadata_health_list_unhealthy,
    1755            0 :                 RequestName("control_v1_metadata_health_list_unhealthy"),
    1756            0 :             )
    1757            0 :         })
    1758            0 :         .post("/control/v1/metadata_health/outdated", |r| {
    1759            0 :             named_request_span(
    1760            0 :                 r,
    1761            0 :                 handle_metadata_health_list_outdated,
    1762            0 :                 RequestName("control_v1_metadata_health_list_outdated"),
    1763            0 :             )
    1764            0 :         })
    1765            0 :         // Tenant Shard operations
    1766            0 :         .put("/control/v1/tenant/:tenant_shard_id/migrate", |r| {
    1767            0 :             tenant_service_handler(
    1768            0 :                 r,
    1769            0 :                 handle_tenant_shard_migrate,
    1770            0 :                 RequestName("control_v1_tenant_migrate"),
    1771            0 :             )
    1772            0 :         })
    1773            0 :         .put("/control/v1/tenant/:tenant_id/shard_split", |r| {
    1774            0 :             tenant_service_handler(
    1775            0 :                 r,
    1776            0 :                 handle_tenant_shard_split,
    1777            0 :                 RequestName("control_v1_tenant_shard_split"),
    1778            0 :             )
    1779            0 :         })
    1780            0 :         .get("/control/v1/tenant/:tenant_id", |r| {
    1781            0 :             tenant_service_handler(
    1782            0 :                 r,
    1783            0 :                 handle_tenant_describe,
    1784            0 :                 RequestName("control_v1_tenant_describe"),
    1785            0 :             )
    1786            0 :         })
    1787            0 :         .get("/control/v1/tenant", |r| {
    1788            0 :             tenant_service_handler(r, handle_tenant_list, RequestName("control_v1_tenant_list"))
    1789            0 :         })
    1790            0 :         .put("/control/v1/tenant/:tenant_id/policy", |r| {
    1791            0 :             named_request_span(
    1792            0 :                 r,
    1793            0 :                 handle_tenant_update_policy,
    1794            0 :                 RequestName("control_v1_tenant_policy"),
    1795            0 :             )
    1796            0 :         })
    1797            0 :         .put("/control/v1/preferred_azs", |r| {
    1798            0 :             named_request_span(
    1799            0 :                 r,
    1800            0 :                 handle_update_preferred_azs,
    1801            0 :                 RequestName("control_v1_preferred_azs"),
    1802            0 :             )
    1803            0 :         })
    1804            0 :         .put("/control/v1/step_down", |r| {
    1805            0 :             named_request_span(r, handle_step_down, RequestName("control_v1_step_down"))
    1806            0 :         })
    1807            0 :         .get("/control/v1/safekeeper/:id", |r| {
    1808            0 :             named_request_span(r, handle_get_safekeeper, RequestName("v1_safekeeper"))
    1809            0 :         })
    1810            0 :         .post("/control/v1/safekeeper/:id", |r| {
    1811            0 :             // id is in the body
    1812            0 :             named_request_span(r, handle_upsert_safekeeper, RequestName("v1_safekeeper"))
    1813            0 :         })
    1814            0 :         // Tenant operations
    1815            0 :         // The ^/v1/ endpoints act as a "Virtual Pageserver", enabling shard-naive clients to call into
    1816            0 :         // this service to manage tenants that actually consist of many tenant shards, as if they are a single entity.
    1817            0 :         .post("/v1/tenant", |r| {
    1818            0 :             tenant_service_handler(r, handle_tenant_create, RequestName("v1_tenant"))
    1819            0 :         })
    1820            0 :         .delete("/v1/tenant/:tenant_id", |r| {
    1821            0 :             tenant_service_handler(r, handle_tenant_delete, RequestName("v1_tenant"))
    1822            0 :         })
    1823            0 :         .put("/v1/tenant/config", |r| {
    1824            0 :             tenant_service_handler(r, handle_tenant_config_set, RequestName("v1_tenant_config"))
    1825            0 :         })
    1826            0 :         .get("/v1/tenant/:tenant_id/config", |r| {
    1827            0 :             tenant_service_handler(r, handle_tenant_config_get, RequestName("v1_tenant_config"))
    1828            0 :         })
    1829            0 :         .put("/v1/tenant/:tenant_shard_id/location_config", |r| {
    1830            0 :             tenant_service_handler(
    1831            0 :                 r,
    1832            0 :                 handle_tenant_location_config,
    1833            0 :                 RequestName("v1_tenant_location_config"),
    1834            0 :             )
    1835            0 :         })
    1836            0 :         .put("/v1/tenant/:tenant_id/time_travel_remote_storage", |r| {
    1837            0 :             tenant_service_handler(
    1838            0 :                 r,
    1839            0 :                 handle_tenant_time_travel_remote_storage,
    1840            0 :                 RequestName("v1_tenant_time_travel_remote_storage"),
    1841            0 :             )
    1842            0 :         })
    1843            0 :         .post("/v1/tenant/:tenant_id/secondary/download", |r| {
    1844            0 :             tenant_service_handler(
    1845            0 :                 r,
    1846            0 :                 handle_tenant_secondary_download,
    1847            0 :                 RequestName("v1_tenant_secondary_download"),
    1848            0 :             )
    1849            0 :         })
    1850            0 :         // Timeline operations
    1851            0 :         .delete("/v1/tenant/:tenant_id/timeline/:timeline_id", |r| {
    1852            0 :             tenant_service_handler(
    1853            0 :                 r,
    1854            0 :                 handle_tenant_timeline_delete,
    1855            0 :                 RequestName("v1_tenant_timeline"),
    1856            0 :             )
    1857            0 :         })
    1858            0 :         .post("/v1/tenant/:tenant_id/timeline", |r| {
    1859            0 :             tenant_service_handler(
    1860            0 :                 r,
    1861            0 :                 handle_tenant_timeline_create,
    1862            0 :                 RequestName("v1_tenant_timeline"),
    1863            0 :             )
    1864            0 :         })
    1865            0 :         .post(
    1866            0 :             "/v1/tenant/:tenant_id/timeline/:timeline_id/archival_config",
    1867            0 :             |r| {
    1868            0 :                 tenant_service_handler(
    1869            0 :                     r,
    1870            0 :                     handle_tenant_timeline_archival_config,
    1871            0 :                     RequestName("v1_tenant_timeline_archival_config"),
    1872            0 :                 )
    1873            0 :             },
    1874            0 :         )
    1875            0 :         .put(
    1876            0 :             "/v1/tenant/:tenant_id/timeline/:timeline_id/detach_ancestor",
    1877            0 :             |r| {
    1878            0 :                 tenant_service_handler(
    1879            0 :                     r,
    1880            0 :                     handle_tenant_timeline_detach_ancestor,
    1881            0 :                     RequestName("v1_tenant_timeline_detach_ancestor"),
    1882            0 :                 )
    1883            0 :             },
    1884            0 :         )
    1885            0 :         .post(
    1886            0 :             "/v1/tenant/:tenant_id/timeline/:timeline_id/block_gc",
    1887            0 :             |r| {
    1888            0 :                 tenant_service_handler(
    1889            0 :                     r,
    1890            0 :                     |s, r| handle_tenant_timeline_block_unblock_gc(s, r, BlockUnblock::Block),
    1891            0 :                     RequestName("v1_tenant_timeline_block_unblock_gc"),
    1892            0 :                 )
    1893            0 :             },
    1894            0 :         )
    1895            0 :         .post(
    1896            0 :             "/v1/tenant/:tenant_id/timeline/:timeline_id/unblock_gc",
    1897            0 :             |r| {
    1898            0 :                 tenant_service_handler(
    1899            0 :                     r,
    1900            0 :                     |s, r| handle_tenant_timeline_block_unblock_gc(s, r, BlockUnblock::Unblock),
    1901            0 :                     RequestName("v1_tenant_timeline_block_unblock_gc"),
    1902            0 :                 )
    1903            0 :             },
    1904            0 :         )
    1905            0 :         // Tenant detail GET passthrough to shard zero:
    1906            0 :         .get("/v1/tenant/:tenant_id", |r| {
    1907            0 :             tenant_service_handler(
    1908            0 :                 r,
    1909            0 :                 handle_tenant_timeline_passthrough,
    1910            0 :                 RequestName("v1_tenant_passthrough"),
    1911            0 :             )
    1912            0 :         })
    1913            0 :         // The `*` in the  URL is a wildcard: any tenant/timeline GET APIs on the pageserver
    1914            0 :         // are implicitly exposed here.  This must be last in the list to avoid
    1915            0 :         // taking precedence over other GET methods we might implement by hand.
    1916            0 :         .get("/v1/tenant/:tenant_id/*", |r| {
    1917            0 :             tenant_service_handler(
    1918            0 :                 r,
    1919            0 :                 handle_tenant_timeline_passthrough,
    1920            0 :                 RequestName("v1_tenant_passthrough"),
    1921            0 :             )
    1922            0 :         })
    1923            0 : }
        

Generated by: LCOV version 2.1-beta