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

Generated by: LCOV version 2.1-beta