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