LCOV - code coverage report
Current view: top level - pageserver/src/http - routes.rs (source / functions) Coverage Total Hit
Test: 691a4c28fe7169edd60b367c52d448a0a6605f1f.info Lines: 0.0 % 1936 0
Test Date: 2024-05-10 13:18:37 Functions: 0.0 % 612 0

            Line data    Source code
       1              : //!
       2              : //! Management HTTP API
       3              : //!
       4              : use std::collections::HashMap;
       5              : use std::str::FromStr;
       6              : use std::sync::Arc;
       7              : use std::time::Duration;
       8              : 
       9              : use anyhow::{anyhow, Context, Result};
      10              : use enumset::EnumSet;
      11              : use futures::TryFutureExt;
      12              : use humantime::format_rfc3339;
      13              : use hyper::header;
      14              : use hyper::StatusCode;
      15              : use hyper::{Body, Request, Response, Uri};
      16              : use metrics::launch_timestamp::LaunchTimestamp;
      17              : use pageserver_api::models::LocationConfig;
      18              : use pageserver_api::models::LocationConfigListResponse;
      19              : use pageserver_api::models::ShardParameters;
      20              : use pageserver_api::models::TenantDetails;
      21              : use pageserver_api::models::TenantLocationConfigResponse;
      22              : use pageserver_api::models::TenantScanRemoteStorageResponse;
      23              : use pageserver_api::models::TenantScanRemoteStorageShard;
      24              : use pageserver_api::models::TenantShardLocation;
      25              : use pageserver_api::models::TenantShardSplitRequest;
      26              : use pageserver_api::models::TenantShardSplitResponse;
      27              : use pageserver_api::models::TenantState;
      28              : use pageserver_api::models::{
      29              :     DownloadRemoteLayersTaskSpawnRequest, LocationConfigMode, TenantAttachRequest,
      30              :     TenantLoadRequest, TenantLocationConfigRequest,
      31              : };
      32              : use pageserver_api::shard::ShardCount;
      33              : use pageserver_api::shard::TenantShardId;
      34              : use remote_storage::DownloadError;
      35              : use remote_storage::GenericRemoteStorage;
      36              : use remote_storage::TimeTravelError;
      37              : use tenant_size_model::{SizeResult, StorageModel};
      38              : use tokio_util::sync::CancellationToken;
      39              : use tracing::*;
      40              : use utils::auth::JwtAuth;
      41              : use utils::failpoint_support::failpoints_handler;
      42              : use utils::http::endpoint::prometheus_metrics_handler;
      43              : use utils::http::endpoint::request_span;
      44              : use utils::http::json::json_request_or_empty_body;
      45              : use utils::http::request::{get_request_param, must_get_query_param, parse_query_param};
      46              : 
      47              : use crate::context::{DownloadBehavior, RequestContext};
      48              : use crate::deletion_queue::DeletionQueueClient;
      49              : use crate::metrics::{StorageTimeOperation, STORAGE_TIME_GLOBAL};
      50              : use crate::pgdatadir_mapping::LsnForTimestamp;
      51              : use crate::task_mgr::TaskKind;
      52              : use crate::tenant::config::{LocationConf, TenantConfOpt};
      53              : use crate::tenant::mgr::GetActiveTenantError;
      54              : use crate::tenant::mgr::{
      55              :     GetTenantError, TenantManager, TenantMapError, TenantMapInsertError, TenantSlotError,
      56              :     TenantSlotUpsertError, TenantStateError,
      57              : };
      58              : use crate::tenant::mgr::{TenantSlot, UpsertLocationError};
      59              : use crate::tenant::remote_timeline_client;
      60              : use crate::tenant::remote_timeline_client::download_index_part;
      61              : use crate::tenant::remote_timeline_client::list_remote_tenant_shards;
      62              : use crate::tenant::remote_timeline_client::list_remote_timelines;
      63              : use crate::tenant::secondary::SecondaryController;
      64              : use crate::tenant::size::ModelInputs;
      65              : use crate::tenant::storage_layer::LayerAccessStatsReset;
      66              : use crate::tenant::storage_layer::LayerName;
      67              : use crate::tenant::timeline::CompactFlags;
      68              : use crate::tenant::timeline::Timeline;
      69              : use crate::tenant::SpawnMode;
      70              : use crate::tenant::{LogicalSizeCalculationCause, PageReconstructError};
      71              : use crate::{config::PageServerConf, tenant::mgr};
      72              : use crate::{disk_usage_eviction_task, tenant};
      73              : use pageserver_api::models::{
      74              :     StatusResponse, TenantConfigRequest, TenantCreateRequest, TenantCreateResponse, TenantInfo,
      75              :     TimelineCreateRequest, TimelineGcRequest, TimelineInfo,
      76              : };
      77              : use utils::{
      78              :     auth::SwappableJwtAuth,
      79              :     generation::Generation,
      80              :     http::{
      81              :         endpoint::{self, attach_openapi_ui, auth_middleware, check_permission_with},
      82              :         error::{ApiError, HttpErrorBody},
      83              :         json::{json_request, json_response},
      84              :         request::parse_request_param,
      85              :         RequestExt, RouterBuilder,
      86              :     },
      87              :     id::{TenantId, TimelineId},
      88              :     lsn::Lsn,
      89              : };
      90              : 
      91              : // For APIs that require an Active tenant, how long should we block waiting for that state?
      92              : // This is not functionally necessary (clients will retry), but avoids generating a lot of
      93              : // failed API calls while tenants are activating.
      94              : #[cfg(not(feature = "testing"))]
      95              : pub(crate) const ACTIVE_TENANT_TIMEOUT: Duration = Duration::from_millis(5000);
      96              : 
      97              : // Tests run on slow/oversubscribed nodes, and may need to wait much longer for tenants to
      98              : // finish attaching, if calls to remote storage are slow.
      99              : #[cfg(feature = "testing")]
     100              : pub(crate) const ACTIVE_TENANT_TIMEOUT: Duration = Duration::from_millis(30000);
     101              : 
     102              : pub struct State {
     103              :     conf: &'static PageServerConf,
     104              :     tenant_manager: Arc<TenantManager>,
     105              :     auth: Option<Arc<SwappableJwtAuth>>,
     106              :     allowlist_routes: Vec<Uri>,
     107              :     remote_storage: Option<GenericRemoteStorage>,
     108              :     broker_client: storage_broker::BrokerClientChannel,
     109              :     disk_usage_eviction_state: Arc<disk_usage_eviction_task::State>,
     110              :     deletion_queue_client: DeletionQueueClient,
     111              :     secondary_controller: SecondaryController,
     112              :     latest_utilization: tokio::sync::Mutex<Option<(std::time::Instant, bytes::Bytes)>>,
     113              : }
     114              : 
     115              : impl State {
     116              :     #[allow(clippy::too_many_arguments)]
     117            0 :     pub fn new(
     118            0 :         conf: &'static PageServerConf,
     119            0 :         tenant_manager: Arc<TenantManager>,
     120            0 :         auth: Option<Arc<SwappableJwtAuth>>,
     121            0 :         remote_storage: Option<GenericRemoteStorage>,
     122            0 :         broker_client: storage_broker::BrokerClientChannel,
     123            0 :         disk_usage_eviction_state: Arc<disk_usage_eviction_task::State>,
     124            0 :         deletion_queue_client: DeletionQueueClient,
     125            0 :         secondary_controller: SecondaryController,
     126            0 :     ) -> anyhow::Result<Self> {
     127            0 :         let allowlist_routes = ["/v1/status", "/v1/doc", "/swagger.yml", "/metrics"]
     128            0 :             .iter()
     129            0 :             .map(|v| v.parse().unwrap())
     130            0 :             .collect::<Vec<_>>();
     131            0 :         Ok(Self {
     132            0 :             conf,
     133            0 :             tenant_manager,
     134            0 :             auth,
     135            0 :             allowlist_routes,
     136            0 :             remote_storage,
     137            0 :             broker_client,
     138            0 :             disk_usage_eviction_state,
     139            0 :             deletion_queue_client,
     140            0 :             secondary_controller,
     141            0 :             latest_utilization: Default::default(),
     142            0 :         })
     143            0 :     }
     144              : }
     145              : 
     146              : #[inline(always)]
     147            0 : fn get_state(request: &Request<Body>) -> &State {
     148            0 :     request
     149            0 :         .data::<Arc<State>>()
     150            0 :         .expect("unknown state type")
     151            0 :         .as_ref()
     152            0 : }
     153              : 
     154              : #[inline(always)]
     155            0 : fn get_config(request: &Request<Body>) -> &'static PageServerConf {
     156            0 :     get_state(request).conf
     157            0 : }
     158              : 
     159              : /// Check that the requester is authorized to operate on given tenant
     160            0 : fn check_permission(request: &Request<Body>, tenant_id: Option<TenantId>) -> Result<(), ApiError> {
     161            0 :     check_permission_with(request, |claims| {
     162            0 :         crate::auth::check_permission(claims, tenant_id)
     163            0 :     })
     164            0 : }
     165              : 
     166              : impl From<PageReconstructError> for ApiError {
     167            0 :     fn from(pre: PageReconstructError) -> ApiError {
     168            0 :         match pre {
     169            0 :             PageReconstructError::Other(pre) => ApiError::InternalServerError(pre),
     170            0 :             PageReconstructError::MissingKey(e) => {
     171            0 :                 ApiError::InternalServerError(anyhow::anyhow!("{e}"))
     172              :             }
     173              :             PageReconstructError::Cancelled => {
     174            0 :                 ApiError::InternalServerError(anyhow::anyhow!("request was cancelled"))
     175              :             }
     176              :             PageReconstructError::AncestorStopping(_) => {
     177            0 :                 ApiError::ResourceUnavailable(format!("{pre}").into())
     178              :             }
     179            0 :             PageReconstructError::AncestorLsnTimeout(e) => ApiError::Timeout(format!("{e}").into()),
     180            0 :             PageReconstructError::WalRedo(pre) => ApiError::InternalServerError(pre),
     181              :         }
     182            0 :     }
     183              : }
     184              : 
     185              : impl From<TenantMapInsertError> for ApiError {
     186            0 :     fn from(tmie: TenantMapInsertError) -> ApiError {
     187            0 :         match tmie {
     188            0 :             TenantMapInsertError::SlotError(e) => e.into(),
     189            0 :             TenantMapInsertError::SlotUpsertError(e) => e.into(),
     190            0 :             TenantMapInsertError::Other(e) => ApiError::InternalServerError(e),
     191              :         }
     192            0 :     }
     193              : }
     194              : 
     195              : impl From<TenantSlotError> for ApiError {
     196            0 :     fn from(e: TenantSlotError) -> ApiError {
     197            0 :         use TenantSlotError::*;
     198            0 :         match e {
     199            0 :             NotFound(tenant_id) => {
     200            0 :                 ApiError::NotFound(anyhow::anyhow!("NotFound: tenant {tenant_id}").into())
     201              :             }
     202            0 :             e @ AlreadyExists(_, _) => ApiError::Conflict(format!("{e}")),
     203              :             InProgress => {
     204            0 :                 ApiError::ResourceUnavailable("Tenant is being modified concurrently".into())
     205              :             }
     206            0 :             MapState(e) => e.into(),
     207              :         }
     208            0 :     }
     209              : }
     210              : 
     211              : impl From<TenantSlotUpsertError> for ApiError {
     212            0 :     fn from(e: TenantSlotUpsertError) -> ApiError {
     213            0 :         use TenantSlotUpsertError::*;
     214            0 :         match e {
     215            0 :             InternalError(e) => ApiError::InternalServerError(anyhow::anyhow!("{e}")),
     216            0 :             MapState(e) => e.into(),
     217            0 :             ShuttingDown(_) => ApiError::ShuttingDown,
     218              :         }
     219            0 :     }
     220              : }
     221              : 
     222              : impl From<UpsertLocationError> for ApiError {
     223            0 :     fn from(e: UpsertLocationError) -> ApiError {
     224            0 :         use UpsertLocationError::*;
     225            0 :         match e {
     226            0 :             BadRequest(e) => ApiError::BadRequest(e),
     227            0 :             Unavailable(_) => ApiError::ShuttingDown,
     228            0 :             e @ InProgress => ApiError::Conflict(format!("{e}")),
     229            0 :             Flush(e) | Other(e) => ApiError::InternalServerError(e),
     230              :         }
     231            0 :     }
     232              : }
     233              : 
     234              : impl From<TenantMapError> for ApiError {
     235            0 :     fn from(e: TenantMapError) -> ApiError {
     236            0 :         use TenantMapError::*;
     237            0 :         match e {
     238              :             StillInitializing | ShuttingDown => {
     239            0 :                 ApiError::ResourceUnavailable(format!("{e}").into())
     240            0 :             }
     241            0 :         }
     242            0 :     }
     243              : }
     244              : 
     245              : impl From<TenantStateError> for ApiError {
     246            0 :     fn from(tse: TenantStateError) -> ApiError {
     247            0 :         match tse {
     248              :             TenantStateError::IsStopping(_) => {
     249            0 :                 ApiError::ResourceUnavailable("Tenant is stopping".into())
     250              :             }
     251            0 :             TenantStateError::SlotError(e) => e.into(),
     252            0 :             TenantStateError::SlotUpsertError(e) => e.into(),
     253            0 :             TenantStateError::Other(e) => ApiError::InternalServerError(anyhow!(e)),
     254              :         }
     255            0 :     }
     256              : }
     257              : 
     258              : impl From<GetTenantError> for ApiError {
     259            0 :     fn from(tse: GetTenantError) -> ApiError {
     260            0 :         match tse {
     261            0 :             GetTenantError::NotFound(tid) => ApiError::NotFound(anyhow!("tenant {}", tid).into()),
     262              :             GetTenantError::NotActive(_) => {
     263              :                 // Why is this not `ApiError::NotFound`?
     264              :                 // Because we must be careful to never return 404 for a tenant if it does
     265              :                 // in fact exist locally. If we did, the caller could draw the conclusion
     266              :                 // that it can attach the tenant to another PS and we'd be in split-brain.
     267            0 :                 ApiError::ResourceUnavailable("Tenant not yet active".into())
     268              :             }
     269            0 :             GetTenantError::MapState(e) => ApiError::ResourceUnavailable(format!("{e}").into()),
     270              :         }
     271            0 :     }
     272              : }
     273              : 
     274              : impl From<GetActiveTenantError> for ApiError {
     275            0 :     fn from(e: GetActiveTenantError) -> ApiError {
     276            0 :         match e {
     277            0 :             GetActiveTenantError::Broken(reason) => {
     278            0 :                 ApiError::InternalServerError(anyhow!("tenant is broken: {}", reason))
     279              :             }
     280            0 :             GetActiveTenantError::WillNotBecomeActive(_) => ApiError::Conflict(format!("{}", e)),
     281            0 :             GetActiveTenantError::Cancelled => ApiError::ShuttingDown,
     282            0 :             GetActiveTenantError::NotFound(gte) => gte.into(),
     283              :             GetActiveTenantError::WaitForActiveTimeout { .. } => {
     284            0 :                 ApiError::ResourceUnavailable(format!("{}", e).into())
     285              :             }
     286              :         }
     287            0 :     }
     288              : }
     289              : 
     290              : impl From<crate::tenant::DeleteTimelineError> for ApiError {
     291            0 :     fn from(value: crate::tenant::DeleteTimelineError) -> Self {
     292            0 :         use crate::tenant::DeleteTimelineError::*;
     293            0 :         match value {
     294            0 :             NotFound => ApiError::NotFound(anyhow::anyhow!("timeline not found").into()),
     295            0 :             HasChildren(children) => ApiError::PreconditionFailed(
     296            0 :                 format!("Cannot delete timeline which has child timelines: {children:?}")
     297            0 :                     .into_boxed_str(),
     298            0 :             ),
     299            0 :             a @ AlreadyInProgress(_) => ApiError::Conflict(a.to_string()),
     300            0 :             Other(e) => ApiError::InternalServerError(e),
     301              :         }
     302            0 :     }
     303              : }
     304              : 
     305              : impl From<crate::tenant::mgr::DeleteTimelineError> for ApiError {
     306            0 :     fn from(value: crate::tenant::mgr::DeleteTimelineError) -> Self {
     307              :         use crate::tenant::mgr::DeleteTimelineError::*;
     308            0 :         match value {
     309              :             // Report Precondition failed so client can distinguish between
     310              :             // "tenant is missing" case from "timeline is missing"
     311            0 :             Tenant(GetTenantError::NotFound(..)) => ApiError::PreconditionFailed(
     312            0 :                 "Requested tenant is missing".to_owned().into_boxed_str(),
     313            0 :             ),
     314            0 :             Tenant(t) => ApiError::from(t),
     315            0 :             Timeline(t) => ApiError::from(t),
     316              :         }
     317            0 :     }
     318              : }
     319              : 
     320              : impl From<crate::tenant::delete::DeleteTenantError> for ApiError {
     321            0 :     fn from(value: crate::tenant::delete::DeleteTenantError) -> Self {
     322            0 :         use crate::tenant::delete::DeleteTenantError::*;
     323            0 :         match value {
     324            0 :             Get(g) => ApiError::from(g),
     325            0 :             e @ AlreadyInProgress => ApiError::Conflict(e.to_string()),
     326            0 :             Timeline(t) => ApiError::from(t),
     327            0 :             NotAttached => ApiError::NotFound(anyhow::anyhow!("Tenant is not attached").into()),
     328            0 :             SlotError(e) => e.into(),
     329            0 :             SlotUpsertError(e) => e.into(),
     330            0 :             Other(o) => ApiError::InternalServerError(o),
     331            0 :             e @ InvalidState(_) => ApiError::PreconditionFailed(e.to_string().into_boxed_str()),
     332            0 :             Cancelled => ApiError::ShuttingDown,
     333              :         }
     334            0 :     }
     335              : }
     336              : 
     337              : // Helper function to construct a TimelineInfo struct for a timeline
     338            0 : async fn build_timeline_info(
     339            0 :     timeline: &Arc<Timeline>,
     340            0 :     include_non_incremental_logical_size: bool,
     341            0 :     force_await_initial_logical_size: bool,
     342            0 :     ctx: &RequestContext,
     343            0 : ) -> anyhow::Result<TimelineInfo> {
     344            0 :     crate::tenant::debug_assert_current_span_has_tenant_and_timeline_id();
     345            0 : 
     346            0 :     if force_await_initial_logical_size {
     347            0 :         timeline.clone().await_initial_logical_size().await
     348            0 :     }
     349              : 
     350            0 :     let mut info = build_timeline_info_common(
     351            0 :         timeline,
     352            0 :         ctx,
     353            0 :         tenant::timeline::GetLogicalSizePriority::Background,
     354            0 :     )
     355            0 :     .await?;
     356            0 :     if include_non_incremental_logical_size {
     357              :         // XXX we should be using spawn_ondemand_logical_size_calculation here.
     358              :         // Otherwise, if someone deletes the timeline / detaches the tenant while
     359              :         // we're executing this function, we will outlive the timeline on-disk state.
     360              :         info.current_logical_size_non_incremental = Some(
     361            0 :             timeline
     362            0 :                 .get_current_logical_size_non_incremental(info.last_record_lsn, ctx)
     363            0 :                 .await?,
     364              :         );
     365            0 :     }
     366            0 :     Ok(info)
     367            0 : }
     368              : 
     369            0 : async fn build_timeline_info_common(
     370            0 :     timeline: &Arc<Timeline>,
     371            0 :     ctx: &RequestContext,
     372            0 :     logical_size_task_priority: tenant::timeline::GetLogicalSizePriority,
     373            0 : ) -> anyhow::Result<TimelineInfo> {
     374            0 :     crate::tenant::debug_assert_current_span_has_tenant_and_timeline_id();
     375            0 :     let initdb_lsn = timeline.initdb_lsn;
     376            0 :     let last_record_lsn = timeline.get_last_record_lsn();
     377            0 :     let (wal_source_connstr, last_received_msg_lsn, last_received_msg_ts) = {
     378            0 :         let guard = timeline.last_received_wal.lock().unwrap();
     379            0 :         if let Some(info) = guard.as_ref() {
     380            0 :             (
     381            0 :                 Some(format!("{:?}", info.wal_source_connconf)), // Password is hidden, but it's for statistics only.
     382            0 :                 Some(info.last_received_msg_lsn),
     383            0 :                 Some(info.last_received_msg_ts),
     384            0 :             )
     385              :         } else {
     386            0 :             (None, None, None)
     387              :         }
     388              :     };
     389              : 
     390            0 :     let ancestor_timeline_id = timeline.get_ancestor_timeline_id();
     391            0 :     let ancestor_lsn = match timeline.get_ancestor_lsn() {
     392            0 :         Lsn(0) => None,
     393            0 :         lsn @ Lsn(_) => Some(lsn),
     394              :     };
     395            0 :     let current_logical_size = timeline.get_current_logical_size(logical_size_task_priority, ctx);
     396            0 :     let current_physical_size = Some(timeline.layer_size_sum().await);
     397            0 :     let state = timeline.current_state();
     398            0 :     let remote_consistent_lsn_projected = timeline
     399            0 :         .get_remote_consistent_lsn_projected()
     400            0 :         .unwrap_or(Lsn(0));
     401            0 :     let remote_consistent_lsn_visible = timeline
     402            0 :         .get_remote_consistent_lsn_visible()
     403            0 :         .unwrap_or(Lsn(0));
     404            0 : 
     405            0 :     let walreceiver_status = timeline.walreceiver_status();
     406              : 
     407            0 :     let info = TimelineInfo {
     408            0 :         tenant_id: timeline.tenant_shard_id,
     409            0 :         timeline_id: timeline.timeline_id,
     410            0 :         ancestor_timeline_id,
     411            0 :         ancestor_lsn,
     412            0 :         disk_consistent_lsn: timeline.get_disk_consistent_lsn(),
     413            0 :         remote_consistent_lsn: remote_consistent_lsn_projected,
     414            0 :         remote_consistent_lsn_visible,
     415            0 :         initdb_lsn,
     416            0 :         last_record_lsn,
     417            0 :         prev_record_lsn: Some(timeline.get_prev_record_lsn()),
     418            0 :         latest_gc_cutoff_lsn: *timeline.get_latest_gc_cutoff_lsn(),
     419            0 :         current_logical_size: current_logical_size.size_dont_care_about_accuracy(),
     420            0 :         current_logical_size_is_accurate: match current_logical_size.accuracy() {
     421            0 :             tenant::timeline::logical_size::Accuracy::Approximate => false,
     422            0 :             tenant::timeline::logical_size::Accuracy::Exact => true,
     423              :         },
     424            0 :         directory_entries_counts: timeline.get_directory_metrics().to_vec(),
     425            0 :         current_physical_size,
     426            0 :         current_logical_size_non_incremental: None,
     427            0 :         timeline_dir_layer_file_size_sum: None,
     428            0 :         wal_source_connstr,
     429            0 :         last_received_msg_lsn,
     430            0 :         last_received_msg_ts,
     431            0 :         pg_version: timeline.pg_version,
     432            0 : 
     433            0 :         state,
     434            0 : 
     435            0 :         walreceiver_status,
     436            0 :     };
     437            0 :     Ok(info)
     438            0 : }
     439              : 
     440              : // healthcheck handler
     441            0 : async fn status_handler(
     442            0 :     request: Request<Body>,
     443            0 :     _cancel: CancellationToken,
     444            0 : ) -> Result<Response<Body>, ApiError> {
     445            0 :     check_permission(&request, None)?;
     446            0 :     let config = get_config(&request);
     447            0 :     json_response(StatusCode::OK, StatusResponse { id: config.id })
     448            0 : }
     449              : 
     450            0 : async fn reload_auth_validation_keys_handler(
     451            0 :     request: Request<Body>,
     452            0 :     _cancel: CancellationToken,
     453            0 : ) -> Result<Response<Body>, ApiError> {
     454            0 :     check_permission(&request, None)?;
     455            0 :     let config = get_config(&request);
     456            0 :     let state = get_state(&request);
     457            0 :     let Some(shared_auth) = &state.auth else {
     458            0 :         return json_response(StatusCode::BAD_REQUEST, ());
     459              :     };
     460              :     // unwrap is ok because check is performed when creating config, so path is set and exists
     461            0 :     let key_path = config.auth_validation_public_key_path.as_ref().unwrap();
     462            0 :     info!("Reloading public key(s) for verifying JWT tokens from {key_path:?}");
     463              : 
     464            0 :     match JwtAuth::from_key_path(key_path) {
     465            0 :         Ok(new_auth) => {
     466            0 :             shared_auth.swap(new_auth);
     467            0 :             json_response(StatusCode::OK, ())
     468              :         }
     469            0 :         Err(e) => {
     470            0 :             let err_msg = "Error reloading public keys";
     471            0 :             warn!("Error reloading public keys from {key_path:?}: {e:}");
     472            0 :             json_response(
     473            0 :                 StatusCode::INTERNAL_SERVER_ERROR,
     474            0 :                 HttpErrorBody::from_msg(err_msg.to_string()),
     475            0 :             )
     476              :         }
     477              :     }
     478            0 : }
     479              : 
     480            0 : async fn timeline_create_handler(
     481            0 :     mut request: Request<Body>,
     482            0 :     _cancel: CancellationToken,
     483            0 : ) -> Result<Response<Body>, ApiError> {
     484            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
     485            0 :     let request_data: TimelineCreateRequest = json_request(&mut request).await?;
     486            0 :     check_permission(&request, Some(tenant_shard_id.tenant_id))?;
     487              : 
     488            0 :     let new_timeline_id = request_data.new_timeline_id;
     489            0 : 
     490            0 :     let ctx = RequestContext::new(TaskKind::MgmtRequest, DownloadBehavior::Error);
     491            0 : 
     492            0 :     let state = get_state(&request);
     493              : 
     494            0 :     async {
     495            0 :         let tenant = state
     496            0 :             .tenant_manager
     497            0 :             .get_attached_tenant_shard(tenant_shard_id)?;
     498              : 
     499            0 :         tenant.wait_to_become_active(ACTIVE_TENANT_TIMEOUT).await?;
     500              : 
     501            0 :         if let Some(ancestor_id) = request_data.ancestor_timeline_id.as_ref() {
     502            0 :             tracing::info!(%ancestor_id, "starting to branch");
     503              :         } else {
     504            0 :             tracing::info!("bootstrapping");
     505              :         }
     506              : 
     507            0 :         match tenant
     508            0 :             .create_timeline(
     509            0 :                 new_timeline_id,
     510            0 :                 request_data.ancestor_timeline_id,
     511            0 :                 request_data.ancestor_start_lsn,
     512            0 :                 request_data.pg_version.unwrap_or(crate::DEFAULT_PG_VERSION),
     513            0 :                 request_data.existing_initdb_timeline_id,
     514            0 :                 state.broker_client.clone(),
     515            0 :                 &ctx,
     516            0 :             )
     517            0 :             .await
     518              :         {
     519            0 :             Ok(new_timeline) => {
     520              :                 // Created. Construct a TimelineInfo for it.
     521            0 :                 let timeline_info = build_timeline_info_common(
     522            0 :                     &new_timeline,
     523            0 :                     &ctx,
     524            0 :                     tenant::timeline::GetLogicalSizePriority::User,
     525            0 :                 )
     526            0 :                 .await
     527            0 :                 .map_err(ApiError::InternalServerError)?;
     528            0 :                 json_response(StatusCode::CREATED, timeline_info)
     529              :             }
     530            0 :             Err(_) if tenant.cancel.is_cancelled() => {
     531            0 :                 // In case we get some ugly error type during shutdown, cast it into a clean 503.
     532            0 :                 json_response(
     533            0 :                     StatusCode::SERVICE_UNAVAILABLE,
     534            0 :                     HttpErrorBody::from_msg("Tenant shutting down".to_string()),
     535            0 :                 )
     536              :             }
     537            0 :             Err(e @ tenant::CreateTimelineError::Conflict) => {
     538            0 :                 json_response(StatusCode::CONFLICT, HttpErrorBody::from_msg(e.to_string()))
     539              :             }
     540            0 :             Err(e @ tenant::CreateTimelineError::AlreadyCreating) => json_response(
     541            0 :                 StatusCode::TOO_MANY_REQUESTS,
     542            0 :                 HttpErrorBody::from_msg(e.to_string()),
     543            0 :             ),
     544            0 :             Err(tenant::CreateTimelineError::AncestorLsn(err)) => json_response(
     545            0 :                 StatusCode::NOT_ACCEPTABLE,
     546            0 :                 HttpErrorBody::from_msg(format!("{err:#}")),
     547            0 :             ),
     548            0 :             Err(e @ tenant::CreateTimelineError::AncestorNotActive) => json_response(
     549            0 :                 StatusCode::SERVICE_UNAVAILABLE,
     550            0 :                 HttpErrorBody::from_msg(e.to_string()),
     551            0 :             ),
     552            0 :             Err(tenant::CreateTimelineError::ShuttingDown) => json_response(
     553            0 :                 StatusCode::SERVICE_UNAVAILABLE,
     554            0 :                 HttpErrorBody::from_msg("tenant shutting down".to_string()),
     555            0 :             ),
     556            0 :             Err(tenant::CreateTimelineError::Other(err)) => Err(ApiError::InternalServerError(err)),
     557              :         }
     558            0 :     }
     559            0 :     .instrument(info_span!("timeline_create",
     560              :         tenant_id = %tenant_shard_id.tenant_id,
     561            0 :         shard_id = %tenant_shard_id.shard_slug(),
     562              :         timeline_id = %new_timeline_id,
     563              :         lsn=?request_data.ancestor_start_lsn,
     564              :         pg_version=?request_data.pg_version
     565              :     ))
     566            0 :     .await
     567            0 : }
     568              : 
     569            0 : async fn timeline_list_handler(
     570            0 :     request: Request<Body>,
     571            0 :     _cancel: CancellationToken,
     572            0 : ) -> Result<Response<Body>, ApiError> {
     573            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
     574            0 :     let include_non_incremental_logical_size: Option<bool> =
     575            0 :         parse_query_param(&request, "include-non-incremental-logical-size")?;
     576            0 :     let force_await_initial_logical_size: Option<bool> =
     577            0 :         parse_query_param(&request, "force-await-initial-logical-size")?;
     578            0 :     check_permission(&request, Some(tenant_shard_id.tenant_id))?;
     579              : 
     580            0 :     let state = get_state(&request);
     581            0 :     let ctx = RequestContext::new(TaskKind::MgmtRequest, DownloadBehavior::Download);
     582              : 
     583            0 :     let response_data = async {
     584            0 :         let tenant = state
     585            0 :             .tenant_manager
     586            0 :             .get_attached_tenant_shard(tenant_shard_id)?;
     587              : 
     588            0 :         tenant.wait_to_become_active(ACTIVE_TENANT_TIMEOUT).await?;
     589              : 
     590            0 :         let timelines = tenant.list_timelines();
     591            0 : 
     592            0 :         let mut response_data = Vec::with_capacity(timelines.len());
     593            0 :         for timeline in timelines {
     594            0 :             let timeline_info = build_timeline_info(
     595            0 :                 &timeline,
     596            0 :                 include_non_incremental_logical_size.unwrap_or(false),
     597            0 :                 force_await_initial_logical_size.unwrap_or(false),
     598            0 :                 &ctx,
     599            0 :             )
     600            0 :             .instrument(info_span!("build_timeline_info", timeline_id = %timeline.timeline_id))
     601            0 :             .await
     602            0 :             .context("Failed to convert tenant timeline {timeline_id} into the local one: {e:?}")
     603            0 :             .map_err(ApiError::InternalServerError)?;
     604              : 
     605            0 :             response_data.push(timeline_info);
     606              :         }
     607            0 :         Ok::<Vec<TimelineInfo>, ApiError>(response_data)
     608            0 :     }
     609            0 :     .instrument(info_span!("timeline_list",
     610              :                 tenant_id = %tenant_shard_id.tenant_id,
     611            0 :                 shard_id = %tenant_shard_id.shard_slug()))
     612            0 :     .await?;
     613              : 
     614            0 :     json_response(StatusCode::OK, response_data)
     615            0 : }
     616              : 
     617            0 : async fn timeline_preserve_initdb_handler(
     618            0 :     request: Request<Body>,
     619            0 :     _cancel: CancellationToken,
     620            0 : ) -> Result<Response<Body>, ApiError> {
     621            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
     622            0 :     let timeline_id: TimelineId = parse_request_param(&request, "timeline_id")?;
     623            0 :     check_permission(&request, Some(tenant_shard_id.tenant_id))?;
     624            0 :     let state = get_state(&request);
     625              : 
     626              :     // Part of the process for disaster recovery from safekeeper-stored WAL:
     627              :     // If we don't recover into a new timeline but want to keep the timeline ID,
     628              :     // then the initdb archive is deleted. This endpoint copies it to a different
     629              :     // location where timeline recreation cand find it.
     630              : 
     631            0 :     async {
     632            0 :         let tenant = state
     633            0 :             .tenant_manager
     634            0 :             .get_attached_tenant_shard(tenant_shard_id)?;
     635              : 
     636            0 :         let timeline = tenant
     637            0 :             .get_timeline(timeline_id, false)
     638            0 :             .map_err(|e| ApiError::NotFound(e.into()))?;
     639              : 
     640            0 :         timeline
     641            0 :             .preserve_initdb_archive()
     642            0 :             .await
     643            0 :             .context("preserving initdb archive")
     644            0 :             .map_err(ApiError::InternalServerError)?;
     645              : 
     646            0 :         Ok::<_, ApiError>(())
     647            0 :     }
     648            0 :     .instrument(info_span!("timeline_preserve_initdb_archive",
     649              :                 tenant_id = %tenant_shard_id.tenant_id,
     650            0 :                 shard_id = %tenant_shard_id.shard_slug(),
     651              :                 %timeline_id))
     652            0 :     .await?;
     653              : 
     654            0 :     json_response(StatusCode::OK, ())
     655            0 : }
     656              : 
     657            0 : async fn timeline_detail_handler(
     658            0 :     request: Request<Body>,
     659            0 :     _cancel: CancellationToken,
     660            0 : ) -> Result<Response<Body>, ApiError> {
     661            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
     662            0 :     let timeline_id: TimelineId = parse_request_param(&request, "timeline_id")?;
     663            0 :     let include_non_incremental_logical_size: Option<bool> =
     664            0 :         parse_query_param(&request, "include-non-incremental-logical-size")?;
     665            0 :     let force_await_initial_logical_size: Option<bool> =
     666            0 :         parse_query_param(&request, "force-await-initial-logical-size")?;
     667            0 :     check_permission(&request, Some(tenant_shard_id.tenant_id))?;
     668              : 
     669              :     // Logical size calculation needs downloading.
     670            0 :     let ctx = RequestContext::new(TaskKind::MgmtRequest, DownloadBehavior::Download);
     671            0 :     let state = get_state(&request);
     672              : 
     673            0 :     let timeline_info = async {
     674            0 :         let tenant = state
     675            0 :             .tenant_manager
     676            0 :             .get_attached_tenant_shard(tenant_shard_id)?;
     677              : 
     678            0 :         tenant.wait_to_become_active(ACTIVE_TENANT_TIMEOUT).await?;
     679              : 
     680            0 :         let timeline = tenant
     681            0 :             .get_timeline(timeline_id, false)
     682            0 :             .map_err(|e| ApiError::NotFound(e.into()))?;
     683              : 
     684            0 :         let timeline_info = build_timeline_info(
     685            0 :             &timeline,
     686            0 :             include_non_incremental_logical_size.unwrap_or(false),
     687            0 :             force_await_initial_logical_size.unwrap_or(false),
     688            0 :             &ctx,
     689            0 :         )
     690            0 :         .await
     691            0 :         .context("get local timeline info")
     692            0 :         .map_err(ApiError::InternalServerError)?;
     693              : 
     694            0 :         Ok::<_, ApiError>(timeline_info)
     695            0 :     }
     696            0 :     .instrument(info_span!("timeline_detail",
     697              :                 tenant_id = %tenant_shard_id.tenant_id,
     698            0 :                 shard_id = %tenant_shard_id.shard_slug(),
     699              :                 %timeline_id))
     700            0 :     .await?;
     701              : 
     702            0 :     json_response(StatusCode::OK, timeline_info)
     703            0 : }
     704              : 
     705            0 : async fn get_lsn_by_timestamp_handler(
     706            0 :     request: Request<Body>,
     707            0 :     cancel: CancellationToken,
     708            0 : ) -> Result<Response<Body>, ApiError> {
     709            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
     710            0 :     check_permission(&request, Some(tenant_shard_id.tenant_id))?;
     711            0 :     let state = get_state(&request);
     712            0 : 
     713            0 :     if !tenant_shard_id.is_shard_zero() {
     714              :         // Requires SLRU contents, which are only stored on shard zero
     715            0 :         return Err(ApiError::BadRequest(anyhow!(
     716            0 :             "Size calculations are only available on shard zero"
     717            0 :         )));
     718            0 :     }
     719              : 
     720            0 :     let timeline_id: TimelineId = parse_request_param(&request, "timeline_id")?;
     721            0 :     let timestamp_raw = must_get_query_param(&request, "timestamp")?;
     722            0 :     let timestamp = humantime::parse_rfc3339(&timestamp_raw)
     723            0 :         .with_context(|| format!("Invalid time: {:?}", timestamp_raw))
     724            0 :         .map_err(ApiError::BadRequest)?;
     725            0 :     let timestamp_pg = postgres_ffi::to_pg_timestamp(timestamp);
     726            0 : 
     727            0 :     let ctx = RequestContext::new(TaskKind::MgmtRequest, DownloadBehavior::Download);
     728              : 
     729            0 :     let timeline =
     730            0 :         active_timeline_of_active_tenant(&state.tenant_manager, tenant_shard_id, timeline_id)
     731            0 :             .await?;
     732            0 :     let result = timeline
     733            0 :         .find_lsn_for_timestamp(timestamp_pg, &cancel, &ctx)
     734            0 :         .await?;
     735              :     #[derive(serde::Serialize, Debug)]
     736              :     struct Result {
     737              :         lsn: Lsn,
     738              :         kind: &'static str,
     739              :     }
     740            0 :     let (lsn, kind) = match result {
     741            0 :         LsnForTimestamp::Present(lsn) => (lsn, "present"),
     742            0 :         LsnForTimestamp::Future(lsn) => (lsn, "future"),
     743            0 :         LsnForTimestamp::Past(lsn) => (lsn, "past"),
     744            0 :         LsnForTimestamp::NoData(lsn) => (lsn, "nodata"),
     745              :     };
     746            0 :     let result = Result { lsn, kind };
     747            0 :     tracing::info!(
     748              :         lsn=?result.lsn,
     749              :         kind=%result.kind,
     750              :         timestamp=%timestamp_raw,
     751            0 :         "lsn_by_timestamp finished"
     752              :     );
     753            0 :     json_response(StatusCode::OK, result)
     754            0 : }
     755              : 
     756            0 : async fn get_timestamp_of_lsn_handler(
     757            0 :     request: Request<Body>,
     758            0 :     _cancel: CancellationToken,
     759            0 : ) -> Result<Response<Body>, ApiError> {
     760            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
     761            0 :     check_permission(&request, Some(tenant_shard_id.tenant_id))?;
     762            0 :     let state = get_state(&request);
     763            0 : 
     764            0 :     if !tenant_shard_id.is_shard_zero() {
     765              :         // Requires SLRU contents, which are only stored on shard zero
     766            0 :         return Err(ApiError::BadRequest(anyhow!(
     767            0 :             "Size calculations are only available on shard zero"
     768            0 :         )));
     769            0 :     }
     770              : 
     771            0 :     let timeline_id: TimelineId = parse_request_param(&request, "timeline_id")?;
     772              : 
     773            0 :     let lsn_str = must_get_query_param(&request, "lsn")?;
     774            0 :     let lsn = Lsn::from_str(&lsn_str)
     775            0 :         .with_context(|| format!("Invalid LSN: {lsn_str:?}"))
     776            0 :         .map_err(ApiError::BadRequest)?;
     777              : 
     778            0 :     let ctx = RequestContext::new(TaskKind::MgmtRequest, DownloadBehavior::Download);
     779            0 :     let timeline =
     780            0 :         active_timeline_of_active_tenant(&state.tenant_manager, tenant_shard_id, timeline_id)
     781            0 :             .await?;
     782            0 :     let result = timeline.get_timestamp_for_lsn(lsn, &ctx).await?;
     783              : 
     784            0 :     match result {
     785            0 :         Some(time) => {
     786            0 :             let time = format_rfc3339(postgres_ffi::from_pg_timestamp(time)).to_string();
     787            0 :             json_response(StatusCode::OK, time)
     788              :         }
     789            0 :         None => Err(ApiError::NotFound(
     790            0 :             anyhow::anyhow!("Timestamp for lsn {} not found", lsn).into(),
     791            0 :         )),
     792              :     }
     793            0 : }
     794              : 
     795            0 : async fn tenant_attach_handler(
     796            0 :     mut request: Request<Body>,
     797            0 :     _cancel: CancellationToken,
     798            0 : ) -> Result<Response<Body>, ApiError> {
     799            0 :     let tenant_id: TenantId = parse_request_param(&request, "tenant_id")?;
     800            0 :     check_permission(&request, Some(tenant_id))?;
     801              : 
     802            0 :     let maybe_body: Option<TenantAttachRequest> = json_request_or_empty_body(&mut request).await?;
     803            0 :     let tenant_conf = match &maybe_body {
     804            0 :         Some(request) => TenantConfOpt::try_from(&*request.config).map_err(ApiError::BadRequest)?,
     805            0 :         None => TenantConfOpt::default(),
     806              :     };
     807              : 
     808            0 :     let ctx = RequestContext::new(TaskKind::MgmtRequest, DownloadBehavior::Warn);
     809            0 : 
     810            0 :     info!("Handling tenant attach {tenant_id}");
     811              : 
     812            0 :     let state = get_state(&request);
     813              : 
     814            0 :     let generation = get_request_generation(state, maybe_body.as_ref().and_then(|r| r.generation))?;
     815              : 
     816            0 :     if state.remote_storage.is_none() {
     817            0 :         return Err(ApiError::BadRequest(anyhow!(
     818            0 :             "attach_tenant is not possible because pageserver was configured without remote storage"
     819            0 :         )));
     820            0 :     }
     821            0 : 
     822            0 :     let tenant_shard_id = TenantShardId::unsharded(tenant_id);
     823            0 :     let shard_params = ShardParameters::default();
     824            0 :     let location_conf = LocationConf::attached_single(tenant_conf, generation, &shard_params);
     825              : 
     826            0 :     let tenant = state
     827            0 :         .tenant_manager
     828            0 :         .upsert_location(tenant_shard_id, location_conf, None, SpawnMode::Eager, &ctx)
     829            0 :         .await?;
     830              : 
     831            0 :     let Some(tenant) = tenant else {
     832              :         // This should never happen: indicates a bug in upsert_location
     833            0 :         return Err(ApiError::InternalServerError(anyhow::anyhow!(
     834            0 :             "Upsert succeeded but didn't return tenant!"
     835            0 :         )));
     836              :     };
     837              : 
     838              :     // We might have successfully constructed a Tenant, but it could still
     839              :     // end up in a broken state:
     840              :     if let TenantState::Broken {
     841            0 :         reason,
     842              :         backtrace: _,
     843            0 :     } = tenant.current_state()
     844              :     {
     845            0 :         return Err(ApiError::InternalServerError(anyhow::anyhow!(
     846            0 :             "Tenant state is Broken: {reason}"
     847            0 :         )));
     848            0 :     }
     849            0 : 
     850            0 :     json_response(StatusCode::ACCEPTED, ())
     851            0 : }
     852              : 
     853            0 : async fn timeline_delete_handler(
     854            0 :     request: Request<Body>,
     855            0 :     _cancel: CancellationToken,
     856            0 : ) -> Result<Response<Body>, ApiError> {
     857            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
     858            0 :     let timeline_id: TimelineId = parse_request_param(&request, "timeline_id")?;
     859            0 :     check_permission(&request, Some(tenant_shard_id.tenant_id))?;
     860              : 
     861            0 :     let state = get_state(&request);
     862              : 
     863            0 :     let tenant = state
     864            0 :         .tenant_manager
     865            0 :         .get_attached_tenant_shard(tenant_shard_id)
     866            0 :         .map_err(|e| {
     867            0 :             match e {
     868              :                 // GetTenantError has a built-in conversion to ApiError, but in this context we don't
     869              :                 // want to treat missing tenants as 404, to avoid ambiguity with successful deletions.
     870            0 :                 GetTenantError::NotFound(_) => ApiError::PreconditionFailed(
     871            0 :                     "Requested tenant is missing".to_string().into_boxed_str(),
     872            0 :                 ),
     873            0 :                 e => e.into(),
     874              :             }
     875            0 :         })?;
     876            0 :     tenant.wait_to_become_active(ACTIVE_TENANT_TIMEOUT).await?;
     877            0 :     tenant.delete_timeline(timeline_id).instrument(info_span!("timeline_delete", tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug(), %timeline_id))
     878            0 :         .await?;
     879              : 
     880            0 :     json_response(StatusCode::ACCEPTED, ())
     881            0 : }
     882              : 
     883            0 : async fn tenant_detach_handler(
     884            0 :     request: Request<Body>,
     885            0 :     _cancel: CancellationToken,
     886            0 : ) -> Result<Response<Body>, ApiError> {
     887            0 :     let tenant_id: TenantId = parse_request_param(&request, "tenant_id")?;
     888            0 :     check_permission(&request, Some(tenant_id))?;
     889            0 :     let detach_ignored: Option<bool> = parse_query_param(&request, "detach_ignored")?;
     890              : 
     891              :     // This is a legacy API (`/location_conf` is the replacement).  It only supports unsharded tenants
     892            0 :     let tenant_shard_id = TenantShardId::unsharded(tenant_id);
     893            0 : 
     894            0 :     let state = get_state(&request);
     895            0 :     let conf = state.conf;
     896            0 :     state
     897            0 :         .tenant_manager
     898            0 :         .detach_tenant(
     899            0 :             conf,
     900            0 :             tenant_shard_id,
     901            0 :             detach_ignored.unwrap_or(false),
     902            0 :             &state.deletion_queue_client,
     903            0 :         )
     904            0 :         .instrument(info_span!("tenant_detach", %tenant_id, shard_id=%tenant_shard_id.shard_slug()))
     905            0 :         .await?;
     906              : 
     907            0 :     json_response(StatusCode::OK, ())
     908            0 : }
     909              : 
     910            0 : async fn tenant_reset_handler(
     911            0 :     request: Request<Body>,
     912            0 :     _cancel: CancellationToken,
     913            0 : ) -> Result<Response<Body>, ApiError> {
     914            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
     915            0 :     check_permission(&request, Some(tenant_shard_id.tenant_id))?;
     916              : 
     917            0 :     let drop_cache: Option<bool> = parse_query_param(&request, "drop_cache")?;
     918              : 
     919            0 :     let ctx = RequestContext::new(TaskKind::MgmtRequest, DownloadBehavior::Warn);
     920            0 :     let state = get_state(&request);
     921            0 :     state
     922            0 :         .tenant_manager
     923            0 :         .reset_tenant(tenant_shard_id, drop_cache.unwrap_or(false), &ctx)
     924            0 :         .await
     925            0 :         .map_err(ApiError::InternalServerError)?;
     926              : 
     927            0 :     json_response(StatusCode::OK, ())
     928            0 : }
     929              : 
     930            0 : async fn tenant_load_handler(
     931            0 :     mut request: Request<Body>,
     932            0 :     _cancel: CancellationToken,
     933            0 : ) -> Result<Response<Body>, ApiError> {
     934            0 :     let tenant_id: TenantId = parse_request_param(&request, "tenant_id")?;
     935            0 :     check_permission(&request, Some(tenant_id))?;
     936              : 
     937            0 :     let ctx = RequestContext::new(TaskKind::MgmtRequest, DownloadBehavior::Warn);
     938              : 
     939            0 :     let maybe_body: Option<TenantLoadRequest> = json_request_or_empty_body(&mut request).await?;
     940              : 
     941            0 :     let state = get_state(&request);
     942              : 
     943              :     // The /load request is only usable when control_plane_api is not set.  Once it is set, callers
     944              :     // should always use /attach instead.
     945            0 :     let generation = get_request_generation(state, maybe_body.as_ref().and_then(|r| r.generation))?;
     946              : 
     947            0 :     mgr::load_tenant(
     948            0 :         state.conf,
     949            0 :         tenant_id,
     950            0 :         generation,
     951            0 :         state.broker_client.clone(),
     952            0 :         state.remote_storage.clone(),
     953            0 :         state.deletion_queue_client.clone(),
     954            0 :         &ctx,
     955            0 :     )
     956            0 :     .instrument(info_span!("load", %tenant_id))
     957            0 :     .await?;
     958              : 
     959            0 :     json_response(StatusCode::ACCEPTED, ())
     960            0 : }
     961              : 
     962            0 : async fn tenant_ignore_handler(
     963            0 :     request: Request<Body>,
     964            0 :     _cancel: CancellationToken,
     965            0 : ) -> Result<Response<Body>, ApiError> {
     966            0 :     let tenant_id: TenantId = parse_request_param(&request, "tenant_id")?;
     967            0 :     check_permission(&request, Some(tenant_id))?;
     968              : 
     969            0 :     let state = get_state(&request);
     970            0 :     let conf = state.conf;
     971            0 :     mgr::ignore_tenant(conf, tenant_id)
     972            0 :         .instrument(info_span!("ignore_tenant", %tenant_id))
     973            0 :         .await?;
     974              : 
     975            0 :     json_response(StatusCode::OK, ())
     976            0 : }
     977              : 
     978            0 : async fn tenant_list_handler(
     979            0 :     request: Request<Body>,
     980            0 :     _cancel: CancellationToken,
     981            0 : ) -> Result<Response<Body>, ApiError> {
     982            0 :     check_permission(&request, None)?;
     983            0 :     let state = get_state(&request);
     984              : 
     985            0 :     let response_data = state
     986            0 :         .tenant_manager
     987            0 :         .list_tenants()
     988            0 :         .map_err(|_| {
     989            0 :             ApiError::ResourceUnavailable("Tenant map is initializing or shutting down".into())
     990            0 :         })?
     991            0 :         .iter()
     992            0 :         .map(|(id, state, gen)| TenantInfo {
     993            0 :             id: *id,
     994            0 :             state: state.clone(),
     995            0 :             current_physical_size: None,
     996            0 :             attachment_status: state.attachment_status(),
     997            0 :             generation: (*gen).into(),
     998            0 :         })
     999            0 :         .collect::<Vec<TenantInfo>>();
    1000            0 : 
    1001            0 :     json_response(StatusCode::OK, response_data)
    1002            0 : }
    1003              : 
    1004            0 : async fn tenant_status(
    1005            0 :     request: Request<Body>,
    1006            0 :     _cancel: CancellationToken,
    1007            0 : ) -> Result<Response<Body>, ApiError> {
    1008            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
    1009            0 :     check_permission(&request, Some(tenant_shard_id.tenant_id))?;
    1010            0 :     let state = get_state(&request);
    1011            0 : 
    1012            0 :     // In tests, sometimes we want to query the state of a tenant without auto-activating it if it's currently waiting.
    1013            0 :     let activate = true;
    1014              :     #[cfg(feature = "testing")]
    1015            0 :     let activate = parse_query_param(&request, "activate")?.unwrap_or(activate);
    1016              : 
    1017            0 :     let tenant_info = async {
    1018            0 :         let tenant = state
    1019            0 :             .tenant_manager
    1020            0 :             .get_attached_tenant_shard(tenant_shard_id)?;
    1021              : 
    1022            0 :         if activate {
    1023              :             // This is advisory: we prefer to let the tenant activate on-demand when this function is
    1024              :             // called, but it is still valid to return 200 and describe the current state of the tenant
    1025              :             // if it doesn't make it into an active state.
    1026            0 :             tenant
    1027            0 :                 .wait_to_become_active(ACTIVE_TENANT_TIMEOUT)
    1028            0 :                 .await
    1029            0 :                 .ok();
    1030            0 :         }
    1031              : 
    1032              :         // Calculate total physical size of all timelines
    1033            0 :         let mut current_physical_size = 0;
    1034            0 :         for timeline in tenant.list_timelines().iter() {
    1035            0 :             current_physical_size += timeline.layer_size_sum().await;
    1036              :         }
    1037              : 
    1038            0 :         let state = tenant.current_state();
    1039            0 :         Result::<_, ApiError>::Ok(TenantDetails {
    1040            0 :             tenant_info: TenantInfo {
    1041            0 :                 id: tenant_shard_id,
    1042            0 :                 state: state.clone(),
    1043            0 :                 current_physical_size: Some(current_physical_size),
    1044            0 :                 attachment_status: state.attachment_status(),
    1045            0 :                 generation: tenant.generation().into(),
    1046            0 :             },
    1047            0 :             walredo: tenant.wal_redo_manager_status(),
    1048            0 :             timelines: tenant.list_timeline_ids(),
    1049            0 :         })
    1050            0 :     }
    1051            0 :     .instrument(info_span!("tenant_status_handler",
    1052              :                 tenant_id = %tenant_shard_id.tenant_id,
    1053            0 :                 shard_id = %tenant_shard_id.shard_slug()))
    1054            0 :     .await?;
    1055              : 
    1056            0 :     json_response(StatusCode::OK, tenant_info)
    1057            0 : }
    1058              : 
    1059            0 : async fn tenant_delete_handler(
    1060            0 :     request: Request<Body>,
    1061            0 :     _cancel: CancellationToken,
    1062            0 : ) -> Result<Response<Body>, ApiError> {
    1063              :     // TODO openapi spec
    1064            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
    1065            0 :     check_permission(&request, Some(tenant_shard_id.tenant_id))?;
    1066              : 
    1067            0 :     let state = get_state(&request);
    1068            0 : 
    1069            0 :     state
    1070            0 :         .tenant_manager
    1071            0 :         .delete_tenant(tenant_shard_id, ACTIVE_TENANT_TIMEOUT)
    1072            0 :         .instrument(info_span!("tenant_delete_handler",
    1073              :             tenant_id = %tenant_shard_id.tenant_id,
    1074            0 :             shard_id = %tenant_shard_id.shard_slug()
    1075              :         ))
    1076            0 :         .await?;
    1077              : 
    1078            0 :     json_response(StatusCode::ACCEPTED, ())
    1079            0 : }
    1080              : 
    1081              : /// HTTP endpoint to query the current tenant_size of a tenant.
    1082              : ///
    1083              : /// This is not used by consumption metrics under [`crate::consumption_metrics`], but can be used
    1084              : /// to debug any of the calculations. Requires `tenant_id` request parameter, supports
    1085              : /// `inputs_only=true|false` (default false) which supports debugging failure to calculate model
    1086              : /// values.
    1087              : ///
    1088              : /// 'retention_period' query parameter overrides the cutoff that is used to calculate the size
    1089              : /// (only if it is shorter than the real cutoff).
    1090              : ///
    1091              : /// Note: we don't update the cached size and prometheus metric here.
    1092              : /// The retention period might be different, and it's nice to have a method to just calculate it
    1093              : /// without modifying anything anyway.
    1094            0 : async fn tenant_size_handler(
    1095            0 :     request: Request<Body>,
    1096            0 :     cancel: CancellationToken,
    1097            0 : ) -> Result<Response<Body>, ApiError> {
    1098            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
    1099            0 :     check_permission(&request, Some(tenant_shard_id.tenant_id))?;
    1100            0 :     let inputs_only: Option<bool> = parse_query_param(&request, "inputs_only")?;
    1101            0 :     let retention_period: Option<u64> = parse_query_param(&request, "retention_period")?;
    1102            0 :     let headers = request.headers();
    1103            0 :     let state = get_state(&request);
    1104            0 : 
    1105            0 :     if !tenant_shard_id.is_shard_zero() {
    1106            0 :         return Err(ApiError::BadRequest(anyhow!(
    1107            0 :             "Size calculations are only available on shard zero"
    1108            0 :         )));
    1109            0 :     }
    1110            0 : 
    1111            0 :     let ctx = RequestContext::new(TaskKind::MgmtRequest, DownloadBehavior::Download);
    1112            0 :     let tenant = state
    1113            0 :         .tenant_manager
    1114            0 :         .get_attached_tenant_shard(tenant_shard_id)?;
    1115            0 :     tenant.wait_to_become_active(ACTIVE_TENANT_TIMEOUT).await?;
    1116              : 
    1117              :     // this can be long operation
    1118            0 :     let inputs = tenant
    1119            0 :         .gather_size_inputs(
    1120            0 :             retention_period,
    1121            0 :             LogicalSizeCalculationCause::TenantSizeHandler,
    1122            0 :             &cancel,
    1123            0 :             &ctx,
    1124            0 :         )
    1125            0 :         .await
    1126            0 :         .map_err(ApiError::InternalServerError)?;
    1127              : 
    1128            0 :     let mut sizes = None;
    1129            0 :     let accepts_html = headers
    1130            0 :         .get(header::ACCEPT)
    1131            0 :         .map(|v| v == "text/html")
    1132            0 :         .unwrap_or_default();
    1133            0 :     if !inputs_only.unwrap_or(false) {
    1134            0 :         let storage_model = inputs
    1135            0 :             .calculate_model()
    1136            0 :             .map_err(ApiError::InternalServerError)?;
    1137            0 :         let size = storage_model.calculate();
    1138            0 : 
    1139            0 :         // If request header expects html, return html
    1140            0 :         if accepts_html {
    1141            0 :             return synthetic_size_html_response(inputs, storage_model, size);
    1142            0 :         }
    1143            0 :         sizes = Some(size);
    1144            0 :     } else if accepts_html {
    1145            0 :         return Err(ApiError::BadRequest(anyhow!(
    1146            0 :             "inputs_only parameter is incompatible with html output request"
    1147            0 :         )));
    1148            0 :     }
    1149              : 
    1150              :     /// The type resides in the pageserver not to expose `ModelInputs`.
    1151              :     #[derive(serde::Serialize)]
    1152              :     struct TenantHistorySize {
    1153              :         id: TenantId,
    1154              :         /// Size is a mixture of WAL and logical size, so the unit is bytes.
    1155              :         ///
    1156              :         /// Will be none if `?inputs_only=true` was given.
    1157              :         size: Option<u64>,
    1158              :         /// Size of each segment used in the model.
    1159              :         /// Will be null if `?inputs_only=true` was given.
    1160              :         segment_sizes: Option<Vec<tenant_size_model::SegmentSizeResult>>,
    1161              :         inputs: crate::tenant::size::ModelInputs,
    1162              :     }
    1163              : 
    1164            0 :     json_response(
    1165            0 :         StatusCode::OK,
    1166            0 :         TenantHistorySize {
    1167            0 :             id: tenant_shard_id.tenant_id,
    1168            0 :             size: sizes.as_ref().map(|x| x.total_size),
    1169            0 :             segment_sizes: sizes.map(|x| x.segments),
    1170            0 :             inputs,
    1171            0 :         },
    1172            0 :     )
    1173            0 : }
    1174              : 
    1175            0 : async fn tenant_shard_split_handler(
    1176            0 :     mut request: Request<Body>,
    1177            0 :     _cancel: CancellationToken,
    1178            0 : ) -> Result<Response<Body>, ApiError> {
    1179            0 :     let req: TenantShardSplitRequest = json_request(&mut request).await?;
    1180              : 
    1181            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
    1182            0 :     let state = get_state(&request);
    1183            0 :     let ctx = RequestContext::new(TaskKind::MgmtRequest, DownloadBehavior::Warn);
    1184              : 
    1185            0 :     let tenant = state
    1186            0 :         .tenant_manager
    1187            0 :         .get_attached_tenant_shard(tenant_shard_id)?;
    1188            0 :     tenant.wait_to_become_active(ACTIVE_TENANT_TIMEOUT).await?;
    1189              : 
    1190            0 :     let new_shards = state
    1191            0 :         .tenant_manager
    1192            0 :         .shard_split(
    1193            0 :             tenant,
    1194            0 :             ShardCount::new(req.new_shard_count),
    1195            0 :             req.new_stripe_size,
    1196            0 :             &ctx,
    1197            0 :         )
    1198            0 :         .await
    1199            0 :         .map_err(ApiError::InternalServerError)?;
    1200              : 
    1201            0 :     json_response(StatusCode::OK, TenantShardSplitResponse { new_shards })
    1202            0 : }
    1203              : 
    1204            0 : async fn layer_map_info_handler(
    1205            0 :     request: Request<Body>,
    1206            0 :     _cancel: CancellationToken,
    1207            0 : ) -> Result<Response<Body>, ApiError> {
    1208            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
    1209            0 :     let timeline_id: TimelineId = parse_request_param(&request, "timeline_id")?;
    1210            0 :     let reset: LayerAccessStatsReset =
    1211            0 :         parse_query_param(&request, "reset")?.unwrap_or(LayerAccessStatsReset::NoReset);
    1212            0 :     let state = get_state(&request);
    1213            0 : 
    1214            0 :     check_permission(&request, Some(tenant_shard_id.tenant_id))?;
    1215              : 
    1216            0 :     let timeline =
    1217            0 :         active_timeline_of_active_tenant(&state.tenant_manager, tenant_shard_id, timeline_id)
    1218            0 :             .await?;
    1219            0 :     let layer_map_info = timeline.layer_map_info(reset).await;
    1220              : 
    1221            0 :     json_response(StatusCode::OK, layer_map_info)
    1222            0 : }
    1223              : 
    1224            0 : async fn layer_download_handler(
    1225            0 :     request: Request<Body>,
    1226            0 :     _cancel: CancellationToken,
    1227            0 : ) -> Result<Response<Body>, ApiError> {
    1228            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
    1229            0 :     let timeline_id: TimelineId = parse_request_param(&request, "timeline_id")?;
    1230            0 :     let layer_file_name = get_request_param(&request, "layer_file_name")?;
    1231            0 :     check_permission(&request, Some(tenant_shard_id.tenant_id))?;
    1232            0 :     let layer_name = LayerName::from_str(layer_file_name)
    1233            0 :         .map_err(|s| ApiError::BadRequest(anyhow::anyhow!(s)))?;
    1234            0 :     let state = get_state(&request);
    1235              : 
    1236            0 :     let timeline =
    1237            0 :         active_timeline_of_active_tenant(&state.tenant_manager, tenant_shard_id, timeline_id)
    1238            0 :             .await?;
    1239            0 :     let downloaded = timeline
    1240            0 :         .download_layer(&layer_name)
    1241            0 :         .await
    1242            0 :         .map_err(ApiError::InternalServerError)?;
    1243              : 
    1244            0 :     match downloaded {
    1245            0 :         Some(true) => json_response(StatusCode::OK, ()),
    1246            0 :         Some(false) => json_response(StatusCode::NOT_MODIFIED, ()),
    1247            0 :         None => json_response(
    1248            0 :             StatusCode::BAD_REQUEST,
    1249            0 :             format!("Layer {tenant_shard_id}/{timeline_id}/{layer_file_name} not found"),
    1250            0 :         ),
    1251              :     }
    1252            0 : }
    1253              : 
    1254            0 : async fn evict_timeline_layer_handler(
    1255            0 :     request: Request<Body>,
    1256            0 :     _cancel: CancellationToken,
    1257            0 : ) -> Result<Response<Body>, ApiError> {
    1258            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
    1259            0 :     check_permission(&request, Some(tenant_shard_id.tenant_id))?;
    1260            0 :     let timeline_id: TimelineId = parse_request_param(&request, "timeline_id")?;
    1261            0 :     let layer_file_name = get_request_param(&request, "layer_file_name")?;
    1262            0 :     let state = get_state(&request);
    1263              : 
    1264            0 :     let layer_name = LayerName::from_str(layer_file_name)
    1265            0 :         .map_err(|s| ApiError::BadRequest(anyhow::anyhow!(s)))?;
    1266              : 
    1267            0 :     let timeline =
    1268            0 :         active_timeline_of_active_tenant(&state.tenant_manager, tenant_shard_id, timeline_id)
    1269            0 :             .await?;
    1270            0 :     let evicted = timeline
    1271            0 :         .evict_layer(&layer_name)
    1272            0 :         .await
    1273            0 :         .map_err(ApiError::InternalServerError)?;
    1274              : 
    1275            0 :     match evicted {
    1276            0 :         Some(true) => json_response(StatusCode::OK, ()),
    1277            0 :         Some(false) => json_response(StatusCode::NOT_MODIFIED, ()),
    1278            0 :         None => json_response(
    1279            0 :             StatusCode::BAD_REQUEST,
    1280            0 :             format!("Layer {tenant_shard_id}/{timeline_id}/{layer_file_name} not found"),
    1281            0 :         ),
    1282              :     }
    1283            0 : }
    1284              : 
    1285              : /// Get tenant_size SVG graph along with the JSON data.
    1286            0 : fn synthetic_size_html_response(
    1287            0 :     inputs: ModelInputs,
    1288            0 :     storage_model: StorageModel,
    1289            0 :     sizes: SizeResult,
    1290            0 : ) -> Result<Response<Body>, ApiError> {
    1291            0 :     let mut timeline_ids: Vec<String> = Vec::new();
    1292            0 :     let mut timeline_map: HashMap<TimelineId, usize> = HashMap::new();
    1293            0 :     for (index, ti) in inputs.timeline_inputs.iter().enumerate() {
    1294            0 :         timeline_map.insert(ti.timeline_id, index);
    1295            0 :         timeline_ids.push(ti.timeline_id.to_string());
    1296            0 :     }
    1297            0 :     let seg_to_branch: Vec<usize> = inputs
    1298            0 :         .segments
    1299            0 :         .iter()
    1300            0 :         .map(|seg| *timeline_map.get(&seg.timeline_id).unwrap())
    1301            0 :         .collect();
    1302              : 
    1303            0 :     let svg =
    1304            0 :         tenant_size_model::svg::draw_svg(&storage_model, &timeline_ids, &seg_to_branch, &sizes)
    1305            0 :             .map_err(ApiError::InternalServerError)?;
    1306              : 
    1307            0 :     let mut response = String::new();
    1308            0 : 
    1309            0 :     use std::fmt::Write;
    1310            0 :     write!(response, "<html>\n<body>\n").unwrap();
    1311            0 :     write!(response, "<div>\n{svg}\n</div>").unwrap();
    1312            0 :     writeln!(response, "Project size: {}", sizes.total_size).unwrap();
    1313            0 :     writeln!(response, "<pre>").unwrap();
    1314            0 :     writeln!(
    1315            0 :         response,
    1316            0 :         "{}",
    1317            0 :         serde_json::to_string_pretty(&inputs).unwrap()
    1318            0 :     )
    1319            0 :     .unwrap();
    1320            0 :     writeln!(
    1321            0 :         response,
    1322            0 :         "{}",
    1323            0 :         serde_json::to_string_pretty(&sizes.segments).unwrap()
    1324            0 :     )
    1325            0 :     .unwrap();
    1326            0 :     writeln!(response, "</pre>").unwrap();
    1327            0 :     write!(response, "</body>\n</html>\n").unwrap();
    1328            0 : 
    1329            0 :     html_response(StatusCode::OK, response)
    1330            0 : }
    1331              : 
    1332            0 : pub fn html_response(status: StatusCode, data: String) -> Result<Response<Body>, ApiError> {
    1333            0 :     let response = Response::builder()
    1334            0 :         .status(status)
    1335            0 :         .header(header::CONTENT_TYPE, "text/html")
    1336            0 :         .body(Body::from(data.as_bytes().to_vec()))
    1337            0 :         .map_err(|e| ApiError::InternalServerError(e.into()))?;
    1338            0 :     Ok(response)
    1339            0 : }
    1340              : 
    1341              : /// Helper for requests that may take a generation, which is mandatory
    1342              : /// when control_plane_api is set, but otherwise defaults to Generation::none()
    1343            0 : fn get_request_generation(state: &State, req_gen: Option<u32>) -> Result<Generation, ApiError> {
    1344            0 :     if state.conf.control_plane_api.is_some() {
    1345            0 :         req_gen
    1346            0 :             .map(Generation::new)
    1347            0 :             .ok_or(ApiError::BadRequest(anyhow!(
    1348            0 :                 "generation attribute missing"
    1349            0 :             )))
    1350              :     } else {
    1351              :         // Legacy mode: all tenants operate with no generation
    1352            0 :         Ok(Generation::none())
    1353              :     }
    1354            0 : }
    1355              : 
    1356            0 : async fn tenant_create_handler(
    1357            0 :     mut request: Request<Body>,
    1358            0 :     _cancel: CancellationToken,
    1359            0 : ) -> Result<Response<Body>, ApiError> {
    1360            0 :     let request_data: TenantCreateRequest = json_request(&mut request).await?;
    1361            0 :     let target_tenant_id = request_data.new_tenant_id;
    1362            0 :     check_permission(&request, None)?;
    1363              : 
    1364            0 :     let _timer = STORAGE_TIME_GLOBAL
    1365            0 :         .get_metric_with_label_values(&[StorageTimeOperation::CreateTenant.into()])
    1366            0 :         .expect("bug")
    1367            0 :         .start_timer();
    1368              : 
    1369            0 :     let tenant_conf =
    1370            0 :         TenantConfOpt::try_from(&request_data.config).map_err(ApiError::BadRequest)?;
    1371              : 
    1372            0 :     let state = get_state(&request);
    1373              : 
    1374            0 :     let generation = get_request_generation(state, request_data.generation)?;
    1375              : 
    1376            0 :     let ctx = RequestContext::new(TaskKind::MgmtRequest, DownloadBehavior::Warn);
    1377            0 : 
    1378            0 :     let location_conf =
    1379            0 :         LocationConf::attached_single(tenant_conf, generation, &request_data.shard_parameters);
    1380              : 
    1381            0 :     let new_tenant = state
    1382            0 :         .tenant_manager
    1383            0 :         .upsert_location(
    1384            0 :             target_tenant_id,
    1385            0 :             location_conf,
    1386            0 :             None,
    1387            0 :             SpawnMode::Create,
    1388            0 :             &ctx,
    1389            0 :         )
    1390            0 :         .await?;
    1391              : 
    1392            0 :     let Some(new_tenant) = new_tenant else {
    1393              :         // This should never happen: indicates a bug in upsert_location
    1394            0 :         return Err(ApiError::InternalServerError(anyhow::anyhow!(
    1395            0 :             "Upsert succeeded but didn't return tenant!"
    1396            0 :         )));
    1397              :     };
    1398              :     // We created the tenant. Existing API semantics are that the tenant
    1399              :     // is Active when this function returns.
    1400            0 :     new_tenant
    1401            0 :         .wait_to_become_active(ACTIVE_TENANT_TIMEOUT)
    1402            0 :         .await?;
    1403              : 
    1404            0 :     json_response(
    1405            0 :         StatusCode::CREATED,
    1406            0 :         TenantCreateResponse(new_tenant.tenant_shard_id().tenant_id),
    1407            0 :     )
    1408            0 : }
    1409              : 
    1410            0 : async fn get_tenant_config_handler(
    1411            0 :     request: Request<Body>,
    1412            0 :     _cancel: CancellationToken,
    1413            0 : ) -> Result<Response<Body>, ApiError> {
    1414            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
    1415            0 :     check_permission(&request, Some(tenant_shard_id.tenant_id))?;
    1416            0 :     let state = get_state(&request);
    1417              : 
    1418            0 :     let tenant = state
    1419            0 :         .tenant_manager
    1420            0 :         .get_attached_tenant_shard(tenant_shard_id)?;
    1421              : 
    1422            0 :     let response = HashMap::from([
    1423              :         (
    1424              :             "tenant_specific_overrides",
    1425            0 :             serde_json::to_value(tenant.tenant_specific_overrides())
    1426            0 :                 .context("serializing tenant specific overrides")
    1427            0 :                 .map_err(ApiError::InternalServerError)?,
    1428              :         ),
    1429              :         (
    1430            0 :             "effective_config",
    1431            0 :             serde_json::to_value(tenant.effective_config())
    1432            0 :                 .context("serializing effective config")
    1433            0 :                 .map_err(ApiError::InternalServerError)?,
    1434              :         ),
    1435              :     ]);
    1436              : 
    1437            0 :     json_response(StatusCode::OK, response)
    1438            0 : }
    1439              : 
    1440            0 : async fn update_tenant_config_handler(
    1441            0 :     mut request: Request<Body>,
    1442            0 :     _cancel: CancellationToken,
    1443            0 : ) -> Result<Response<Body>, ApiError> {
    1444            0 :     let request_data: TenantConfigRequest = json_request(&mut request).await?;
    1445            0 :     let tenant_id = request_data.tenant_id;
    1446            0 :     check_permission(&request, Some(tenant_id))?;
    1447              : 
    1448            0 :     let new_tenant_conf =
    1449            0 :         TenantConfOpt::try_from(&request_data.config).map_err(ApiError::BadRequest)?;
    1450              : 
    1451            0 :     let state = get_state(&request);
    1452            0 : 
    1453            0 :     let tenant_shard_id = TenantShardId::unsharded(tenant_id);
    1454              : 
    1455            0 :     let tenant = state
    1456            0 :         .tenant_manager
    1457            0 :         .get_attached_tenant_shard(tenant_shard_id)?;
    1458            0 :     tenant.wait_to_become_active(ACTIVE_TENANT_TIMEOUT).await?;
    1459              : 
    1460              :     // This is a legacy API that only operates on attached tenants: the preferred
    1461              :     // API to use is the location_config/ endpoint, which lets the caller provide
    1462              :     // the full LocationConf.
    1463            0 :     let location_conf = LocationConf::attached_single(
    1464            0 :         new_tenant_conf.clone(),
    1465            0 :         tenant.get_generation(),
    1466            0 :         &ShardParameters::default(),
    1467            0 :     );
    1468            0 : 
    1469            0 :     crate::tenant::Tenant::persist_tenant_config(state.conf, &tenant_shard_id, &location_conf)
    1470            0 :         .await
    1471            0 :         .map_err(ApiError::InternalServerError)?;
    1472            0 :     tenant.set_new_tenant_config(new_tenant_conf);
    1473            0 : 
    1474            0 :     json_response(StatusCode::OK, ())
    1475            0 : }
    1476              : 
    1477            0 : async fn put_tenant_location_config_handler(
    1478            0 :     mut request: Request<Body>,
    1479            0 :     _cancel: CancellationToken,
    1480            0 : ) -> Result<Response<Body>, ApiError> {
    1481            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
    1482              : 
    1483            0 :     let request_data: TenantLocationConfigRequest = json_request(&mut request).await?;
    1484            0 :     let flush = parse_query_param(&request, "flush_ms")?.map(Duration::from_millis);
    1485            0 :     let lazy = parse_query_param(&request, "lazy")?.unwrap_or(false);
    1486            0 :     check_permission(&request, Some(tenant_shard_id.tenant_id))?;
    1487              : 
    1488            0 :     let ctx = RequestContext::new(TaskKind::MgmtRequest, DownloadBehavior::Warn);
    1489            0 :     let state = get_state(&request);
    1490            0 :     let conf = state.conf;
    1491            0 : 
    1492            0 :     // The `Detached` state is special, it doesn't upsert a tenant, it removes
    1493            0 :     // its local disk content and drops it from memory.
    1494            0 :     if let LocationConfigMode::Detached = request_data.config.mode {
    1495            0 :         if let Err(e) = state
    1496            0 :             .tenant_manager
    1497            0 :             .detach_tenant(conf, tenant_shard_id, true, &state.deletion_queue_client)
    1498            0 :             .instrument(info_span!("tenant_detach",
    1499              :                 tenant_id = %tenant_shard_id.tenant_id,
    1500            0 :                 shard_id = %tenant_shard_id.shard_slug()
    1501              :             ))
    1502            0 :             .await
    1503              :         {
    1504            0 :             match e {
    1505            0 :                 TenantStateError::SlotError(TenantSlotError::NotFound(_)) => {
    1506            0 :                     // This API is idempotent: a NotFound on a detach is fine.
    1507            0 :                 }
    1508            0 :                 _ => return Err(e.into()),
    1509              :             }
    1510            0 :         }
    1511            0 :         return json_response(StatusCode::OK, ());
    1512            0 :     }
    1513              : 
    1514            0 :     let location_conf =
    1515            0 :         LocationConf::try_from(&request_data.config).map_err(ApiError::BadRequest)?;
    1516              : 
    1517              :     // lazy==true queues up for activation or jumps the queue like normal when a compute connects,
    1518              :     // similar to at startup ordering.
    1519            0 :     let spawn_mode = if lazy {
    1520            0 :         tenant::SpawnMode::Lazy
    1521              :     } else {
    1522            0 :         tenant::SpawnMode::Eager
    1523              :     };
    1524              : 
    1525            0 :     let tenant = state
    1526            0 :         .tenant_manager
    1527            0 :         .upsert_location(tenant_shard_id, location_conf, flush, spawn_mode, &ctx)
    1528            0 :         .await?;
    1529            0 :     let stripe_size = tenant.as_ref().map(|t| t.get_shard_stripe_size());
    1530            0 :     let attached = tenant.is_some();
    1531              : 
    1532            0 :     if let Some(_flush_ms) = flush {
    1533            0 :         match state
    1534            0 :             .secondary_controller
    1535            0 :             .upload_tenant(tenant_shard_id)
    1536            0 :             .await
    1537              :         {
    1538              :             Ok(()) => {
    1539            0 :                 tracing::info!("Uploaded heatmap during flush");
    1540              :             }
    1541            0 :             Err(e) => {
    1542            0 :                 tracing::warn!("Failed to flush heatmap: {e}");
    1543              :             }
    1544              :         }
    1545              :     } else {
    1546            0 :         tracing::info!("No flush requested when configuring");
    1547              :     }
    1548              : 
    1549              :     // This API returns a vector of pageservers where the tenant is attached: this is
    1550              :     // primarily for use in the sharding service.  For compatibilty, we also return this
    1551              :     // when called directly on a pageserver, but the payload is always zero or one shards.
    1552            0 :     let mut response = TenantLocationConfigResponse {
    1553            0 :         shards: Vec::new(),
    1554            0 :         stripe_size: None,
    1555            0 :     };
    1556            0 :     if attached {
    1557            0 :         response.shards.push(TenantShardLocation {
    1558            0 :             shard_id: tenant_shard_id,
    1559            0 :             node_id: state.conf.id,
    1560            0 :         });
    1561            0 :         if tenant_shard_id.shard_count.count() > 1 {
    1562              :             // Stripe size should be set if we are attached
    1563            0 :             debug_assert!(stripe_size.is_some());
    1564            0 :             response.stripe_size = stripe_size;
    1565            0 :         }
    1566            0 :     }
    1567              : 
    1568            0 :     json_response(StatusCode::OK, response)
    1569            0 : }
    1570              : 
    1571            0 : async fn list_location_config_handler(
    1572            0 :     request: Request<Body>,
    1573            0 :     _cancel: CancellationToken,
    1574            0 : ) -> Result<Response<Body>, ApiError> {
    1575            0 :     let state = get_state(&request);
    1576            0 :     let slots = state.tenant_manager.list();
    1577            0 :     let result = LocationConfigListResponse {
    1578            0 :         tenant_shards: slots
    1579            0 :             .into_iter()
    1580            0 :             .map(|(tenant_shard_id, slot)| {
    1581            0 :                 let v = match slot {
    1582            0 :                     TenantSlot::Attached(t) => Some(t.get_location_conf()),
    1583            0 :                     TenantSlot::Secondary(s) => Some(s.get_location_conf()),
    1584            0 :                     TenantSlot::InProgress(_) => None,
    1585              :                 };
    1586            0 :                 (tenant_shard_id, v)
    1587            0 :             })
    1588            0 :             .collect(),
    1589            0 :     };
    1590            0 :     json_response(StatusCode::OK, result)
    1591            0 : }
    1592              : 
    1593            0 : async fn get_location_config_handler(
    1594            0 :     request: Request<Body>,
    1595            0 :     _cancel: CancellationToken,
    1596            0 : ) -> Result<Response<Body>, ApiError> {
    1597            0 :     let state = get_state(&request);
    1598            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
    1599            0 :     let slot = state.tenant_manager.get(tenant_shard_id);
    1600              : 
    1601            0 :     let Some(slot) = slot else {
    1602            0 :         return Err(ApiError::NotFound(
    1603            0 :             anyhow::anyhow!("Tenant shard not found").into(),
    1604            0 :         ));
    1605              :     };
    1606              : 
    1607            0 :     let result: Option<LocationConfig> = match slot {
    1608            0 :         TenantSlot::Attached(t) => Some(t.get_location_conf()),
    1609            0 :         TenantSlot::Secondary(s) => Some(s.get_location_conf()),
    1610            0 :         TenantSlot::InProgress(_) => None,
    1611              :     };
    1612              : 
    1613            0 :     json_response(StatusCode::OK, result)
    1614            0 : }
    1615              : 
    1616              : // Do a time travel recovery on the given tenant/tenant shard. Tenant needs to be detached
    1617              : // (from all pageservers) as it invalidates consistency assumptions.
    1618            0 : async fn tenant_time_travel_remote_storage_handler(
    1619            0 :     request: Request<Body>,
    1620            0 :     cancel: CancellationToken,
    1621            0 : ) -> Result<Response<Body>, ApiError> {
    1622            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
    1623              : 
    1624            0 :     check_permission(&request, Some(tenant_shard_id.tenant_id))?;
    1625              : 
    1626            0 :     let timestamp_raw = must_get_query_param(&request, "travel_to")?;
    1627            0 :     let timestamp = humantime::parse_rfc3339(&timestamp_raw)
    1628            0 :         .with_context(|| format!("Invalid time for travel_to: {timestamp_raw:?}"))
    1629            0 :         .map_err(ApiError::BadRequest)?;
    1630              : 
    1631            0 :     let done_if_after_raw = must_get_query_param(&request, "done_if_after")?;
    1632            0 :     let done_if_after = humantime::parse_rfc3339(&done_if_after_raw)
    1633            0 :         .with_context(|| format!("Invalid time for done_if_after: {done_if_after_raw:?}"))
    1634            0 :         .map_err(ApiError::BadRequest)?;
    1635              : 
    1636              :     // This is just a sanity check to fend off naive wrong usages of the API:
    1637              :     // the tenant needs to be detached *everywhere*
    1638            0 :     let state = get_state(&request);
    1639            0 :     let we_manage_tenant = state.tenant_manager.manages_tenant_shard(tenant_shard_id);
    1640            0 :     if we_manage_tenant {
    1641            0 :         return Err(ApiError::BadRequest(anyhow!(
    1642            0 :             "Tenant {tenant_shard_id} is already attached at this pageserver"
    1643            0 :         )));
    1644            0 :     }
    1645              : 
    1646            0 :     let Some(storage) = state.remote_storage.as_ref() else {
    1647            0 :         return Err(ApiError::InternalServerError(anyhow::anyhow!(
    1648            0 :             "remote storage not configured, cannot run time travel"
    1649            0 :         )));
    1650              :     };
    1651              : 
    1652            0 :     if timestamp > done_if_after {
    1653            0 :         return Err(ApiError::BadRequest(anyhow!(
    1654            0 :             "The done_if_after timestamp comes before the timestamp to recover to"
    1655            0 :         )));
    1656            0 :     }
    1657            0 : 
    1658            0 :     tracing::info!("Issuing time travel request internally. timestamp={timestamp_raw}, done_if_after={done_if_after_raw}");
    1659              : 
    1660            0 :     remote_timeline_client::upload::time_travel_recover_tenant(
    1661            0 :         storage,
    1662            0 :         &tenant_shard_id,
    1663            0 :         timestamp,
    1664            0 :         done_if_after,
    1665            0 :         &cancel,
    1666            0 :     )
    1667            0 :     .await
    1668            0 :     .map_err(|e| match e {
    1669            0 :         TimeTravelError::BadInput(e) => {
    1670            0 :             warn!("bad input error: {e}");
    1671            0 :             ApiError::BadRequest(anyhow!("bad input error"))
    1672              :         }
    1673              :         TimeTravelError::Unimplemented => {
    1674            0 :             ApiError::BadRequest(anyhow!("unimplemented for the configured remote storage"))
    1675              :         }
    1676            0 :         TimeTravelError::Cancelled => ApiError::InternalServerError(anyhow!("cancelled")),
    1677              :         TimeTravelError::TooManyVersions => {
    1678            0 :             ApiError::InternalServerError(anyhow!("too many versions in remote storage"))
    1679              :         }
    1680            0 :         TimeTravelError::Other(e) => {
    1681            0 :             warn!("internal error: {e}");
    1682            0 :             ApiError::InternalServerError(anyhow!("internal error"))
    1683              :         }
    1684            0 :     })?;
    1685              : 
    1686            0 :     json_response(StatusCode::OK, ())
    1687            0 : }
    1688              : 
    1689              : /// Testing helper to transition a tenant to [`crate::tenant::TenantState::Broken`].
    1690            0 : async fn handle_tenant_break(
    1691            0 :     r: Request<Body>,
    1692            0 :     _cancel: CancellationToken,
    1693            0 : ) -> Result<Response<Body>, ApiError> {
    1694            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&r, "tenant_shard_id")?;
    1695              : 
    1696            0 :     let state = get_state(&r);
    1697            0 :     state
    1698            0 :         .tenant_manager
    1699            0 :         .get_attached_tenant_shard(tenant_shard_id)?
    1700            0 :         .set_broken("broken from test".to_owned())
    1701            0 :         .await;
    1702              : 
    1703            0 :     json_response(StatusCode::OK, ())
    1704            0 : }
    1705              : 
    1706              : // Run GC immediately on given timeline.
    1707            0 : async fn timeline_gc_handler(
    1708            0 :     mut request: Request<Body>,
    1709            0 :     cancel: CancellationToken,
    1710            0 : ) -> Result<Response<Body>, ApiError> {
    1711            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
    1712            0 :     let timeline_id: TimelineId = parse_request_param(&request, "timeline_id")?;
    1713            0 :     check_permission(&request, Some(tenant_shard_id.tenant_id))?;
    1714              : 
    1715            0 :     let gc_req: TimelineGcRequest = json_request(&mut request).await?;
    1716              : 
    1717            0 :     let ctx = RequestContext::new(TaskKind::MgmtRequest, DownloadBehavior::Download);
    1718            0 :     let wait_task_done = mgr::immediate_gc(tenant_shard_id, timeline_id, gc_req, cancel, &ctx)?;
    1719            0 :     let gc_result = wait_task_done
    1720            0 :         .await
    1721            0 :         .context("wait for gc task")
    1722            0 :         .map_err(ApiError::InternalServerError)?
    1723            0 :         .map_err(ApiError::InternalServerError)?;
    1724              : 
    1725            0 :     json_response(StatusCode::OK, gc_result)
    1726            0 : }
    1727              : 
    1728              : // Run compaction immediately on given timeline.
    1729            0 : async fn timeline_compact_handler(
    1730            0 :     request: Request<Body>,
    1731            0 :     cancel: CancellationToken,
    1732            0 : ) -> Result<Response<Body>, ApiError> {
    1733            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
    1734            0 :     let timeline_id: TimelineId = parse_request_param(&request, "timeline_id")?;
    1735            0 :     check_permission(&request, Some(tenant_shard_id.tenant_id))?;
    1736              : 
    1737            0 :     let state = get_state(&request);
    1738            0 : 
    1739            0 :     let mut flags = EnumSet::empty();
    1740            0 :     if Some(true) == parse_query_param::<_, bool>(&request, "force_repartition")? {
    1741            0 :         flags |= CompactFlags::ForceRepartition;
    1742            0 :     }
    1743            0 :     if Some(true) == parse_query_param::<_, bool>(&request, "force_image_layer_creation")? {
    1744            0 :         flags |= CompactFlags::ForceImageLayerCreation;
    1745            0 :     }
    1746              : 
    1747            0 :     async {
    1748            0 :         let ctx = RequestContext::new(TaskKind::MgmtRequest, DownloadBehavior::Download);
    1749            0 :         let timeline = active_timeline_of_active_tenant(&state.tenant_manager, tenant_shard_id, timeline_id).await?;
    1750            0 :         timeline
    1751            0 :             .compact(&cancel, flags, &ctx)
    1752            0 :             .await
    1753            0 :             .map_err(|e| ApiError::InternalServerError(e.into()))?;
    1754            0 :         json_response(StatusCode::OK, ())
    1755            0 :     }
    1756            0 :     .instrument(info_span!("manual_compaction", tenant_id = %tenant_shard_id.tenant_id, shard_id = %tenant_shard_id.shard_slug(), %timeline_id))
    1757            0 :     .await
    1758            0 : }
    1759              : 
    1760              : // Run checkpoint immediately on given timeline.
    1761            0 : async fn timeline_checkpoint_handler(
    1762            0 :     request: Request<Body>,
    1763            0 :     cancel: CancellationToken,
    1764            0 : ) -> Result<Response<Body>, ApiError> {
    1765            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
    1766            0 :     let timeline_id: TimelineId = parse_request_param(&request, "timeline_id")?;
    1767            0 :     check_permission(&request, Some(tenant_shard_id.tenant_id))?;
    1768              : 
    1769            0 :     let state = get_state(&request);
    1770            0 : 
    1771            0 :     let mut flags = EnumSet::empty();
    1772            0 :     if Some(true) == parse_query_param::<_, bool>(&request, "force_repartition")? {
    1773            0 :         flags |= CompactFlags::ForceRepartition;
    1774            0 :     }
    1775            0 :     if Some(true) == parse_query_param::<_, bool>(&request, "force_image_layer_creation")? {
    1776            0 :         flags |= CompactFlags::ForceImageLayerCreation;
    1777            0 :     }
    1778              : 
    1779            0 :     async {
    1780            0 :         let ctx = RequestContext::new(TaskKind::MgmtRequest, DownloadBehavior::Download);
    1781            0 :         let timeline = active_timeline_of_active_tenant(&state.tenant_manager, tenant_shard_id, timeline_id).await?;
    1782            0 :         timeline
    1783            0 :             .freeze_and_flush()
    1784            0 :             .await
    1785            0 :             .map_err(ApiError::InternalServerError)?;
    1786            0 :         timeline
    1787            0 :             .compact(&cancel, flags, &ctx)
    1788            0 :             .await
    1789            0 :             .map_err(|e| ApiError::InternalServerError(e.into()))?;
    1790              : 
    1791            0 :         json_response(StatusCode::OK, ())
    1792            0 :     }
    1793            0 :     .instrument(info_span!("manual_checkpoint", tenant_id = %tenant_shard_id.tenant_id, shard_id = %tenant_shard_id.shard_slug(), %timeline_id))
    1794            0 :     .await
    1795            0 : }
    1796              : 
    1797            0 : async fn timeline_download_remote_layers_handler_post(
    1798            0 :     mut request: Request<Body>,
    1799            0 :     _cancel: CancellationToken,
    1800            0 : ) -> Result<Response<Body>, ApiError> {
    1801            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
    1802            0 :     let timeline_id: TimelineId = parse_request_param(&request, "timeline_id")?;
    1803            0 :     let body: DownloadRemoteLayersTaskSpawnRequest = json_request(&mut request).await?;
    1804            0 :     check_permission(&request, Some(tenant_shard_id.tenant_id))?;
    1805              : 
    1806            0 :     let state = get_state(&request);
    1807              : 
    1808            0 :     let timeline =
    1809            0 :         active_timeline_of_active_tenant(&state.tenant_manager, tenant_shard_id, timeline_id)
    1810            0 :             .await?;
    1811            0 :     match timeline.spawn_download_all_remote_layers(body).await {
    1812            0 :         Ok(st) => json_response(StatusCode::ACCEPTED, st),
    1813            0 :         Err(st) => json_response(StatusCode::CONFLICT, st),
    1814              :     }
    1815            0 : }
    1816              : 
    1817            0 : async fn timeline_download_remote_layers_handler_get(
    1818            0 :     request: Request<Body>,
    1819            0 :     _cancel: CancellationToken,
    1820            0 : ) -> Result<Response<Body>, ApiError> {
    1821            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
    1822            0 :     check_permission(&request, Some(tenant_shard_id.tenant_id))?;
    1823            0 :     let timeline_id: TimelineId = parse_request_param(&request, "timeline_id")?;
    1824            0 :     let state = get_state(&request);
    1825              : 
    1826            0 :     let timeline =
    1827            0 :         active_timeline_of_active_tenant(&state.tenant_manager, tenant_shard_id, timeline_id)
    1828            0 :             .await?;
    1829            0 :     let info = timeline
    1830            0 :         .get_download_all_remote_layers_task_info()
    1831            0 :         .context("task never started since last pageserver process start")
    1832            0 :         .map_err(|e| ApiError::NotFound(e.into()))?;
    1833            0 :     json_response(StatusCode::OK, info)
    1834            0 : }
    1835              : 
    1836            0 : async fn timeline_detach_ancestor_handler(
    1837            0 :     request: Request<Body>,
    1838            0 :     _cancel: CancellationToken,
    1839            0 : ) -> Result<Response<Body>, ApiError> {
    1840              :     use crate::tenant::timeline::detach_ancestor::Options;
    1841            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
    1842            0 :     check_permission(&request, Some(tenant_shard_id.tenant_id))?;
    1843            0 :     let timeline_id: TimelineId = parse_request_param(&request, "timeline_id")?;
    1844              : 
    1845            0 :     let span = tracing::info_span!("detach_ancestor", tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug(), %timeline_id);
    1846              : 
    1847            0 :     async move {
    1848            0 :         let mut options = Options::default();
    1849              : 
    1850            0 :         let rewrite_concurrency =
    1851            0 :             parse_query_param::<_, std::num::NonZeroUsize>(&request, "rewrite_concurrency")?;
    1852            0 :         let copy_concurrency =
    1853            0 :             parse_query_param::<_, std::num::NonZeroUsize>(&request, "copy_concurrency")?;
    1854              : 
    1855            0 :         [
    1856            0 :             (&mut options.rewrite_concurrency, rewrite_concurrency),
    1857            0 :             (&mut options.copy_concurrency, copy_concurrency),
    1858            0 :         ]
    1859            0 :         .into_iter()
    1860            0 :         .filter_map(|(target, val)| val.map(|val| (target, val)))
    1861            0 :         .for_each(|(target, val)| *target = val);
    1862            0 : 
    1863            0 :         let state = get_state(&request);
    1864              : 
    1865            0 :         let tenant = state
    1866            0 :             .tenant_manager
    1867            0 :             .get_attached_tenant_shard(tenant_shard_id)?;
    1868              : 
    1869            0 :         tenant.wait_to_become_active(ACTIVE_TENANT_TIMEOUT).await?;
    1870              : 
    1871            0 :         let ctx = RequestContext::new(TaskKind::DetachAncestor, DownloadBehavior::Download);
    1872            0 :         let ctx = &ctx;
    1873              : 
    1874            0 :         let timeline = tenant
    1875            0 :             .get_timeline(timeline_id, true)
    1876            0 :             .map_err(|e| ApiError::NotFound(e.into()))?;
    1877              : 
    1878            0 :         let (_guard, prepared) = timeline
    1879            0 :             .prepare_to_detach_from_ancestor(&tenant, options, ctx)
    1880            0 :             .await
    1881            0 :             .map_err(|e| ApiError::InternalServerError(e.into()))?;
    1882              : 
    1883            0 :         let res = state
    1884            0 :             .tenant_manager
    1885            0 :             .complete_detaching_timeline_ancestor(tenant_shard_id, timeline_id, prepared, ctx)
    1886            0 :             .await;
    1887              : 
    1888            0 :         match res {
    1889            0 :             Ok(reparented_timelines) => {
    1890            0 :                 let resp = pageserver_api::models::detach_ancestor::AncestorDetached {
    1891            0 :                     reparented_timelines,
    1892            0 :                 };
    1893            0 : 
    1894            0 :                 json_response(StatusCode::OK, resp)
    1895              :             }
    1896            0 :             Err(e) => Err(ApiError::InternalServerError(
    1897            0 :                 e.context("timeline detach completion"),
    1898            0 :             )),
    1899              :         }
    1900            0 :     }
    1901            0 :     .instrument(span)
    1902            0 :     .await
    1903            0 : }
    1904              : 
    1905            0 : async fn deletion_queue_flush(
    1906            0 :     r: Request<Body>,
    1907            0 :     cancel: CancellationToken,
    1908            0 : ) -> Result<Response<Body>, ApiError> {
    1909            0 :     let state = get_state(&r);
    1910            0 : 
    1911            0 :     if state.remote_storage.is_none() {
    1912              :         // Nothing to do if remote storage is disabled.
    1913            0 :         return json_response(StatusCode::OK, ());
    1914            0 :     }
    1915              : 
    1916            0 :     let execute = parse_query_param(&r, "execute")?.unwrap_or(false);
    1917            0 : 
    1918            0 :     let flush = async {
    1919            0 :         if execute {
    1920            0 :             state.deletion_queue_client.flush_execute().await
    1921              :         } else {
    1922            0 :             state.deletion_queue_client.flush().await
    1923              :         }
    1924            0 :     }
    1925              :     // DeletionQueueError's only case is shutting down.
    1926            0 :     .map_err(|_| ApiError::ShuttingDown);
    1927              : 
    1928              :     tokio::select! {
    1929              :         res = flush => {
    1930            0 :             res.map(|()| json_response(StatusCode::OK, ()))?
    1931              :         }
    1932              :         _ = cancel.cancelled() => {
    1933              :             Err(ApiError::ShuttingDown)
    1934              :         }
    1935              :     }
    1936            0 : }
    1937              : 
    1938              : /// Try if `GetPage@Lsn` is successful, useful for manual debugging.
    1939            0 : async fn getpage_at_lsn_handler(
    1940            0 :     request: Request<Body>,
    1941            0 :     _cancel: CancellationToken,
    1942            0 : ) -> Result<Response<Body>, ApiError> {
    1943            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
    1944            0 :     let timeline_id: TimelineId = parse_request_param(&request, "timeline_id")?;
    1945            0 :     check_permission(&request, Some(tenant_shard_id.tenant_id))?;
    1946            0 :     let state = get_state(&request);
    1947              : 
    1948              :     struct Key(crate::repository::Key);
    1949              : 
    1950              :     impl std::str::FromStr for Key {
    1951              :         type Err = anyhow::Error;
    1952              : 
    1953            0 :         fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
    1954            0 :             crate::repository::Key::from_hex(s).map(Key)
    1955            0 :         }
    1956              :     }
    1957              : 
    1958            0 :     let key: Key = parse_query_param(&request, "key")?
    1959            0 :         .ok_or_else(|| ApiError::BadRequest(anyhow!("missing 'key' query parameter")))?;
    1960            0 :     let lsn: Lsn = parse_query_param(&request, "lsn")?
    1961            0 :         .ok_or_else(|| ApiError::BadRequest(anyhow!("missing 'lsn' query parameter")))?;
    1962              : 
    1963            0 :     async {
    1964            0 :         let ctx = RequestContext::new(TaskKind::MgmtRequest, DownloadBehavior::Download);
    1965            0 :         let timeline = active_timeline_of_active_tenant(&state.tenant_manager, tenant_shard_id, timeline_id).await?;
    1966              : 
    1967            0 :         let page = timeline.get(key.0, lsn, &ctx).await?;
    1968              : 
    1969            0 :         Result::<_, ApiError>::Ok(
    1970            0 :             Response::builder()
    1971            0 :                 .status(StatusCode::OK)
    1972            0 :                 .header(header::CONTENT_TYPE, "application/octet-stream")
    1973            0 :                 .body(hyper::Body::from(page))
    1974            0 :                 .unwrap(),
    1975            0 :         )
    1976            0 :     }
    1977            0 :     .instrument(info_span!("timeline_get", tenant_id = %tenant_shard_id.tenant_id, shard_id = %tenant_shard_id.shard_slug(), %timeline_id))
    1978            0 :     .await
    1979            0 : }
    1980              : 
    1981            0 : async fn timeline_collect_keyspace(
    1982            0 :     request: Request<Body>,
    1983            0 :     _cancel: CancellationToken,
    1984            0 : ) -> Result<Response<Body>, ApiError> {
    1985            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
    1986            0 :     let timeline_id: TimelineId = parse_request_param(&request, "timeline_id")?;
    1987            0 :     check_permission(&request, Some(tenant_shard_id.tenant_id))?;
    1988            0 :     let state = get_state(&request);
    1989              : 
    1990            0 :     let at_lsn: Option<Lsn> = parse_query_param(&request, "at_lsn")?;
    1991              : 
    1992            0 :     async {
    1993            0 :         let ctx = RequestContext::new(TaskKind::MgmtRequest, DownloadBehavior::Download);
    1994            0 :         let timeline = active_timeline_of_active_tenant(&state.tenant_manager, tenant_shard_id, timeline_id).await?;
    1995            0 :         let at_lsn = at_lsn.unwrap_or_else(|| timeline.get_last_record_lsn());
    1996            0 :         let (dense_ks, sparse_ks) = timeline
    1997            0 :             .collect_keyspace(at_lsn, &ctx)
    1998            0 :             .await
    1999            0 :             .map_err(|e| ApiError::InternalServerError(e.into()))?;
    2000              : 
    2001              :         // This API is currently used by pagebench. Pagebench will iterate all keys within the keyspace.
    2002              :         // Therefore, we split dense/sparse keys in this API.
    2003            0 :         let res = pageserver_api::models::partitioning::Partitioning { keys: dense_ks, sparse_keys: sparse_ks, at_lsn };
    2004            0 : 
    2005            0 :         json_response(StatusCode::OK, res)
    2006            0 :     }
    2007            0 :     .instrument(info_span!("timeline_collect_keyspace", tenant_id = %tenant_shard_id.tenant_id, shard_id = %tenant_shard_id.shard_slug(), %timeline_id))
    2008            0 :     .await
    2009            0 : }
    2010              : 
    2011            0 : async fn active_timeline_of_active_tenant(
    2012            0 :     tenant_manager: &TenantManager,
    2013            0 :     tenant_shard_id: TenantShardId,
    2014            0 :     timeline_id: TimelineId,
    2015            0 : ) -> Result<Arc<Timeline>, ApiError> {
    2016            0 :     let tenant = tenant_manager.get_attached_tenant_shard(tenant_shard_id)?;
    2017              : 
    2018            0 :     tenant.wait_to_become_active(ACTIVE_TENANT_TIMEOUT).await?;
    2019              : 
    2020            0 :     tenant
    2021            0 :         .get_timeline(timeline_id, true)
    2022            0 :         .map_err(|e| ApiError::NotFound(e.into()))
    2023            0 : }
    2024              : 
    2025            0 : async fn always_panic_handler(
    2026            0 :     req: Request<Body>,
    2027            0 :     _cancel: CancellationToken,
    2028            0 : ) -> Result<Response<Body>, ApiError> {
    2029            0 :     // Deliberately cause a panic to exercise the panic hook registered via std::panic::set_hook().
    2030            0 :     // For pageserver, the relevant panic hook is `tracing_panic_hook` , and the `sentry` crate's wrapper around it.
    2031            0 :     // Use catch_unwind to ensure that tokio nor hyper are distracted by our panic.
    2032            0 :     let query = req.uri().query();
    2033            0 :     let _ = std::panic::catch_unwind(|| {
    2034            0 :         panic!("unconditional panic for testing panic hook integration; request query: {query:?}")
    2035            0 :     });
    2036            0 :     json_response(StatusCode::NO_CONTENT, ())
    2037            0 : }
    2038              : 
    2039            0 : async fn disk_usage_eviction_run(
    2040            0 :     mut r: Request<Body>,
    2041            0 :     cancel: CancellationToken,
    2042            0 : ) -> Result<Response<Body>, ApiError> {
    2043            0 :     check_permission(&r, None)?;
    2044              : 
    2045            0 :     #[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)]
    2046              :     struct Config {
    2047              :         /// How many bytes to evict before reporting that pressure is relieved.
    2048              :         evict_bytes: u64,
    2049              : 
    2050              :         #[serde(default)]
    2051              :         eviction_order: crate::disk_usage_eviction_task::EvictionOrder,
    2052              :     }
    2053              : 
    2054              :     #[derive(Debug, Clone, Copy, serde::Serialize)]
    2055              :     struct Usage {
    2056              :         // remains unchanged after instantiation of the struct
    2057              :         evict_bytes: u64,
    2058              :         // updated by `add_available_bytes`
    2059              :         freed_bytes: u64,
    2060              :     }
    2061              : 
    2062              :     impl crate::disk_usage_eviction_task::Usage for Usage {
    2063            0 :         fn has_pressure(&self) -> bool {
    2064            0 :             self.evict_bytes > self.freed_bytes
    2065            0 :         }
    2066              : 
    2067            0 :         fn add_available_bytes(&mut self, bytes: u64) {
    2068            0 :             self.freed_bytes += bytes;
    2069            0 :         }
    2070              :     }
    2071              : 
    2072            0 :     let config = json_request::<Config>(&mut r).await?;
    2073              : 
    2074            0 :     let usage = Usage {
    2075            0 :         evict_bytes: config.evict_bytes,
    2076            0 :         freed_bytes: 0,
    2077            0 :     };
    2078            0 : 
    2079            0 :     let state = get_state(&r);
    2080              : 
    2081            0 :     let Some(storage) = state.remote_storage.as_ref() else {
    2082            0 :         return Err(ApiError::InternalServerError(anyhow::anyhow!(
    2083            0 :             "remote storage not configured, cannot run eviction iteration"
    2084            0 :         )));
    2085              :     };
    2086              : 
    2087            0 :     let eviction_state = state.disk_usage_eviction_state.clone();
    2088              : 
    2089            0 :     let res = crate::disk_usage_eviction_task::disk_usage_eviction_task_iteration_impl(
    2090            0 :         &eviction_state,
    2091            0 :         storage,
    2092            0 :         usage,
    2093            0 :         &state.tenant_manager,
    2094            0 :         config.eviction_order,
    2095            0 :         &cancel,
    2096            0 :     )
    2097            0 :     .await;
    2098              : 
    2099            0 :     info!(?res, "disk_usage_eviction_task_iteration_impl finished");
    2100              : 
    2101            0 :     let res = res.map_err(ApiError::InternalServerError)?;
    2102              : 
    2103            0 :     json_response(StatusCode::OK, res)
    2104            0 : }
    2105              : 
    2106            0 : async fn secondary_upload_handler(
    2107            0 :     request: Request<Body>,
    2108            0 :     _cancel: CancellationToken,
    2109            0 : ) -> Result<Response<Body>, ApiError> {
    2110            0 :     let state = get_state(&request);
    2111            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
    2112            0 :     state
    2113            0 :         .secondary_controller
    2114            0 :         .upload_tenant(tenant_shard_id)
    2115            0 :         .await
    2116            0 :         .map_err(ApiError::InternalServerError)?;
    2117              : 
    2118            0 :     json_response(StatusCode::OK, ())
    2119            0 : }
    2120              : 
    2121            0 : async fn tenant_scan_remote_handler(
    2122            0 :     request: Request<Body>,
    2123            0 :     cancel: CancellationToken,
    2124            0 : ) -> Result<Response<Body>, ApiError> {
    2125            0 :     let state = get_state(&request);
    2126            0 :     let tenant_id: TenantId = parse_request_param(&request, "tenant_id")?;
    2127              : 
    2128            0 :     let Some(remote_storage) = state.remote_storage.as_ref() else {
    2129            0 :         return Err(ApiError::BadRequest(anyhow::anyhow!(
    2130            0 :             "Remote storage not configured"
    2131            0 :         )));
    2132              :     };
    2133              : 
    2134            0 :     let mut response = TenantScanRemoteStorageResponse::default();
    2135              : 
    2136            0 :     let (shards, _other_keys) =
    2137            0 :         list_remote_tenant_shards(remote_storage, tenant_id, cancel.clone())
    2138            0 :             .await
    2139            0 :             .map_err(|e| ApiError::InternalServerError(anyhow::anyhow!(e)))?;
    2140              : 
    2141            0 :     for tenant_shard_id in shards {
    2142            0 :         let (timeline_ids, _other_keys) =
    2143            0 :             list_remote_timelines(remote_storage, tenant_shard_id, cancel.clone())
    2144            0 :                 .await
    2145            0 :                 .map_err(|e| ApiError::InternalServerError(anyhow::anyhow!(e)))?;
    2146              : 
    2147            0 :         let mut generation = Generation::none();
    2148            0 :         for timeline_id in timeline_ids {
    2149            0 :             match download_index_part(
    2150            0 :                 remote_storage,
    2151            0 :                 &tenant_shard_id,
    2152            0 :                 &timeline_id,
    2153            0 :                 Generation::MAX,
    2154            0 :                 &cancel,
    2155            0 :             )
    2156            0 :             .instrument(info_span!("download_index_part",
    2157              :                          tenant_id=%tenant_shard_id.tenant_id,
    2158            0 :                          shard_id=%tenant_shard_id.shard_slug(),
    2159              :                          %timeline_id))
    2160            0 :             .await
    2161              :             {
    2162            0 :                 Ok((index_part, index_generation)) => {
    2163            0 :                     tracing::info!("Found timeline {tenant_shard_id}/{timeline_id} metadata (gen {index_generation:?}, {} layers, {} consistent LSN)",
    2164            0 :                         index_part.layer_metadata.len(), index_part.get_disk_consistent_lsn());
    2165            0 :                     generation = std::cmp::max(generation, index_generation);
    2166              :                 }
    2167              :                 Err(DownloadError::NotFound) => {
    2168              :                     // This is normal for tenants that were created with multiple shards: they have an unsharded path
    2169              :                     // containing the timeline's initdb tarball but no index.  Otherwise it is a bit strange.
    2170            0 :                     tracing::info!("Timeline path {tenant_shard_id}/{timeline_id} exists in remote storage but has no index, skipping");
    2171            0 :                     continue;
    2172              :                 }
    2173            0 :                 Err(e) => {
    2174            0 :                     return Err(ApiError::InternalServerError(anyhow::anyhow!(e)));
    2175              :                 }
    2176              :             };
    2177              :         }
    2178              : 
    2179            0 :         response.shards.push(TenantScanRemoteStorageShard {
    2180            0 :             tenant_shard_id,
    2181            0 :             generation: generation.into(),
    2182            0 :         });
    2183              :     }
    2184              : 
    2185            0 :     if response.shards.is_empty() {
    2186            0 :         return Err(ApiError::NotFound(
    2187            0 :             anyhow::anyhow!("No shards found for tenant ID {tenant_id}").into(),
    2188            0 :         ));
    2189            0 :     }
    2190            0 : 
    2191            0 :     json_response(StatusCode::OK, response)
    2192            0 : }
    2193              : 
    2194            0 : async fn secondary_download_handler(
    2195            0 :     request: Request<Body>,
    2196            0 :     _cancel: CancellationToken,
    2197            0 : ) -> Result<Response<Body>, ApiError> {
    2198            0 :     let state = get_state(&request);
    2199            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
    2200            0 :     let wait = parse_query_param(&request, "wait_ms")?.map(Duration::from_millis);
    2201              : 
    2202              :     // We don't need this to issue the download request, but:
    2203              :     // - it enables us to cleanly return 404 if we get a request for an absent shard
    2204              :     // - we will use this to provide status feedback in the response
    2205            0 :     let Some(secondary_tenant) = state
    2206            0 :         .tenant_manager
    2207            0 :         .get_secondary_tenant_shard(tenant_shard_id)
    2208              :     else {
    2209            0 :         return Err(ApiError::NotFound(
    2210            0 :             anyhow::anyhow!("Shard {} not found", tenant_shard_id).into(),
    2211            0 :         ));
    2212              :     };
    2213              : 
    2214            0 :     let timeout = wait.unwrap_or(Duration::MAX);
    2215              : 
    2216            0 :     let status = match tokio::time::timeout(
    2217            0 :         timeout,
    2218            0 :         state.secondary_controller.download_tenant(tenant_shard_id),
    2219            0 :     )
    2220            0 :     .await
    2221              :     {
    2222              :         // Download job ran to completion.
    2223            0 :         Ok(Ok(())) => StatusCode::OK,
    2224              :         // Edge case: downloads aren't usually fallible: things like a missing heatmap are considered
    2225              :         // okay.  We could get an error here in the unlikely edge case that the tenant
    2226              :         // was detached between our check above and executing the download job.
    2227            0 :         Ok(Err(e)) => return Err(ApiError::InternalServerError(e)),
    2228              :         // A timeout is not an error: we have started the download, we're just not done
    2229              :         // yet.  The caller will get a response body indicating status.
    2230            0 :         Err(_) => StatusCode::ACCEPTED,
    2231              :     };
    2232              : 
    2233            0 :     let progress = secondary_tenant.progress.lock().unwrap().clone();
    2234            0 : 
    2235            0 :     json_response(status, progress)
    2236            0 : }
    2237              : 
    2238            0 : async fn secondary_status_handler(
    2239            0 :     request: Request<Body>,
    2240            0 :     _cancel: CancellationToken,
    2241            0 : ) -> Result<Response<Body>, ApiError> {
    2242            0 :     let state = get_state(&request);
    2243            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
    2244              : 
    2245            0 :     let Some(secondary_tenant) = state
    2246            0 :         .tenant_manager
    2247            0 :         .get_secondary_tenant_shard(tenant_shard_id)
    2248              :     else {
    2249            0 :         return Err(ApiError::NotFound(
    2250            0 :             anyhow::anyhow!("Shard {} not found", tenant_shard_id).into(),
    2251            0 :         ));
    2252              :     };
    2253              : 
    2254            0 :     let progress = secondary_tenant.progress.lock().unwrap().clone();
    2255            0 : 
    2256            0 :     json_response(StatusCode::OK, progress)
    2257            0 : }
    2258              : 
    2259            0 : async fn handler_404(_: Request<Body>) -> Result<Response<Body>, ApiError> {
    2260            0 :     json_response(
    2261            0 :         StatusCode::NOT_FOUND,
    2262            0 :         HttpErrorBody::from_msg("page not found".to_owned()),
    2263            0 :     )
    2264            0 : }
    2265              : 
    2266            0 : async fn post_tracing_event_handler(
    2267            0 :     mut r: Request<Body>,
    2268            0 :     _cancel: CancellationToken,
    2269            0 : ) -> Result<Response<Body>, ApiError> {
    2270            0 :     #[derive(Debug, serde::Deserialize)]
    2271              :     #[serde(rename_all = "lowercase")]
    2272              :     enum Level {
    2273              :         Error,
    2274              :         Warn,
    2275              :         Info,
    2276              :         Debug,
    2277              :         Trace,
    2278              :     }
    2279            0 :     #[derive(Debug, serde::Deserialize)]
    2280              :     struct Request {
    2281              :         level: Level,
    2282              :         message: String,
    2283              :     }
    2284            0 :     let body: Request = json_request(&mut r)
    2285            0 :         .await
    2286            0 :         .map_err(|_| ApiError::BadRequest(anyhow::anyhow!("invalid JSON body")))?;
    2287              : 
    2288            0 :     match body.level {
    2289            0 :         Level::Error => tracing::error!(?body.message),
    2290            0 :         Level::Warn => tracing::warn!(?body.message),
    2291            0 :         Level::Info => tracing::info!(?body.message),
    2292            0 :         Level::Debug => tracing::debug!(?body.message),
    2293            0 :         Level::Trace => tracing::trace!(?body.message),
    2294              :     }
    2295              : 
    2296            0 :     json_response(StatusCode::OK, ())
    2297            0 : }
    2298              : 
    2299            0 : async fn put_io_engine_handler(
    2300            0 :     mut r: Request<Body>,
    2301            0 :     _cancel: CancellationToken,
    2302            0 : ) -> Result<Response<Body>, ApiError> {
    2303            0 :     check_permission(&r, None)?;
    2304            0 :     let kind: crate::virtual_file::IoEngineKind = json_request(&mut r).await?;
    2305            0 :     crate::virtual_file::io_engine::set(kind);
    2306            0 :     json_response(StatusCode::OK, ())
    2307            0 : }
    2308              : 
    2309              : /// Polled by control plane.
    2310              : ///
    2311              : /// See [`crate::utilization`].
    2312            0 : async fn get_utilization(
    2313            0 :     r: Request<Body>,
    2314            0 :     _cancel: CancellationToken,
    2315            0 : ) -> Result<Response<Body>, ApiError> {
    2316            0 :     fail::fail_point!("get-utilization-http-handler", |_| {
    2317            0 :         Err(ApiError::ResourceUnavailable("failpoint".into()))
    2318            0 :     });
    2319              : 
    2320              :     // this probably could be completely public, but lets make that change later.
    2321            0 :     check_permission(&r, None)?;
    2322              : 
    2323            0 :     let state = get_state(&r);
    2324            0 :     let mut g = state.latest_utilization.lock().await;
    2325              : 
    2326            0 :     let regenerate_every = Duration::from_secs(1);
    2327            0 :     let still_valid = g
    2328            0 :         .as_ref()
    2329            0 :         .is_some_and(|(captured_at, _)| captured_at.elapsed() < regenerate_every);
    2330            0 : 
    2331            0 :     // avoid needless statvfs calls even though those should be non-blocking fast.
    2332            0 :     // regenerate at most 1Hz to allow polling at any rate.
    2333            0 :     if !still_valid {
    2334            0 :         let path = state.conf.tenants_path();
    2335            0 :         let doc = crate::utilization::regenerate(path.as_std_path())
    2336            0 :             .map_err(ApiError::InternalServerError)?;
    2337              : 
    2338            0 :         let mut buf = Vec::new();
    2339            0 :         serde_json::to_writer(&mut buf, &doc)
    2340            0 :             .context("serialize")
    2341            0 :             .map_err(ApiError::InternalServerError)?;
    2342              : 
    2343            0 :         let body = bytes::Bytes::from(buf);
    2344            0 : 
    2345            0 :         *g = Some((std::time::Instant::now(), body));
    2346            0 :     }
    2347              : 
    2348              :     // hyper 0.14 doesn't yet have Response::clone so this is a bit of extra legwork
    2349            0 :     let cached = g.as_ref().expect("just set").1.clone();
    2350            0 : 
    2351            0 :     Response::builder()
    2352            0 :         .header(hyper::http::header::CONTENT_TYPE, "application/json")
    2353            0 :         // thought of using http date header, but that is second precision which does not give any
    2354            0 :         // debugging aid
    2355            0 :         .status(StatusCode::OK)
    2356            0 :         .body(hyper::Body::from(cached))
    2357            0 :         .context("build response")
    2358            0 :         .map_err(ApiError::InternalServerError)
    2359            0 : }
    2360              : 
    2361              : /// Common functionality of all the HTTP API handlers.
    2362              : ///
    2363              : /// - Adds a tracing span to each request (by `request_span`)
    2364              : /// - Logs the request depending on the request method (by `request_span`)
    2365              : /// - Logs the response if it was not successful (by `request_span`
    2366              : /// - Shields the handler function from async cancellations. Hyper can drop the handler
    2367              : ///   Future if the connection to the client is lost, but most of the pageserver code is
    2368              : ///   not async cancellation safe. This converts the dropped future into a graceful cancellation
    2369              : ///   request with a CancellationToken.
    2370            0 : async fn api_handler<R, H>(request: Request<Body>, handler: H) -> Result<Response<Body>, ApiError>
    2371            0 : where
    2372            0 :     R: std::future::Future<Output = Result<Response<Body>, ApiError>> + Send + 'static,
    2373            0 :     H: FnOnce(Request<Body>, CancellationToken) -> R + Send + Sync + 'static,
    2374            0 : {
    2375            0 :     if request.uri() != &"/v1/failpoints".parse::<Uri>().unwrap() {
    2376            0 :         fail::fail_point!("api-503", |_| Err(ApiError::ResourceUnavailable(
    2377            0 :             "failpoint".into()
    2378            0 :         )));
    2379              : 
    2380            0 :         fail::fail_point!("api-500", |_| Err(ApiError::InternalServerError(
    2381            0 :             anyhow::anyhow!("failpoint")
    2382            0 :         )));
    2383            0 :     }
    2384              : 
    2385              :     // Spawn a new task to handle the request, to protect the handler from unexpected
    2386              :     // async cancellations. Most pageserver functions are not async cancellation safe.
    2387              :     // We arm a drop-guard, so that if Hyper drops the Future, we signal the task
    2388              :     // with the cancellation token.
    2389            0 :     let token = CancellationToken::new();
    2390            0 :     let cancel_guard = token.clone().drop_guard();
    2391            0 :     let result = request_span(request, move |r| async {
    2392            0 :         let handle = tokio::spawn(
    2393            0 :             async {
    2394            0 :                 let token_cloned = token.clone();
    2395            0 :                 let result = handler(r, token).await;
    2396            0 :                 if token_cloned.is_cancelled() {
    2397            0 :                     // dropguard has executed: we will never turn this result into response.
    2398            0 :                     //
    2399            0 :                     // at least temporarily do {:?} logging; these failures are rare enough but
    2400            0 :                     // could hide difficult errors.
    2401            0 :                     match &result {
    2402            0 :                         Ok(response) => {
    2403            0 :                             let status = response.status();
    2404            0 :                             info!(%status, "Cancelled request finished successfully")
    2405            0 :                         }
    2406            0 :                         Err(e) => error!("Cancelled request finished with an error: {e:?}"),
    2407            0 :                     }
    2408            0 :                 }
    2409            0 :                 // only logging for cancelled panicked request handlers is the tracing_panic_hook,
    2410            0 :                 // which should suffice.
    2411            0 :                 //
    2412            0 :                 // there is still a chance to lose the result due to race between
    2413            0 :                 // returning from here and the actual connection closing happening
    2414            0 :                 // before outer task gets to execute. leaving that up for #5815.
    2415            0 :                 result
    2416            0 :             }
    2417            0 :             .in_current_span(),
    2418            0 :         );
    2419            0 : 
    2420            0 :         match handle.await {
    2421            0 :             // TODO: never actually return Err from here, always Ok(...) so that we can log
    2422            0 :             // spanned errors. Call api_error_handler instead and return appropriate Body.
    2423            0 :             Ok(result) => result,
    2424            0 :             Err(e) => {
    2425            0 :                 // The handler task panicked. We have a global panic handler that logs the
    2426            0 :                 // panic with its backtrace, so no need to log that here. Only log a brief
    2427            0 :                 // message to make it clear that we returned the error to the client.
    2428            0 :                 error!("HTTP request handler task panicked: {e:#}");
    2429            0 : 
    2430            0 :                 // Don't return an Error here, because then fallback error handler that was
    2431            0 :                 // installed in make_router() will print the error. Instead, construct the
    2432            0 :                 // HTTP error response and return that.
    2433            0 :                 Ok(
    2434            0 :                     ApiError::InternalServerError(anyhow!("HTTP request handler task panicked"))
    2435            0 :                         .into_response(),
    2436            0 :                 )
    2437            0 :             }
    2438            0 :         }
    2439            0 :     })
    2440            0 :     .await;
    2441              : 
    2442            0 :     cancel_guard.disarm();
    2443            0 : 
    2444            0 :     result
    2445            0 : }
    2446              : 
    2447              : /// Like api_handler, but returns an error response if the server is built without
    2448              : /// the 'testing' feature.
    2449            0 : async fn testing_api_handler<R, H>(
    2450            0 :     desc: &str,
    2451            0 :     request: Request<Body>,
    2452            0 :     handler: H,
    2453            0 : ) -> Result<Response<Body>, ApiError>
    2454            0 : where
    2455            0 :     R: std::future::Future<Output = Result<Response<Body>, ApiError>> + Send + 'static,
    2456            0 :     H: FnOnce(Request<Body>, CancellationToken) -> R + Send + Sync + 'static,
    2457            0 : {
    2458            0 :     if cfg!(feature = "testing") {
    2459            0 :         api_handler(request, handler).await
    2460              :     } else {
    2461            0 :         std::future::ready(Err(ApiError::BadRequest(anyhow!(
    2462            0 :             "Cannot {desc} because pageserver was compiled without testing APIs",
    2463            0 :         ))))
    2464            0 :         .await
    2465              :     }
    2466            0 : }
    2467              : 
    2468            0 : pub fn make_router(
    2469            0 :     state: Arc<State>,
    2470            0 :     launch_ts: &'static LaunchTimestamp,
    2471            0 :     auth: Option<Arc<SwappableJwtAuth>>,
    2472            0 : ) -> anyhow::Result<RouterBuilder<hyper::Body, ApiError>> {
    2473            0 :     let spec = include_bytes!("openapi_spec.yml");
    2474            0 :     let mut router = attach_openapi_ui(endpoint::make_router(), spec, "/swagger.yml", "/v1/doc");
    2475            0 :     if auth.is_some() {
    2476            0 :         router = router.middleware(auth_middleware(|request| {
    2477            0 :             let state = get_state(request);
    2478            0 :             if state.allowlist_routes.contains(request.uri()) {
    2479            0 :                 None
    2480              :             } else {
    2481            0 :                 state.auth.as_deref()
    2482              :             }
    2483            0 :         }))
    2484            0 :     }
    2485              : 
    2486            0 :     router = router.middleware(
    2487            0 :         endpoint::add_response_header_middleware(
    2488            0 :             "PAGESERVER_LAUNCH_TIMESTAMP",
    2489            0 :             &launch_ts.to_string(),
    2490            0 :         )
    2491            0 :         .expect("construct launch timestamp header middleware"),
    2492            0 :     );
    2493            0 : 
    2494            0 :     Ok(router
    2495            0 :         .data(state)
    2496            0 :         .get("/metrics", |r| request_span(r, prometheus_metrics_handler))
    2497            0 :         .get("/v1/status", |r| api_handler(r, status_handler))
    2498            0 :         .put("/v1/failpoints", |r| {
    2499            0 :             testing_api_handler("manage failpoints", r, failpoints_handler)
    2500            0 :         })
    2501            0 :         .post("/v1/reload_auth_validation_keys", |r| {
    2502            0 :             api_handler(r, reload_auth_validation_keys_handler)
    2503            0 :         })
    2504            0 :         .get("/v1/tenant", |r| api_handler(r, tenant_list_handler))
    2505            0 :         .post("/v1/tenant", |r| api_handler(r, tenant_create_handler))
    2506            0 :         .get("/v1/tenant/:tenant_shard_id", |r| {
    2507            0 :             api_handler(r, tenant_status)
    2508            0 :         })
    2509            0 :         .delete("/v1/tenant/:tenant_shard_id", |r| {
    2510            0 :             api_handler(r, tenant_delete_handler)
    2511            0 :         })
    2512            0 :         .get("/v1/tenant/:tenant_shard_id/synthetic_size", |r| {
    2513            0 :             api_handler(r, tenant_size_handler)
    2514            0 :         })
    2515            0 :         .put("/v1/tenant/config", |r| {
    2516            0 :             api_handler(r, update_tenant_config_handler)
    2517            0 :         })
    2518            0 :         .put("/v1/tenant/:tenant_shard_id/shard_split", |r| {
    2519            0 :             api_handler(r, tenant_shard_split_handler)
    2520            0 :         })
    2521            0 :         .get("/v1/tenant/:tenant_shard_id/config", |r| {
    2522            0 :             api_handler(r, get_tenant_config_handler)
    2523            0 :         })
    2524            0 :         .put("/v1/tenant/:tenant_shard_id/location_config", |r| {
    2525            0 :             api_handler(r, put_tenant_location_config_handler)
    2526            0 :         })
    2527            0 :         .get("/v1/location_config", |r| {
    2528            0 :             api_handler(r, list_location_config_handler)
    2529            0 :         })
    2530            0 :         .get("/v1/location_config/:tenant_shard_id", |r| {
    2531            0 :             api_handler(r, get_location_config_handler)
    2532            0 :         })
    2533            0 :         .put(
    2534            0 :             "/v1/tenant/:tenant_shard_id/time_travel_remote_storage",
    2535            0 :             |r| api_handler(r, tenant_time_travel_remote_storage_handler),
    2536            0 :         )
    2537            0 :         .get("/v1/tenant/:tenant_shard_id/timeline", |r| {
    2538            0 :             api_handler(r, timeline_list_handler)
    2539            0 :         })
    2540            0 :         .post("/v1/tenant/:tenant_shard_id/timeline", |r| {
    2541            0 :             api_handler(r, timeline_create_handler)
    2542            0 :         })
    2543            0 :         .post("/v1/tenant/:tenant_id/attach", |r| {
    2544            0 :             api_handler(r, tenant_attach_handler)
    2545            0 :         })
    2546            0 :         .post("/v1/tenant/:tenant_id/detach", |r| {
    2547            0 :             api_handler(r, tenant_detach_handler)
    2548            0 :         })
    2549            0 :         .post("/v1/tenant/:tenant_shard_id/reset", |r| {
    2550            0 :             api_handler(r, tenant_reset_handler)
    2551            0 :         })
    2552            0 :         .post("/v1/tenant/:tenant_id/load", |r| {
    2553            0 :             api_handler(r, tenant_load_handler)
    2554            0 :         })
    2555            0 :         .post("/v1/tenant/:tenant_id/ignore", |r| {
    2556            0 :             api_handler(r, tenant_ignore_handler)
    2557            0 :         })
    2558            0 :         .post(
    2559            0 :             "/v1/tenant/:tenant_shard_id/timeline/:timeline_id/preserve_initdb_archive",
    2560            0 :             |r| api_handler(r, timeline_preserve_initdb_handler),
    2561            0 :         )
    2562            0 :         .get("/v1/tenant/:tenant_shard_id/timeline/:timeline_id", |r| {
    2563            0 :             api_handler(r, timeline_detail_handler)
    2564            0 :         })
    2565            0 :         .get(
    2566            0 :             "/v1/tenant/:tenant_shard_id/timeline/:timeline_id/get_lsn_by_timestamp",
    2567            0 :             |r| api_handler(r, get_lsn_by_timestamp_handler),
    2568            0 :         )
    2569            0 :         .get(
    2570            0 :             "/v1/tenant/:tenant_shard_id/timeline/:timeline_id/get_timestamp_of_lsn",
    2571            0 :             |r| api_handler(r, get_timestamp_of_lsn_handler),
    2572            0 :         )
    2573            0 :         .put(
    2574            0 :             "/v1/tenant/:tenant_shard_id/timeline/:timeline_id/do_gc",
    2575            0 :             |r| api_handler(r, timeline_gc_handler),
    2576            0 :         )
    2577            0 :         .put(
    2578            0 :             "/v1/tenant/:tenant_shard_id/timeline/:timeline_id/compact",
    2579            0 :             |r| testing_api_handler("run timeline compaction", r, timeline_compact_handler),
    2580            0 :         )
    2581            0 :         .put(
    2582            0 :             "/v1/tenant/:tenant_shard_id/timeline/:timeline_id/checkpoint",
    2583            0 :             |r| testing_api_handler("run timeline checkpoint", r, timeline_checkpoint_handler),
    2584            0 :         )
    2585            0 :         .post(
    2586            0 :             "/v1/tenant/:tenant_shard_id/timeline/:timeline_id/download_remote_layers",
    2587            0 :             |r| api_handler(r, timeline_download_remote_layers_handler_post),
    2588            0 :         )
    2589            0 :         .get(
    2590            0 :             "/v1/tenant/:tenant_shard_id/timeline/:timeline_id/download_remote_layers",
    2591            0 :             |r| api_handler(r, timeline_download_remote_layers_handler_get),
    2592            0 :         )
    2593            0 :         .put(
    2594            0 :             "/v1/tenant/:tenant_shard_id/timeline/:timeline_id/detach_ancestor",
    2595            0 :             |r| api_handler(r, timeline_detach_ancestor_handler),
    2596            0 :         )
    2597            0 :         .delete("/v1/tenant/:tenant_shard_id/timeline/:timeline_id", |r| {
    2598            0 :             api_handler(r, timeline_delete_handler)
    2599            0 :         })
    2600            0 :         .get(
    2601            0 :             "/v1/tenant/:tenant_shard_id/timeline/:timeline_id/layer",
    2602            0 :             |r| api_handler(r, layer_map_info_handler),
    2603            0 :         )
    2604            0 :         .get(
    2605            0 :             "/v1/tenant/:tenant_shard_id/timeline/:timeline_id/layer/:layer_file_name",
    2606            0 :             |r| api_handler(r, layer_download_handler),
    2607            0 :         )
    2608            0 :         .delete(
    2609            0 :             "/v1/tenant/:tenant_shard_id/timeline/:timeline_id/layer/:layer_file_name",
    2610            0 :             |r| api_handler(r, evict_timeline_layer_handler),
    2611            0 :         )
    2612            0 :         .post("/v1/tenant/:tenant_shard_id/heatmap_upload", |r| {
    2613            0 :             api_handler(r, secondary_upload_handler)
    2614            0 :         })
    2615            0 :         .get("/v1/tenant/:tenant_id/scan_remote_storage", |r| {
    2616            0 :             api_handler(r, tenant_scan_remote_handler)
    2617            0 :         })
    2618            0 :         .put("/v1/disk_usage_eviction/run", |r| {
    2619            0 :             api_handler(r, disk_usage_eviction_run)
    2620            0 :         })
    2621            0 :         .put("/v1/deletion_queue/flush", |r| {
    2622            0 :             api_handler(r, deletion_queue_flush)
    2623            0 :         })
    2624            0 :         .get("/v1/tenant/:tenant_shard_id/secondary/status", |r| {
    2625            0 :             api_handler(r, secondary_status_handler)
    2626            0 :         })
    2627            0 :         .post("/v1/tenant/:tenant_shard_id/secondary/download", |r| {
    2628            0 :             api_handler(r, secondary_download_handler)
    2629            0 :         })
    2630            0 :         .put("/v1/tenant/:tenant_shard_id/break", |r| {
    2631            0 :             testing_api_handler("set tenant state to broken", r, handle_tenant_break)
    2632            0 :         })
    2633            0 :         .get("/v1/panic", |r| api_handler(r, always_panic_handler))
    2634            0 :         .post("/v1/tracing/event", |r| {
    2635            0 :             testing_api_handler("emit a tracing event", r, post_tracing_event_handler)
    2636            0 :         })
    2637            0 :         .get(
    2638            0 :             "/v1/tenant/:tenant_shard_id/timeline/:timeline_id/getpage",
    2639            0 :             |r| testing_api_handler("getpage@lsn", r, getpage_at_lsn_handler),
    2640            0 :         )
    2641            0 :         .get(
    2642            0 :             "/v1/tenant/:tenant_shard_id/timeline/:timeline_id/keyspace",
    2643            0 :             |r| api_handler(r, timeline_collect_keyspace),
    2644            0 :         )
    2645            0 :         .put("/v1/io_engine", |r| api_handler(r, put_io_engine_handler))
    2646            0 :         .get("/v1/utilization", |r| api_handler(r, get_utilization))
    2647            0 :         .any(handler_404))
    2648            0 : }
        

Generated by: LCOV version 2.1-beta