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