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

Generated by: LCOV version 2.1-beta