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