LCOV - code coverage report
Current view: top level - pageserver/src/http - routes.rs (source / functions) Coverage Total Hit
Test: 65975feb441523e1ae5866ecbec0610188cb8ce3.info Lines: 0.0 % 2610 0
Test Date: 2025-02-12 20:31:43 Functions: 0.0 % 802 0

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

Generated by: LCOV version 2.1-beta