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

Generated by: LCOV version 2.1-beta