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