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