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