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