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