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