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

Generated by: LCOV version 2.1-beta