LCOV - code coverage report
Current view: top level - pageserver/src/http - routes.rs (source / functions) Coverage Total Hit
Test: bb522999b2ee0ee028df22bb188d3a84170ba700.info Lines: 0.0 % 2161 0
Test Date: 2024-07-21 16:16:09 Functions: 0.0 % 677 0

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

Generated by: LCOV version 2.1-beta