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