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