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