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