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

Generated by: LCOV version 2.1-beta