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