LCOV - code coverage report
Current view: top level - pageserver/src/http - routes.rs (source / functions) Coverage Total Hit
Test: 83fdc07b20afb411eb00587331b88259a1ff6742.info Lines: 0.0 % 2124 0
Test Date: 2024-06-20 09:39:16 Functions: 0.0 % 682 0

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

Generated by: LCOV version 2.1-beta