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

Generated by: LCOV version 2.1-beta