LCOV - code coverage report
Current view: top level - pageserver/src/http - routes.rs (source / functions) Coverage Total Hit
Test: 09e7485004805bd42b53a0c369170b3228136512.info Lines: 0.0 % 2357 0
Test Date: 2024-11-21 18:36:18 Functions: 0.0 % 744 0

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

Generated by: LCOV version 2.1-beta