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