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

Generated by: LCOV version 2.1-beta