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