Line data Source code
1 : use std::str::FromStr;
2 : use std::sync::{Arc, LazyLock};
3 : use std::time::{Duration, Instant};
4 :
5 : use anyhow::Context;
6 : use control_plane::storage_controller::{AttachHookRequest, InspectRequest};
7 : use futures::Future;
8 : use http_utils::endpoint::{
9 : self, auth_middleware, check_permission_with, profile_cpu_handler, profile_heap_handler,
10 : request_span,
11 : };
12 : use http_utils::error::ApiError;
13 : use http_utils::failpoints::failpoints_handler;
14 : use http_utils::json::{json_request, json_response};
15 : use http_utils::request::{must_get_query_param, parse_query_param, parse_request_param};
16 : use http_utils::{RequestExt, RouterBuilder};
17 : use hyper::header::CONTENT_TYPE;
18 : use hyper::{Body, Request, Response, StatusCode, Uri};
19 : use metrics::{BuildInfo, NeonMetrics};
20 : use pageserver_api::controller_api::{
21 : MetadataHealthListOutdatedRequest, MetadataHealthListOutdatedResponse,
22 : MetadataHealthListUnhealthyResponse, MetadataHealthUpdateRequest, MetadataHealthUpdateResponse,
23 : NodeAvailability, NodeConfigureRequest, NodeRegisterRequest, SafekeeperSchedulingPolicyRequest,
24 : ShardsPreferredAzsRequest, TenantCreateRequest, TenantPolicyRequest, TenantShardMigrateRequest,
25 : TimelineImportRequest,
26 : };
27 : use pageserver_api::models::{
28 : DetachBehavior, LsnLeaseRequest, TenantConfigPatchRequest, TenantConfigRequest,
29 : TenantLocationConfigRequest, TenantShardSplitRequest, TenantTimeTravelRequest,
30 : TimelineArchivalConfigRequest, TimelineCreateRequest,
31 : };
32 : use pageserver_api::shard::TenantShardId;
33 : use pageserver_api::upcall_api::{
34 : PutTimelineImportStatusRequest, ReAttachRequest, TimelineImportStatusRequest, ValidateRequest,
35 : };
36 : use pageserver_client::{BlockUnblock, mgmt_api};
37 : use routerify::Middleware;
38 : use tokio_util::sync::CancellationToken;
39 : use tracing::warn;
40 : use utils::auth::{Scope, SwappableJwtAuth};
41 : use utils::id::{NodeId, TenantId, TimelineId};
42 :
43 : use crate::http;
44 : use crate::metrics::{
45 : HttpRequestLatencyLabelGroup, HttpRequestStatusLabelGroup, METRICS_REGISTRY,
46 : PageserverRequestLabelGroup,
47 : };
48 : use crate::persistence::SafekeeperUpsert;
49 : use crate::reconciler::ReconcileError;
50 : use crate::service::{LeadershipStatus, RECONCILE_TIMEOUT, STARTUP_RECONCILE_TIMEOUT, Service};
51 :
52 : /// State available to HTTP request handlers
53 : pub struct HttpState {
54 : service: Arc<crate::service::Service>,
55 : auth: Option<Arc<SwappableJwtAuth>>,
56 : rate_limiter: governor::DefaultKeyedRateLimiter<TenantId>,
57 : neon_metrics: NeonMetrics,
58 : allowlist_routes: &'static [&'static str],
59 : }
60 :
61 : impl HttpState {
62 0 : pub fn new(
63 0 : service: Arc<crate::service::Service>,
64 0 : auth: Option<Arc<SwappableJwtAuth>>,
65 0 : build_info: BuildInfo,
66 0 : ) -> Self {
67 0 : let quota = governor::Quota::per_second(service.get_config().tenant_rate_limit);
68 0 : Self {
69 0 : service,
70 0 : auth,
71 0 : rate_limiter: governor::RateLimiter::keyed(quota),
72 0 : neon_metrics: NeonMetrics::new(build_info),
73 0 : allowlist_routes: &[
74 0 : "/status",
75 0 : "/live",
76 0 : "/ready",
77 0 : "/metrics",
78 0 : "/profile/cpu",
79 0 : "/profile/heap",
80 0 : ],
81 0 : }
82 0 : }
83 : }
84 :
85 : #[inline(always)]
86 0 : fn get_state(request: &Request<Body>) -> &HttpState {
87 0 : request
88 0 : .data::<Arc<HttpState>>()
89 0 : .expect("unknown state type")
90 0 : .as_ref()
91 0 : }
92 :
93 : /// Rate limits tenant requests.
94 : ///
95 : /// TODO: this should be a request middleware, but requires us to extract the tenant ID from
96 : /// different URLs in a systematic way.
97 : ///
98 : /// TODO: consider returning a 429 response if these start piling up.
99 0 : async fn maybe_rate_limit(request: &Request<Body>, tenant_id: TenantId) {
100 0 : // Check if the tenant should be rate-limited.
101 0 : let rate_limiter = &get_state(request).rate_limiter;
102 0 : if rate_limiter.check_key(&tenant_id).is_ok() {
103 0 : return;
104 0 : }
105 0 :
106 0 : // Measure the rate limiting delay.
107 0 : let _timer = METRICS_REGISTRY
108 0 : .metrics_group
109 0 : .storage_controller_http_request_rate_limited
110 0 : .start_timer();
111 :
112 : // Log rate limited tenants once every 10 seconds.
113 : static LOG_RATE_LIMITER: LazyLock<governor::DefaultKeyedRateLimiter<TenantId>> =
114 0 : LazyLock::new(|| {
115 0 : let quota = governor::Quota::with_period(Duration::from_secs(10)).unwrap();
116 0 : governor::RateLimiter::keyed(quota)
117 0 : });
118 :
119 0 : if LOG_RATE_LIMITER.check_key(&tenant_id).is_ok() {
120 0 : warn!("tenant {tenant_id} is rate limited")
121 0 : }
122 :
123 : // Wait for quota.
124 0 : rate_limiter.until_key_ready(&tenant_id).await;
125 0 : }
126 :
127 : /// Pageserver calls into this on startup, to learn which tenants it should attach
128 0 : async fn handle_re_attach(req: Request<Body>) -> Result<Response<Body>, ApiError> {
129 0 : check_permissions(&req, Scope::GenerationsApi)?;
130 :
131 0 : let mut req = match maybe_forward(req).await {
132 0 : ForwardOutcome::Forwarded(res) => {
133 0 : return res;
134 : }
135 0 : ForwardOutcome::NotForwarded(req) => req,
136 : };
137 :
138 0 : let reattach_req = json_request::<ReAttachRequest>(&mut req).await?;
139 0 : let state = get_state(&req);
140 0 : json_response(StatusCode::OK, state.service.re_attach(reattach_req).await?)
141 0 : }
142 :
143 : /// Pageserver calls into this before doing deletions, to confirm that it still
144 : /// holds the latest generation for the tenants with deletions enqueued
145 0 : async fn handle_validate(req: Request<Body>) -> Result<Response<Body>, ApiError> {
146 0 : check_permissions(&req, Scope::GenerationsApi)?;
147 :
148 0 : let mut req = match maybe_forward(req).await {
149 0 : ForwardOutcome::Forwarded(res) => {
150 0 : return res;
151 : }
152 0 : ForwardOutcome::NotForwarded(req) => req,
153 : };
154 :
155 0 : let validate_req = json_request::<ValidateRequest>(&mut req).await?;
156 0 : let state = get_state(&req);
157 0 : json_response(StatusCode::OK, state.service.validate(validate_req).await?)
158 0 : }
159 :
160 0 : async fn handle_get_timeline_import_status(req: Request<Body>) -> Result<Response<Body>, ApiError> {
161 0 : check_permissions(&req, Scope::GenerationsApi)?;
162 :
163 0 : let mut req = match maybe_forward(req).await {
164 0 : ForwardOutcome::Forwarded(res) => {
165 0 : return res;
166 : }
167 0 : ForwardOutcome::NotForwarded(req) => req,
168 : };
169 :
170 0 : let get_req = json_request::<TimelineImportStatusRequest>(&mut req).await?;
171 :
172 0 : let state = get_state(&req);
173 0 :
174 0 : json_response(
175 0 : StatusCode::OK,
176 0 : state
177 0 : .service
178 0 : .handle_timeline_shard_import_progress(get_req)
179 0 : .await?,
180 : )
181 0 : }
182 :
183 0 : async fn handle_put_timeline_import_status(req: Request<Body>) -> Result<Response<Body>, ApiError> {
184 0 : check_permissions(&req, Scope::GenerationsApi)?;
185 :
186 0 : let mut req = match maybe_forward(req).await {
187 0 : ForwardOutcome::Forwarded(res) => {
188 0 : return res;
189 : }
190 0 : ForwardOutcome::NotForwarded(req) => req,
191 : };
192 :
193 0 : let put_req = json_request::<PutTimelineImportStatusRequest>(&mut req).await?;
194 :
195 0 : let state = get_state(&req);
196 0 : json_response(
197 0 : StatusCode::OK,
198 0 : state
199 0 : .service
200 0 : .handle_timeline_shard_import_progress_upcall(put_req)
201 0 : .await?,
202 : )
203 0 : }
204 :
205 : /// Call into this before attaching a tenant to a pageserver, to acquire a generation number
206 : /// (in the real control plane this is unnecessary, because the same program is managing
207 : /// generation numbers and doing attachments).
208 0 : async fn handle_attach_hook(req: Request<Body>) -> Result<Response<Body>, ApiError> {
209 0 : check_permissions(&req, Scope::Admin)?;
210 :
211 0 : let mut req = match maybe_forward(req).await {
212 0 : ForwardOutcome::Forwarded(res) => {
213 0 : return res;
214 : }
215 0 : ForwardOutcome::NotForwarded(req) => req,
216 : };
217 :
218 0 : let attach_req = json_request::<AttachHookRequest>(&mut req).await?;
219 0 : let state = get_state(&req);
220 0 :
221 0 : json_response(
222 0 : StatusCode::OK,
223 0 : state
224 0 : .service
225 0 : .attach_hook(attach_req)
226 0 : .await
227 0 : .map_err(ApiError::InternalServerError)?,
228 : )
229 0 : }
230 :
231 0 : async fn handle_inspect(req: Request<Body>) -> Result<Response<Body>, ApiError> {
232 0 : check_permissions(&req, Scope::Admin)?;
233 :
234 0 : let mut req = match maybe_forward(req).await {
235 0 : ForwardOutcome::Forwarded(res) => {
236 0 : return res;
237 : }
238 0 : ForwardOutcome::NotForwarded(req) => req,
239 : };
240 :
241 0 : let inspect_req = json_request::<InspectRequest>(&mut req).await?;
242 :
243 0 : let state = get_state(&req);
244 0 :
245 0 : json_response(StatusCode::OK, state.service.inspect(inspect_req))
246 0 : }
247 :
248 0 : async fn handle_tenant_create(
249 0 : service: Arc<Service>,
250 0 : req: Request<Body>,
251 0 : ) -> Result<Response<Body>, ApiError> {
252 0 : check_permissions(&req, Scope::PageServerApi)?;
253 :
254 0 : let mut req = match maybe_forward(req).await {
255 0 : ForwardOutcome::Forwarded(res) => {
256 0 : return res;
257 : }
258 0 : ForwardOutcome::NotForwarded(req) => req,
259 : };
260 :
261 0 : let create_req = json_request::<TenantCreateRequest>(&mut req).await?;
262 :
263 : json_response(
264 : StatusCode::CREATED,
265 0 : service.tenant_create(create_req).await?,
266 : )
267 0 : }
268 :
269 0 : async fn handle_tenant_location_config(
270 0 : service: Arc<Service>,
271 0 : req: Request<Body>,
272 0 : ) -> Result<Response<Body>, ApiError> {
273 0 : let tenant_shard_id: TenantShardId = parse_request_param(&req, "tenant_shard_id")?;
274 0 : check_permissions(&req, Scope::PageServerApi)?;
275 :
276 0 : let mut req = match maybe_forward(req).await {
277 0 : ForwardOutcome::Forwarded(res) => {
278 0 : return res;
279 : }
280 0 : ForwardOutcome::NotForwarded(req) => req,
281 : };
282 :
283 0 : let config_req = json_request::<TenantLocationConfigRequest>(&mut req).await?;
284 : json_response(
285 : StatusCode::OK,
286 0 : service
287 0 : .tenant_location_config(tenant_shard_id, config_req)
288 0 : .await?,
289 : )
290 0 : }
291 :
292 0 : async fn handle_tenant_config_patch(
293 0 : service: Arc<Service>,
294 0 : req: Request<Body>,
295 0 : ) -> Result<Response<Body>, ApiError> {
296 0 : check_permissions(&req, Scope::PageServerApi)?;
297 :
298 0 : let mut req = match maybe_forward(req).await {
299 0 : ForwardOutcome::Forwarded(res) => {
300 0 : return res;
301 : }
302 0 : ForwardOutcome::NotForwarded(req) => req,
303 : };
304 :
305 0 : let config_req = json_request::<TenantConfigPatchRequest>(&mut req).await?;
306 :
307 : json_response(
308 : StatusCode::OK,
309 0 : service.tenant_config_patch(config_req).await?,
310 : )
311 0 : }
312 :
313 0 : async fn handle_tenant_config_set(
314 0 : service: Arc<Service>,
315 0 : req: Request<Body>,
316 0 : ) -> Result<Response<Body>, ApiError> {
317 0 : check_permissions(&req, Scope::PageServerApi)?;
318 :
319 0 : let mut req = match maybe_forward(req).await {
320 0 : ForwardOutcome::Forwarded(res) => {
321 0 : return res;
322 : }
323 0 : ForwardOutcome::NotForwarded(req) => req,
324 : };
325 :
326 0 : let config_req = json_request::<TenantConfigRequest>(&mut req).await?;
327 :
328 0 : json_response(StatusCode::OK, service.tenant_config_set(config_req).await?)
329 0 : }
330 :
331 0 : async fn handle_tenant_config_get(
332 0 : service: Arc<Service>,
333 0 : req: Request<Body>,
334 0 : ) -> Result<Response<Body>, ApiError> {
335 0 : let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
336 0 : check_permissions(&req, Scope::PageServerApi)?;
337 0 : maybe_rate_limit(&req, tenant_id).await;
338 :
339 0 : match maybe_forward(req).await {
340 0 : ForwardOutcome::Forwarded(res) => {
341 0 : return res;
342 : }
343 0 : ForwardOutcome::NotForwarded(_req) => {}
344 0 : };
345 0 :
346 0 : json_response(StatusCode::OK, service.tenant_config_get(tenant_id)?)
347 0 : }
348 :
349 0 : async fn handle_tenant_time_travel_remote_storage(
350 0 : service: Arc<Service>,
351 0 : req: Request<Body>,
352 0 : ) -> Result<Response<Body>, ApiError> {
353 0 : let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
354 0 : check_permissions(&req, Scope::PageServerApi)?;
355 0 : maybe_rate_limit(&req, tenant_id).await;
356 :
357 0 : let mut req = match maybe_forward(req).await {
358 0 : ForwardOutcome::Forwarded(res) => {
359 0 : return res;
360 : }
361 0 : ForwardOutcome::NotForwarded(req) => req,
362 : };
363 :
364 0 : let time_travel_req = json_request::<TenantTimeTravelRequest>(&mut req).await?;
365 :
366 0 : let timestamp_raw = must_get_query_param(&req, "travel_to")?;
367 0 : let _timestamp = humantime::parse_rfc3339(×tamp_raw).map_err(|_e| {
368 0 : ApiError::BadRequest(anyhow::anyhow!(
369 0 : "Invalid time for travel_to: {timestamp_raw:?}"
370 0 : ))
371 0 : })?;
372 :
373 0 : let done_if_after_raw = must_get_query_param(&req, "done_if_after")?;
374 0 : let _done_if_after = humantime::parse_rfc3339(&done_if_after_raw).map_err(|_e| {
375 0 : ApiError::BadRequest(anyhow::anyhow!(
376 0 : "Invalid time for done_if_after: {done_if_after_raw:?}"
377 0 : ))
378 0 : })?;
379 :
380 0 : service
381 0 : .tenant_time_travel_remote_storage(
382 0 : &time_travel_req,
383 0 : tenant_id,
384 0 : timestamp_raw,
385 0 : done_if_after_raw,
386 0 : )
387 0 : .await?;
388 0 : json_response(StatusCode::OK, ())
389 0 : }
390 :
391 0 : fn map_reqwest_hyper_status(status: reqwest::StatusCode) -> Result<hyper::StatusCode, ApiError> {
392 0 : hyper::StatusCode::from_u16(status.as_u16())
393 0 : .context("invalid status code")
394 0 : .map_err(ApiError::InternalServerError)
395 0 : }
396 :
397 0 : async fn handle_tenant_secondary_download(
398 0 : service: Arc<Service>,
399 0 : req: Request<Body>,
400 0 : ) -> Result<Response<Body>, ApiError> {
401 0 : let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
402 0 : let wait = parse_query_param(&req, "wait_ms")?.map(Duration::from_millis);
403 0 : maybe_rate_limit(&req, tenant_id).await;
404 :
405 0 : match maybe_forward(req).await {
406 0 : ForwardOutcome::Forwarded(res) => {
407 0 : return res;
408 : }
409 0 : ForwardOutcome::NotForwarded(_req) => {}
410 : };
411 :
412 0 : let (status, progress) = service.tenant_secondary_download(tenant_id, wait).await?;
413 0 : json_response(map_reqwest_hyper_status(status)?, progress)
414 0 : }
415 :
416 0 : async fn handle_tenant_delete(
417 0 : service: Arc<Service>,
418 0 : req: Request<Body>,
419 0 : ) -> Result<Response<Body>, ApiError> {
420 0 : let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
421 0 : check_permissions(&req, Scope::PageServerApi)?;
422 0 : maybe_rate_limit(&req, tenant_id).await;
423 :
424 0 : match maybe_forward(req).await {
425 0 : ForwardOutcome::Forwarded(res) => {
426 0 : return res;
427 : }
428 0 : ForwardOutcome::NotForwarded(_req) => {}
429 : };
430 :
431 0 : let status_code = service
432 0 : .tenant_delete(tenant_id)
433 0 : .await
434 0 : .and_then(map_reqwest_hyper_status)?;
435 :
436 0 : if status_code == StatusCode::NOT_FOUND {
437 : // The pageserver uses 404 for successful deletion, but we use 200
438 0 : json_response(StatusCode::OK, ())
439 : } else {
440 0 : json_response(status_code, ())
441 : }
442 0 : }
443 :
444 0 : async fn handle_tenant_timeline_create(
445 0 : service: Arc<Service>,
446 0 : req: Request<Body>,
447 0 : ) -> Result<Response<Body>, ApiError> {
448 0 : let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
449 0 : check_permissions(&req, Scope::PageServerApi)?;
450 0 : maybe_rate_limit(&req, tenant_id).await;
451 :
452 0 : let mut req = match maybe_forward(req).await {
453 0 : ForwardOutcome::Forwarded(res) => {
454 0 : return res;
455 : }
456 0 : ForwardOutcome::NotForwarded(req) => req,
457 : };
458 :
459 0 : let create_req = json_request::<TimelineCreateRequest>(&mut req).await?;
460 : json_response(
461 : StatusCode::CREATED,
462 0 : service
463 0 : .tenant_timeline_create(tenant_id, create_req)
464 0 : .await?,
465 : )
466 0 : }
467 :
468 0 : async fn handle_tenant_timeline_delete(
469 0 : service: Arc<Service>,
470 0 : req: Request<Body>,
471 0 : ) -> Result<Response<Body>, ApiError> {
472 0 : let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
473 0 : let timeline_id: TimelineId = parse_request_param(&req, "timeline_id")?;
474 :
475 0 : check_permissions(&req, Scope::PageServerApi)?;
476 0 : maybe_rate_limit(&req, tenant_id).await;
477 :
478 0 : match maybe_forward(req).await {
479 0 : ForwardOutcome::Forwarded(res) => {
480 0 : return res;
481 : }
482 0 : ForwardOutcome::NotForwarded(_req) => {}
483 : };
484 :
485 : // For timeline deletions, which both implement an "initially return 202, then 404 once
486 : // we're done" semantic, we wrap with a retry loop to expose a simpler API upstream.
487 0 : async fn deletion_wrapper<R, F>(service: Arc<Service>, f: F) -> Result<Response<Body>, ApiError>
488 0 : where
489 0 : R: std::future::Future<Output = Result<StatusCode, ApiError>> + Send + 'static,
490 0 : F: Fn(Arc<Service>) -> R + Send + Sync + 'static,
491 0 : {
492 : // On subsequent retries, wait longer.
493 : // Enable callers with a 25 second request timeout to reliably get a response
494 : const MAX_WAIT: Duration = Duration::from_secs(25);
495 : const MAX_RETRY_PERIOD: Duration = Duration::from_secs(5);
496 :
497 0 : let started_at = Instant::now();
498 0 :
499 0 : // To keep deletion reasonably snappy for small tenants, initially check after 1 second if deletion
500 0 : // completed.
501 0 : let mut retry_period = Duration::from_secs(1);
502 :
503 : loop {
504 0 : let status = f(service.clone()).await?;
505 0 : match status {
506 : StatusCode::ACCEPTED => {
507 0 : tracing::info!("Deletion accepted, waiting to try again...");
508 0 : tokio::time::sleep(retry_period).await;
509 0 : retry_period = MAX_RETRY_PERIOD;
510 : }
511 : StatusCode::CONFLICT => {
512 0 : tracing::info!("Deletion already in progress, waiting to try again...");
513 0 : tokio::time::sleep(retry_period).await;
514 : }
515 : StatusCode::NOT_FOUND => {
516 0 : tracing::info!("Deletion complete");
517 0 : return json_response(StatusCode::OK, ());
518 : }
519 : _ => {
520 0 : tracing::warn!("Unexpected status {status}");
521 0 : return json_response(status, ());
522 : }
523 : }
524 :
525 0 : let now = Instant::now();
526 0 : if now + retry_period > started_at + MAX_WAIT {
527 0 : tracing::info!("Deletion timed out waiting for 404");
528 : // REQUEST_TIMEOUT would be more appropriate, but CONFLICT is already part of
529 : // the pageserver's swagger definition for this endpoint, and has the same desired
530 : // effect of causing the control plane to retry later.
531 0 : return json_response(StatusCode::CONFLICT, ());
532 0 : }
533 : }
534 0 : }
535 :
536 0 : deletion_wrapper(service, move |service| async move {
537 0 : service
538 0 : .tenant_timeline_delete(tenant_id, timeline_id)
539 0 : .await
540 0 : .and_then(map_reqwest_hyper_status)
541 0 : })
542 0 : .await
543 0 : }
544 :
545 0 : async fn handle_tenant_timeline_archival_config(
546 0 : service: Arc<Service>,
547 0 : req: Request<Body>,
548 0 : ) -> Result<Response<Body>, ApiError> {
549 0 : let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
550 0 : let timeline_id: TimelineId = parse_request_param(&req, "timeline_id")?;
551 :
552 0 : check_permissions(&req, Scope::PageServerApi)?;
553 0 : maybe_rate_limit(&req, tenant_id).await;
554 :
555 0 : let mut req = match maybe_forward(req).await {
556 0 : ForwardOutcome::Forwarded(res) => {
557 0 : return res;
558 : }
559 0 : ForwardOutcome::NotForwarded(req) => req,
560 : };
561 :
562 0 : let create_req = json_request::<TimelineArchivalConfigRequest>(&mut req).await?;
563 :
564 0 : service
565 0 : .tenant_timeline_archival_config(tenant_id, timeline_id, create_req)
566 0 : .await?;
567 :
568 0 : json_response(StatusCode::OK, ())
569 0 : }
570 :
571 0 : async fn handle_tenant_timeline_detach_ancestor(
572 0 : service: Arc<Service>,
573 0 : req: Request<Body>,
574 0 : ) -> Result<Response<Body>, ApiError> {
575 0 : let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
576 0 : let timeline_id: TimelineId = parse_request_param(&req, "timeline_id")?;
577 0 : let behavior: Option<DetachBehavior> = parse_query_param(&req, "detach_behavior")?;
578 :
579 0 : check_permissions(&req, Scope::PageServerApi)?;
580 0 : maybe_rate_limit(&req, tenant_id).await;
581 :
582 0 : match maybe_forward(req).await {
583 0 : ForwardOutcome::Forwarded(res) => {
584 0 : return res;
585 : }
586 0 : ForwardOutcome::NotForwarded(_req) => {}
587 : };
588 :
589 0 : let res = service
590 0 : .tenant_timeline_detach_ancestor(tenant_id, timeline_id, behavior)
591 0 : .await?;
592 :
593 0 : json_response(StatusCode::OK, res)
594 0 : }
595 :
596 0 : async fn handle_tenant_timeline_block_unblock_gc(
597 0 : service: Arc<Service>,
598 0 : req: Request<Body>,
599 0 : dir: BlockUnblock,
600 0 : ) -> Result<Response<Body>, ApiError> {
601 0 : let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
602 0 : check_permissions(&req, Scope::PageServerApi)?;
603 0 : maybe_rate_limit(&req, tenant_id).await;
604 :
605 0 : let timeline_id: TimelineId = parse_request_param(&req, "timeline_id")?;
606 :
607 0 : service
608 0 : .tenant_timeline_block_unblock_gc(tenant_id, timeline_id, dir)
609 0 : .await?;
610 :
611 0 : json_response(StatusCode::OK, ())
612 0 : }
613 :
614 0 : async fn handle_tenant_timeline_download_heatmap_layers(
615 0 : service: Arc<Service>,
616 0 : req: Request<Body>,
617 0 : ) -> Result<Response<Body>, ApiError> {
618 0 : let tenant_shard_id: TenantShardId = parse_request_param(&req, "tenant_shard_id")?;
619 :
620 0 : check_permissions(&req, Scope::PageServerApi)?;
621 0 : maybe_rate_limit(&req, tenant_shard_id.tenant_id).await;
622 :
623 0 : let timeline_id: TimelineId = parse_request_param(&req, "timeline_id")?;
624 0 : let concurrency: Option<usize> = parse_query_param(&req, "concurrency")?;
625 0 : let recurse = parse_query_param(&req, "recurse")?.unwrap_or(false);
626 0 :
627 0 : service
628 0 : .tenant_timeline_download_heatmap_layers(tenant_shard_id, timeline_id, concurrency, recurse)
629 0 : .await?;
630 :
631 0 : json_response(StatusCode::OK, ())
632 0 : }
633 :
634 0 : async fn handle_tenant_timeline_lsn_lease(
635 0 : service: Arc<Service>,
636 0 : req: Request<Body>,
637 0 : ) -> Result<Response<Body>, ApiError> {
638 0 : let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
639 0 : let timeline_id: TimelineId = parse_request_param(&req, "timeline_id")?;
640 :
641 0 : check_permissions(&req, Scope::PageServerApi)?;
642 0 : maybe_rate_limit(&req, tenant_id).await;
643 :
644 0 : let mut req = match maybe_forward(req).await {
645 0 : ForwardOutcome::Forwarded(res) => {
646 0 : return res;
647 : }
648 0 : ForwardOutcome::NotForwarded(req) => req,
649 : };
650 :
651 0 : let lsn_lease_request = json_request::<LsnLeaseRequest>(&mut req).await?;
652 :
653 0 : service
654 0 : .tenant_timeline_lsn_lease(tenant_id, timeline_id, lsn_lease_request.lsn)
655 0 : .await?;
656 :
657 0 : json_response(StatusCode::OK, ())
658 0 : }
659 :
660 : // For metric labels where we would like to include the approximate path, but exclude high-cardinality fields like query parameters
661 : // and tenant/timeline IDs. Since we are proxying to arbitrary paths, we don't have routing templates to
662 : // compare to, so we can just filter out our well known ID format with regexes.
663 3 : fn path_without_ids(path: &str) -> String {
664 : static ID_REGEX: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
665 3 : ID_REGEX
666 3 : .get_or_init(|| regex::Regex::new(r"([0-9a-fA-F]{32}(-[0-9]{4})?|\?.*)").unwrap())
667 3 : .replace_all(path, "")
668 3 : .to_string()
669 3 : }
670 :
671 0 : async fn handle_tenant_timeline_passthrough(
672 0 : service: Arc<Service>,
673 0 : req: Request<Body>,
674 0 : ) -> Result<Response<Body>, ApiError> {
675 0 : let tenant_or_shard_id: TenantShardId = parse_request_param(&req, "tenant_id")?;
676 0 : check_permissions(&req, Scope::PageServerApi)?;
677 0 : maybe_rate_limit(&req, tenant_or_shard_id.tenant_id).await;
678 :
679 0 : let req = match maybe_forward(req).await {
680 0 : ForwardOutcome::Forwarded(res) => {
681 0 : return res;
682 : }
683 0 : ForwardOutcome::NotForwarded(req) => req,
684 : };
685 :
686 0 : let Some(path) = req.uri().path_and_query() else {
687 : // This should never happen, our request router only calls us if there is a path
688 0 : return Err(ApiError::BadRequest(anyhow::anyhow!("Missing path")));
689 : };
690 :
691 0 : let method = match *req.method() {
692 0 : hyper::Method::GET => reqwest::Method::GET,
693 0 : hyper::Method::POST => reqwest::Method::POST,
694 0 : hyper::Method::PUT => reqwest::Method::PUT,
695 0 : hyper::Method::DELETE => reqwest::Method::DELETE,
696 0 : hyper::Method::PATCH => reqwest::Method::PATCH,
697 0 : _ => return Err(ApiError::BadRequest(anyhow::anyhow!("Unsupported method"))),
698 : };
699 :
700 0 : tracing::info!(
701 0 : "Proxying request for tenant {} ({})",
702 : tenant_or_shard_id.tenant_id,
703 : path
704 : );
705 :
706 : // Find the node that holds shard zero
707 0 : let (node, tenant_shard_id) = if tenant_or_shard_id.is_unsharded() {
708 0 : service
709 0 : .tenant_shard0_node(tenant_or_shard_id.tenant_id)
710 0 : .await?
711 : } else {
712 : (
713 0 : service.tenant_shard_node(tenant_or_shard_id).await?,
714 0 : tenant_or_shard_id,
715 : )
716 : };
717 :
718 : // Callers will always pass an unsharded tenant ID. Before proxying, we must
719 : // rewrite this to a shard-aware shard zero ID.
720 0 : let path = format!("{}", path);
721 0 : let tenant_str = tenant_or_shard_id.tenant_id.to_string();
722 0 : let tenant_shard_str = format!("{}", tenant_shard_id);
723 0 : let path = path.replace(&tenant_str, &tenant_shard_str);
724 0 :
725 0 : let latency = &METRICS_REGISTRY
726 0 : .metrics_group
727 0 : .storage_controller_passthrough_request_latency;
728 0 :
729 0 : let path_label = path_without_ids(&path)
730 0 : .split('/')
731 0 : .filter(|token| !token.is_empty())
732 0 : .collect::<Vec<_>>()
733 0 : .join("_");
734 0 : let labels = PageserverRequestLabelGroup {
735 0 : pageserver_id: &node.get_id().to_string(),
736 0 : path: &path_label,
737 0 : method: crate::metrics::Method::Get,
738 0 : };
739 0 :
740 0 : let _timer = latency.start_timer(labels.clone());
741 0 :
742 0 : let client = mgmt_api::Client::new(
743 0 : service.get_http_client().clone(),
744 0 : node.base_url(),
745 0 : service.get_config().pageserver_jwt_token.as_deref(),
746 0 : );
747 0 : let resp = client.op_raw(method, path).await.map_err(|e|
748 : // We return 503 here because if we can't successfully send a request to the pageserver,
749 : // either we aren't available or the pageserver is unavailable.
750 0 : ApiError::ResourceUnavailable(format!("Error sending pageserver API request to {node}: {e}").into()))?;
751 :
752 0 : if !resp.status().is_success() {
753 0 : let error_counter = &METRICS_REGISTRY
754 0 : .metrics_group
755 0 : .storage_controller_passthrough_request_error;
756 0 : error_counter.inc(labels);
757 0 : }
758 :
759 : // Transform 404 into 503 if we raced with a migration
760 0 : if resp.status() == reqwest::StatusCode::NOT_FOUND {
761 : // Look up node again: if we migrated it will be different
762 0 : let new_node = service.tenant_shard_node(tenant_shard_id).await?;
763 0 : if new_node.get_id() != node.get_id() {
764 : // Rather than retry here, send the client a 503 to prompt a retry: this matches
765 : // the pageserver's use of 503, and all clients calling this API should retry on 503.
766 0 : return Err(ApiError::ResourceUnavailable(
767 0 : format!("Pageserver {node} returned 404, was migrated to {new_node}").into(),
768 0 : ));
769 0 : }
770 0 : }
771 :
772 : // We have a reqest::Response, would like a http::Response
773 0 : let mut builder = hyper::Response::builder().status(map_reqwest_hyper_status(resp.status())?);
774 0 : for (k, v) in resp.headers() {
775 0 : builder = builder.header(k.as_str(), v.as_bytes());
776 0 : }
777 :
778 0 : let response = builder
779 0 : .body(Body::wrap_stream(resp.bytes_stream()))
780 0 : .map_err(|e| ApiError::InternalServerError(e.into()))?;
781 :
782 0 : Ok(response)
783 0 : }
784 :
785 0 : async fn handle_tenant_locate(
786 0 : service: Arc<Service>,
787 0 : req: Request<Body>,
788 0 : ) -> Result<Response<Body>, ApiError> {
789 0 : let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
790 :
791 0 : check_permissions(&req, Scope::Admin)?;
792 : // NB: don't rate limit: admin operation.
793 :
794 0 : match maybe_forward(req).await {
795 0 : ForwardOutcome::Forwarded(res) => {
796 0 : return res;
797 : }
798 0 : ForwardOutcome::NotForwarded(_req) => {}
799 0 : };
800 0 :
801 0 : json_response(StatusCode::OK, service.tenant_locate(tenant_id)?)
802 0 : }
803 :
804 0 : async fn handle_tenant_describe(
805 0 : service: Arc<Service>,
806 0 : req: Request<Body>,
807 0 : ) -> Result<Response<Body>, ApiError> {
808 0 : let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
809 0 : check_permissions(&req, Scope::Scrubber)?;
810 : // NB: don't rate limit: scrubber operation.
811 :
812 0 : match maybe_forward(req).await {
813 0 : ForwardOutcome::Forwarded(res) => {
814 0 : return res;
815 : }
816 0 : ForwardOutcome::NotForwarded(_req) => {}
817 0 : };
818 0 :
819 0 : json_response(StatusCode::OK, service.tenant_describe(tenant_id)?)
820 0 : }
821 :
822 0 : async fn handle_tenant_list(
823 0 : service: Arc<Service>,
824 0 : req: Request<Body>,
825 0 : ) -> Result<Response<Body>, ApiError> {
826 0 : check_permissions(&req, Scope::Admin)?;
827 :
828 0 : let limit: Option<usize> = parse_query_param(&req, "limit")?;
829 0 : let start_after: Option<TenantId> = parse_query_param(&req, "start_after")?;
830 0 : tracing::info!("start_after: {:?}", start_after);
831 :
832 0 : match maybe_forward(req).await {
833 0 : ForwardOutcome::Forwarded(res) => {
834 0 : return res;
835 : }
836 0 : ForwardOutcome::NotForwarded(_req) => {}
837 0 : };
838 0 :
839 0 : json_response(StatusCode::OK, service.tenant_list(limit, start_after))
840 0 : }
841 :
842 0 : async fn handle_node_register(req: Request<Body>) -> Result<Response<Body>, ApiError> {
843 0 : check_permissions(&req, Scope::Infra)?;
844 :
845 0 : let mut req = match maybe_forward(req).await {
846 0 : ForwardOutcome::Forwarded(res) => {
847 0 : return res;
848 : }
849 0 : ForwardOutcome::NotForwarded(req) => req,
850 : };
851 :
852 0 : let register_req = json_request::<NodeRegisterRequest>(&mut req).await?;
853 0 : let state = get_state(&req);
854 0 : state.service.node_register(register_req).await?;
855 0 : json_response(StatusCode::OK, ())
856 0 : }
857 :
858 0 : async fn handle_node_list(req: Request<Body>) -> Result<Response<Body>, ApiError> {
859 0 : check_permissions(&req, Scope::Infra)?;
860 :
861 0 : let req = match maybe_forward(req).await {
862 0 : ForwardOutcome::Forwarded(res) => {
863 0 : return res;
864 : }
865 0 : ForwardOutcome::NotForwarded(req) => req,
866 0 : };
867 0 :
868 0 : let state = get_state(&req);
869 0 : let mut nodes = state.service.node_list().await?;
870 0 : nodes.sort_by_key(|n| n.get_id());
871 0 : let api_nodes = nodes.into_iter().map(|n| n.describe()).collect::<Vec<_>>();
872 0 :
873 0 : json_response(StatusCode::OK, api_nodes)
874 0 : }
875 :
876 0 : async fn handle_node_drop(req: Request<Body>) -> Result<Response<Body>, ApiError> {
877 0 : check_permissions(&req, Scope::Admin)?;
878 :
879 0 : let req = match maybe_forward(req).await {
880 0 : ForwardOutcome::Forwarded(res) => {
881 0 : return res;
882 : }
883 0 : ForwardOutcome::NotForwarded(req) => req,
884 0 : };
885 0 :
886 0 : let state = get_state(&req);
887 0 : let node_id: NodeId = parse_request_param(&req, "node_id")?;
888 0 : json_response(StatusCode::OK, state.service.node_drop(node_id).await?)
889 0 : }
890 :
891 0 : async fn handle_node_delete(req: Request<Body>) -> Result<Response<Body>, ApiError> {
892 0 : check_permissions(&req, Scope::Admin)?;
893 :
894 0 : let req = match maybe_forward(req).await {
895 0 : ForwardOutcome::Forwarded(res) => {
896 0 : return res;
897 : }
898 0 : ForwardOutcome::NotForwarded(req) => req,
899 0 : };
900 0 :
901 0 : let state = get_state(&req);
902 0 : let node_id: NodeId = parse_request_param(&req, "node_id")?;
903 0 : json_response(StatusCode::OK, state.service.node_delete(node_id).await?)
904 0 : }
905 :
906 0 : async fn handle_node_configure(req: Request<Body>) -> Result<Response<Body>, ApiError> {
907 0 : check_permissions(&req, Scope::Admin)?;
908 :
909 0 : let mut req = match maybe_forward(req).await {
910 0 : ForwardOutcome::Forwarded(res) => {
911 0 : return res;
912 : }
913 0 : ForwardOutcome::NotForwarded(req) => req,
914 : };
915 :
916 0 : let node_id: NodeId = parse_request_param(&req, "node_id")?;
917 0 : let config_req = json_request::<NodeConfigureRequest>(&mut req).await?;
918 0 : if node_id != config_req.node_id {
919 0 : return Err(ApiError::BadRequest(anyhow::anyhow!(
920 0 : "Path and body node_id differ"
921 0 : )));
922 0 : }
923 0 : let state = get_state(&req);
924 0 :
925 0 : json_response(
926 0 : StatusCode::OK,
927 0 : state
928 0 : .service
929 0 : .external_node_configure(
930 0 : config_req.node_id,
931 0 : config_req.availability.map(NodeAvailability::from),
932 0 : config_req.scheduling,
933 0 : )
934 0 : .await?,
935 : )
936 0 : }
937 :
938 0 : async fn handle_node_status(req: Request<Body>) -> Result<Response<Body>, ApiError> {
939 0 : check_permissions(&req, Scope::Infra)?;
940 :
941 0 : let req = match maybe_forward(req).await {
942 0 : ForwardOutcome::Forwarded(res) => {
943 0 : return res;
944 : }
945 0 : ForwardOutcome::NotForwarded(req) => req,
946 0 : };
947 0 :
948 0 : let state = get_state(&req);
949 0 : let node_id: NodeId = parse_request_param(&req, "node_id")?;
950 :
951 0 : let node_status = state.service.get_node(node_id).await?.describe();
952 0 :
953 0 : json_response(StatusCode::OK, node_status)
954 0 : }
955 :
956 0 : async fn handle_node_shards(req: Request<Body>) -> Result<Response<Body>, ApiError> {
957 0 : check_permissions(&req, Scope::Admin)?;
958 :
959 0 : let state = get_state(&req);
960 0 : let node_id: NodeId = parse_request_param(&req, "node_id")?;
961 :
962 0 : let node_status = state.service.get_node_shards(node_id).await?;
963 :
964 0 : json_response(StatusCode::OK, node_status)
965 0 : }
966 :
967 0 : async fn handle_get_leader(req: Request<Body>) -> Result<Response<Body>, ApiError> {
968 0 : check_permissions(&req, Scope::Admin)?;
969 :
970 0 : let req = match maybe_forward(req).await {
971 0 : ForwardOutcome::Forwarded(res) => {
972 0 : return res;
973 : }
974 0 : ForwardOutcome::NotForwarded(req) => req,
975 0 : };
976 0 :
977 0 : let state = get_state(&req);
978 0 : let leader = state.service.get_leader().await.map_err(|err| {
979 0 : ApiError::InternalServerError(anyhow::anyhow!(
980 0 : "Failed to read leader from database: {err}"
981 0 : ))
982 0 : })?;
983 :
984 0 : json_response(StatusCode::OK, leader)
985 0 : }
986 :
987 0 : async fn handle_node_drain(req: Request<Body>) -> Result<Response<Body>, ApiError> {
988 0 : check_permissions(&req, Scope::Infra)?;
989 :
990 0 : let req = match maybe_forward(req).await {
991 0 : ForwardOutcome::Forwarded(res) => {
992 0 : return res;
993 : }
994 0 : ForwardOutcome::NotForwarded(req) => req,
995 0 : };
996 0 :
997 0 : let state = get_state(&req);
998 0 : let node_id: NodeId = parse_request_param(&req, "node_id")?;
999 :
1000 0 : state.service.start_node_drain(node_id).await?;
1001 :
1002 0 : json_response(StatusCode::ACCEPTED, ())
1003 0 : }
1004 :
1005 0 : async fn handle_cancel_node_drain(req: Request<Body>) -> Result<Response<Body>, ApiError> {
1006 0 : check_permissions(&req, Scope::Infra)?;
1007 :
1008 0 : let req = match maybe_forward(req).await {
1009 0 : ForwardOutcome::Forwarded(res) => {
1010 0 : return res;
1011 : }
1012 0 : ForwardOutcome::NotForwarded(req) => req,
1013 0 : };
1014 0 :
1015 0 : let state = get_state(&req);
1016 0 : let node_id: NodeId = parse_request_param(&req, "node_id")?;
1017 :
1018 0 : state.service.cancel_node_drain(node_id).await?;
1019 :
1020 0 : json_response(StatusCode::ACCEPTED, ())
1021 0 : }
1022 :
1023 0 : async fn handle_node_fill(req: Request<Body>) -> Result<Response<Body>, ApiError> {
1024 0 : check_permissions(&req, Scope::Infra)?;
1025 :
1026 0 : let req = match maybe_forward(req).await {
1027 0 : ForwardOutcome::Forwarded(res) => {
1028 0 : return res;
1029 : }
1030 0 : ForwardOutcome::NotForwarded(req) => req,
1031 0 : };
1032 0 :
1033 0 : let state = get_state(&req);
1034 0 : let node_id: NodeId = parse_request_param(&req, "node_id")?;
1035 :
1036 0 : state.service.start_node_fill(node_id).await?;
1037 :
1038 0 : json_response(StatusCode::ACCEPTED, ())
1039 0 : }
1040 :
1041 0 : async fn handle_cancel_node_fill(req: Request<Body>) -> Result<Response<Body>, ApiError> {
1042 0 : check_permissions(&req, Scope::Infra)?;
1043 :
1044 0 : let req = match maybe_forward(req).await {
1045 0 : ForwardOutcome::Forwarded(res) => {
1046 0 : return res;
1047 : }
1048 0 : ForwardOutcome::NotForwarded(req) => req,
1049 0 : };
1050 0 :
1051 0 : let state = get_state(&req);
1052 0 : let node_id: NodeId = parse_request_param(&req, "node_id")?;
1053 :
1054 0 : state.service.cancel_node_fill(node_id).await?;
1055 :
1056 0 : json_response(StatusCode::ACCEPTED, ())
1057 0 : }
1058 :
1059 0 : async fn handle_safekeeper_list(req: Request<Body>) -> Result<Response<Body>, ApiError> {
1060 0 : check_permissions(&req, Scope::Infra)?;
1061 :
1062 0 : let req = match maybe_forward(req).await {
1063 0 : ForwardOutcome::Forwarded(res) => {
1064 0 : return res;
1065 : }
1066 0 : ForwardOutcome::NotForwarded(req) => req,
1067 0 : };
1068 0 :
1069 0 : let state = get_state(&req);
1070 0 : let safekeepers = state.service.safekeepers_list().await?;
1071 0 : json_response(StatusCode::OK, safekeepers)
1072 0 : }
1073 :
1074 0 : async fn handle_metadata_health_update(req: Request<Body>) -> Result<Response<Body>, ApiError> {
1075 0 : check_permissions(&req, Scope::Scrubber)?;
1076 :
1077 0 : let mut req = match maybe_forward(req).await {
1078 0 : ForwardOutcome::Forwarded(res) => {
1079 0 : return res;
1080 : }
1081 0 : ForwardOutcome::NotForwarded(req) => req,
1082 : };
1083 :
1084 0 : let update_req = json_request::<MetadataHealthUpdateRequest>(&mut req).await?;
1085 0 : let state = get_state(&req);
1086 0 :
1087 0 : state.service.metadata_health_update(update_req).await?;
1088 :
1089 0 : json_response(StatusCode::OK, MetadataHealthUpdateResponse {})
1090 0 : }
1091 :
1092 0 : async fn handle_metadata_health_list_unhealthy(
1093 0 : req: Request<Body>,
1094 0 : ) -> Result<Response<Body>, ApiError> {
1095 0 : check_permissions(&req, Scope::Admin)?;
1096 :
1097 0 : let req = match maybe_forward(req).await {
1098 0 : ForwardOutcome::Forwarded(res) => {
1099 0 : return res;
1100 : }
1101 0 : ForwardOutcome::NotForwarded(req) => req,
1102 0 : };
1103 0 :
1104 0 : let state = get_state(&req);
1105 0 : let unhealthy_tenant_shards = state.service.metadata_health_list_unhealthy().await?;
1106 :
1107 0 : json_response(
1108 0 : StatusCode::OK,
1109 0 : MetadataHealthListUnhealthyResponse {
1110 0 : unhealthy_tenant_shards,
1111 0 : },
1112 0 : )
1113 0 : }
1114 :
1115 0 : async fn handle_metadata_health_list_outdated(
1116 0 : req: Request<Body>,
1117 0 : ) -> Result<Response<Body>, ApiError> {
1118 0 : check_permissions(&req, Scope::Admin)?;
1119 :
1120 0 : let mut req = match maybe_forward(req).await {
1121 0 : ForwardOutcome::Forwarded(res) => {
1122 0 : return res;
1123 : }
1124 0 : ForwardOutcome::NotForwarded(req) => req,
1125 : };
1126 :
1127 0 : let list_outdated_req = json_request::<MetadataHealthListOutdatedRequest>(&mut req).await?;
1128 0 : let state = get_state(&req);
1129 0 : let health_records = state
1130 0 : .service
1131 0 : .metadata_health_list_outdated(list_outdated_req.not_scrubbed_for)
1132 0 : .await?;
1133 :
1134 0 : json_response(
1135 0 : StatusCode::OK,
1136 0 : MetadataHealthListOutdatedResponse { health_records },
1137 0 : )
1138 0 : }
1139 :
1140 0 : async fn handle_tenant_shard_split(
1141 0 : service: Arc<Service>,
1142 0 : req: Request<Body>,
1143 0 : ) -> Result<Response<Body>, ApiError> {
1144 0 : check_permissions(&req, Scope::Admin)?;
1145 : // NB: don't rate limit: admin operation.
1146 :
1147 0 : let mut req = match maybe_forward(req).await {
1148 0 : ForwardOutcome::Forwarded(res) => {
1149 0 : return res;
1150 : }
1151 0 : ForwardOutcome::NotForwarded(req) => req,
1152 : };
1153 :
1154 0 : let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
1155 0 : let split_req = json_request::<TenantShardSplitRequest>(&mut req).await?;
1156 :
1157 : json_response(
1158 : StatusCode::OK,
1159 0 : service.tenant_shard_split(tenant_id, split_req).await?,
1160 : )
1161 0 : }
1162 :
1163 0 : async fn handle_tenant_shard_migrate(
1164 0 : service: Arc<Service>,
1165 0 : req: Request<Body>,
1166 0 : ) -> Result<Response<Body>, ApiError> {
1167 0 : check_permissions(&req, Scope::Admin)?;
1168 : // NB: don't rate limit: admin operation.
1169 :
1170 0 : let mut req = match maybe_forward(req).await {
1171 0 : ForwardOutcome::Forwarded(res) => {
1172 0 : return res;
1173 : }
1174 0 : ForwardOutcome::NotForwarded(req) => req,
1175 : };
1176 :
1177 0 : let tenant_shard_id: TenantShardId = parse_request_param(&req, "tenant_shard_id")?;
1178 0 : let migrate_req = json_request::<TenantShardMigrateRequest>(&mut req).await?;
1179 : json_response(
1180 : StatusCode::OK,
1181 0 : service
1182 0 : .tenant_shard_migrate(tenant_shard_id, migrate_req)
1183 0 : .await?,
1184 : )
1185 0 : }
1186 :
1187 0 : async fn handle_tenant_shard_migrate_secondary(
1188 0 : service: Arc<Service>,
1189 0 : req: Request<Body>,
1190 0 : ) -> Result<Response<Body>, ApiError> {
1191 0 : check_permissions(&req, Scope::Admin)?;
1192 : // NB: don't rate limit: admin operation.
1193 :
1194 0 : let mut req = match maybe_forward(req).await {
1195 0 : ForwardOutcome::Forwarded(res) => {
1196 0 : return res;
1197 : }
1198 0 : ForwardOutcome::NotForwarded(req) => req,
1199 : };
1200 :
1201 0 : let tenant_shard_id: TenantShardId = parse_request_param(&req, "tenant_shard_id")?;
1202 0 : let migrate_req = json_request::<TenantShardMigrateRequest>(&mut req).await?;
1203 : json_response(
1204 : StatusCode::OK,
1205 0 : service
1206 0 : .tenant_shard_migrate_secondary(tenant_shard_id, migrate_req)
1207 0 : .await?,
1208 : )
1209 0 : }
1210 :
1211 0 : async fn handle_tenant_shard_cancel_reconcile(
1212 0 : service: Arc<Service>,
1213 0 : req: Request<Body>,
1214 0 : ) -> Result<Response<Body>, ApiError> {
1215 0 : check_permissions(&req, Scope::Admin)?;
1216 : // NB: don't rate limit: admin operation.
1217 :
1218 0 : let req = match maybe_forward(req).await {
1219 0 : ForwardOutcome::Forwarded(res) => {
1220 0 : return res;
1221 : }
1222 0 : ForwardOutcome::NotForwarded(req) => req,
1223 : };
1224 :
1225 0 : let tenant_shard_id: TenantShardId = parse_request_param(&req, "tenant_shard_id")?;
1226 : json_response(
1227 : StatusCode::OK,
1228 0 : service
1229 0 : .tenant_shard_cancel_reconcile(tenant_shard_id)
1230 0 : .await?,
1231 : )
1232 0 : }
1233 :
1234 0 : async fn handle_tenant_update_policy(req: Request<Body>) -> Result<Response<Body>, ApiError> {
1235 0 : check_permissions(&req, Scope::Admin)?;
1236 : // NB: don't rate limit: admin operation.
1237 :
1238 0 : let mut req = match maybe_forward(req).await {
1239 0 : ForwardOutcome::Forwarded(res) => {
1240 0 : return res;
1241 : }
1242 0 : ForwardOutcome::NotForwarded(req) => req,
1243 : };
1244 :
1245 0 : let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
1246 0 : let update_req = json_request::<TenantPolicyRequest>(&mut req).await?;
1247 0 : let state = get_state(&req);
1248 0 :
1249 0 : json_response(
1250 0 : StatusCode::OK,
1251 0 : state
1252 0 : .service
1253 0 : .tenant_update_policy(tenant_id, update_req)
1254 0 : .await?,
1255 : )
1256 0 : }
1257 :
1258 0 : async fn handle_update_preferred_azs(req: Request<Body>) -> Result<Response<Body>, ApiError> {
1259 0 : check_permissions(&req, Scope::Admin)?;
1260 :
1261 0 : let mut req = match maybe_forward(req).await {
1262 0 : ForwardOutcome::Forwarded(res) => {
1263 0 : return res;
1264 : }
1265 0 : ForwardOutcome::NotForwarded(req) => req,
1266 : };
1267 :
1268 0 : let azs_req = json_request::<ShardsPreferredAzsRequest>(&mut req).await?;
1269 0 : let state = get_state(&req);
1270 0 :
1271 0 : json_response(
1272 0 : StatusCode::OK,
1273 0 : state.service.update_shards_preferred_azs(azs_req).await?,
1274 : )
1275 0 : }
1276 :
1277 0 : async fn handle_step_down(req: Request<Body>) -> Result<Response<Body>, ApiError> {
1278 0 : check_permissions(&req, Scope::ControllerPeer)?;
1279 :
1280 0 : let req = match maybe_forward(req).await {
1281 0 : ForwardOutcome::Forwarded(res) => {
1282 0 : return res;
1283 : }
1284 0 : ForwardOutcome::NotForwarded(req) => req,
1285 0 : };
1286 0 :
1287 0 : let state = get_state(&req);
1288 0 : let result = state.service.step_down().await;
1289 :
1290 0 : json_response(StatusCode::OK, result)
1291 0 : }
1292 :
1293 0 : async fn handle_tenant_drop(req: Request<Body>) -> Result<Response<Body>, ApiError> {
1294 0 : let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
1295 0 : check_permissions(&req, Scope::PageServerApi)?;
1296 0 : maybe_rate_limit(&req, tenant_id).await;
1297 :
1298 0 : let req = match maybe_forward(req).await {
1299 0 : ForwardOutcome::Forwarded(res) => {
1300 0 : return res;
1301 : }
1302 0 : ForwardOutcome::NotForwarded(req) => req,
1303 0 : };
1304 0 :
1305 0 : let state = get_state(&req);
1306 0 :
1307 0 : json_response(StatusCode::OK, state.service.tenant_drop(tenant_id).await?)
1308 0 : }
1309 :
1310 0 : async fn handle_tenant_import(req: Request<Body>) -> Result<Response<Body>, ApiError> {
1311 0 : let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
1312 0 : check_permissions(&req, Scope::PageServerApi)?;
1313 0 : maybe_rate_limit(&req, tenant_id).await;
1314 :
1315 0 : let req = match maybe_forward(req).await {
1316 0 : ForwardOutcome::Forwarded(res) => {
1317 0 : return res;
1318 : }
1319 0 : ForwardOutcome::NotForwarded(req) => req,
1320 0 : };
1321 0 :
1322 0 : let state = get_state(&req);
1323 0 :
1324 0 : json_response(
1325 0 : StatusCode::OK,
1326 0 : state.service.tenant_import(tenant_id).await?,
1327 : )
1328 0 : }
1329 :
1330 0 : async fn handle_timeline_import(req: Request<Body>) -> Result<Response<Body>, ApiError> {
1331 0 : let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
1332 0 : let timeline_id: TimelineId = parse_request_param(&req, "timeline_id")?;
1333 0 : check_permissions(&req, Scope::PageServerApi)?;
1334 0 : maybe_rate_limit(&req, tenant_id).await;
1335 :
1336 0 : let mut req = match maybe_forward(req).await {
1337 0 : ForwardOutcome::Forwarded(res) => {
1338 0 : return res;
1339 : }
1340 0 : ForwardOutcome::NotForwarded(req) => req,
1341 : };
1342 :
1343 0 : let import_req = json_request::<TimelineImportRequest>(&mut req).await?;
1344 :
1345 0 : let state = get_state(&req);
1346 0 :
1347 0 : if import_req.tenant_id != tenant_id || import_req.timeline_id != timeline_id {
1348 0 : return Err(ApiError::BadRequest(anyhow::anyhow!(
1349 0 : "tenant id or timeline id mismatch: url={tenant_id}/{timeline_id}, body={}/{}",
1350 0 : import_req.tenant_id,
1351 0 : import_req.timeline_id
1352 0 : )));
1353 0 : }
1354 0 :
1355 0 : json_response(
1356 0 : StatusCode::OK,
1357 0 : state.service.timeline_import(import_req).await?,
1358 : )
1359 0 : }
1360 :
1361 0 : async fn handle_tenants_dump(req: Request<Body>) -> Result<Response<Body>, ApiError> {
1362 0 : check_permissions(&req, Scope::Admin)?;
1363 :
1364 0 : let req = match maybe_forward(req).await {
1365 0 : ForwardOutcome::Forwarded(res) => {
1366 0 : return res;
1367 : }
1368 0 : ForwardOutcome::NotForwarded(req) => req,
1369 0 : };
1370 0 :
1371 0 : let state = get_state(&req);
1372 0 : state.service.tenants_dump()
1373 0 : }
1374 :
1375 0 : async fn handle_scheduler_dump(req: Request<Body>) -> Result<Response<Body>, ApiError> {
1376 0 : check_permissions(&req, Scope::Admin)?;
1377 :
1378 0 : let req = match maybe_forward(req).await {
1379 0 : ForwardOutcome::Forwarded(res) => {
1380 0 : return res;
1381 : }
1382 0 : ForwardOutcome::NotForwarded(req) => req,
1383 0 : };
1384 0 :
1385 0 : let state = get_state(&req);
1386 0 : state.service.scheduler_dump()
1387 0 : }
1388 :
1389 0 : async fn handle_consistency_check(req: Request<Body>) -> Result<Response<Body>, ApiError> {
1390 0 : check_permissions(&req, Scope::Admin)?;
1391 :
1392 0 : let req = match maybe_forward(req).await {
1393 0 : ForwardOutcome::Forwarded(res) => {
1394 0 : return res;
1395 : }
1396 0 : ForwardOutcome::NotForwarded(req) => req,
1397 0 : };
1398 0 :
1399 0 : let state = get_state(&req);
1400 0 :
1401 0 : json_response(StatusCode::OK, state.service.consistency_check().await?)
1402 0 : }
1403 :
1404 0 : async fn handle_reconcile_all(req: Request<Body>) -> Result<Response<Body>, ApiError> {
1405 0 : check_permissions(&req, Scope::Admin)?;
1406 :
1407 0 : let req = match maybe_forward(req).await {
1408 0 : ForwardOutcome::Forwarded(res) => {
1409 0 : return res;
1410 : }
1411 0 : ForwardOutcome::NotForwarded(req) => req,
1412 0 : };
1413 0 :
1414 0 : let state = get_state(&req);
1415 0 :
1416 0 : json_response(StatusCode::OK, state.service.reconcile_all_now().await?)
1417 0 : }
1418 :
1419 : /// Status endpoint is just used for checking that our HTTP listener is up
1420 : ///
1421 : /// This serves as our k8s startup probe.
1422 0 : async fn handle_status(req: Request<Body>) -> Result<Response<Body>, ApiError> {
1423 0 : match maybe_forward(req).await {
1424 0 : ForwardOutcome::Forwarded(res) => {
1425 0 : return res;
1426 : }
1427 0 : ForwardOutcome::NotForwarded(_req) => {}
1428 0 : };
1429 0 :
1430 0 : json_response(StatusCode::OK, ())
1431 0 : }
1432 :
1433 : /// Liveness endpoint indicates that this storage controller is in a state
1434 : /// where it can fulfill it's responsibilties. Namely, startup has finished
1435 : /// and it is the current leader.
1436 : ///
1437 : /// This serves as our k8s liveness probe.
1438 0 : async fn handle_live(req: Request<Body>) -> Result<Response<Body>, ApiError> {
1439 0 : let req = match maybe_forward(req).await {
1440 0 : ForwardOutcome::Forwarded(res) => {
1441 0 : return res;
1442 : }
1443 0 : ForwardOutcome::NotForwarded(req) => req,
1444 0 : };
1445 0 :
1446 0 : let state = get_state(&req);
1447 0 : let live = state.service.startup_complete.is_ready()
1448 0 : && state.service.get_leadership_status() == LeadershipStatus::Leader;
1449 :
1450 0 : if live {
1451 0 : json_response(StatusCode::OK, ())
1452 : } else {
1453 0 : json_response(StatusCode::SERVICE_UNAVAILABLE, ())
1454 : }
1455 0 : }
1456 :
1457 : /// Readiness endpoint indicates when we're done doing startup I/O (e.g. reconciling
1458 : /// with remote pageserver nodes). This is intended for use as a kubernetes readiness probe.
1459 0 : async fn handle_ready(req: Request<Body>) -> Result<Response<Body>, ApiError> {
1460 0 : let req = match maybe_forward(req).await {
1461 0 : ForwardOutcome::Forwarded(res) => {
1462 0 : return res;
1463 : }
1464 0 : ForwardOutcome::NotForwarded(req) => req,
1465 0 : };
1466 0 :
1467 0 : let state = get_state(&req);
1468 0 : if state.service.startup_complete.is_ready() {
1469 0 : json_response(StatusCode::OK, ())
1470 : } else {
1471 0 : json_response(StatusCode::SERVICE_UNAVAILABLE, ())
1472 : }
1473 0 : }
1474 :
1475 : impl From<ReconcileError> for ApiError {
1476 0 : fn from(value: ReconcileError) -> Self {
1477 0 : ApiError::Conflict(format!("Reconciliation error: {}", value))
1478 0 : }
1479 : }
1480 :
1481 : /// Return the safekeeper record by instance id, or 404.
1482 : ///
1483 : /// Not used by anything except manual testing.
1484 0 : async fn handle_get_safekeeper(req: Request<Body>) -> Result<Response<Body>, ApiError> {
1485 0 : check_permissions(&req, Scope::Infra)?;
1486 :
1487 0 : let id = parse_request_param::<i64>(&req, "id")?;
1488 :
1489 0 : let req = match maybe_forward(req).await {
1490 0 : ForwardOutcome::Forwarded(res) => {
1491 0 : return res;
1492 : }
1493 0 : ForwardOutcome::NotForwarded(req) => req,
1494 0 : };
1495 0 :
1496 0 : let state = get_state(&req);
1497 :
1498 0 : let res = state.service.get_safekeeper(id).await;
1499 :
1500 0 : match res {
1501 0 : Ok(b) => json_response(StatusCode::OK, b),
1502 : Err(crate::persistence::DatabaseError::Query(diesel::result::Error::NotFound)) => {
1503 0 : Err(ApiError::NotFound("unknown instance id".into()))
1504 : }
1505 0 : Err(other) => Err(other.into()),
1506 : }
1507 0 : }
1508 :
1509 : /// Used as part of deployment scripts.
1510 : ///
1511 : /// Assumes information is only relayed to storage controller after first selecting an unique id on
1512 : /// control plane database, which means we have an id field in the request and payload.
1513 0 : async fn handle_upsert_safekeeper(mut req: Request<Body>) -> Result<Response<Body>, ApiError> {
1514 0 : check_permissions(&req, Scope::Infra)?;
1515 :
1516 0 : let body = json_request::<SafekeeperUpsert>(&mut req).await?;
1517 0 : let id = parse_request_param::<i64>(&req, "id")?;
1518 :
1519 0 : if id != body.id {
1520 : // it should be repeated
1521 0 : return Err(ApiError::BadRequest(anyhow::anyhow!(
1522 0 : "id mismatch: url={id:?}, body={:?}",
1523 0 : body.id
1524 0 : )));
1525 0 : }
1526 0 :
1527 0 : if id <= 0 {
1528 0 : return Err(ApiError::BadRequest(anyhow::anyhow!(
1529 0 : "id not allowed to be zero or negative: {id}"
1530 0 : )));
1531 0 : }
1532 :
1533 0 : let req = match maybe_forward(req).await {
1534 0 : ForwardOutcome::Forwarded(res) => {
1535 0 : return res;
1536 : }
1537 0 : ForwardOutcome::NotForwarded(req) => req,
1538 0 : };
1539 0 :
1540 0 : let state = get_state(&req);
1541 0 :
1542 0 : state.service.upsert_safekeeper(body).await?;
1543 :
1544 0 : Ok(Response::builder()
1545 0 : .status(StatusCode::NO_CONTENT)
1546 0 : .body(Body::empty())
1547 0 : .unwrap())
1548 0 : }
1549 :
1550 : /// Sets the scheduling policy of the specified safekeeper
1551 0 : async fn handle_safekeeper_scheduling_policy(
1552 0 : mut req: Request<Body>,
1553 0 : ) -> Result<Response<Body>, ApiError> {
1554 0 : check_permissions(&req, Scope::Admin)?;
1555 :
1556 0 : let body = json_request::<SafekeeperSchedulingPolicyRequest>(&mut req).await?;
1557 0 : let id = parse_request_param::<i64>(&req, "id")?;
1558 :
1559 0 : let req = match maybe_forward(req).await {
1560 0 : ForwardOutcome::Forwarded(res) => {
1561 0 : return res;
1562 : }
1563 0 : ForwardOutcome::NotForwarded(req) => req,
1564 0 : };
1565 0 :
1566 0 : let state = get_state(&req);
1567 0 :
1568 0 : state
1569 0 : .service
1570 0 : .set_safekeeper_scheduling_policy(id, body.scheduling_policy)
1571 0 : .await?;
1572 :
1573 0 : json_response(StatusCode::OK, ())
1574 0 : }
1575 :
1576 : /// Common wrapper for request handlers that call into Service and will operate on tenants: they must only
1577 : /// be allowed to run if Service has finished its initial reconciliation.
1578 0 : async fn tenant_service_handler<R, H>(
1579 0 : request: Request<Body>,
1580 0 : handler: H,
1581 0 : request_name: RequestName,
1582 0 : ) -> R::Output
1583 0 : where
1584 0 : R: std::future::Future<Output = Result<Response<Body>, ApiError>> + Send + 'static,
1585 0 : H: FnOnce(Arc<Service>, Request<Body>) -> R + Send + Sync + 'static,
1586 0 : {
1587 0 : let state = get_state(&request);
1588 0 : let service = state.service.clone();
1589 0 :
1590 0 : let startup_complete = service.startup_complete.clone();
1591 0 : if tokio::time::timeout(STARTUP_RECONCILE_TIMEOUT, startup_complete.wait())
1592 0 : .await
1593 0 : .is_err()
1594 : {
1595 : // This shouldn't happen: it is the responsibilty of [`Service::startup_reconcile`] to use appropriate
1596 : // timeouts around its remote calls, to bound its runtime.
1597 0 : return Err(ApiError::Timeout(
1598 0 : "Timed out waiting for service readiness".into(),
1599 0 : ));
1600 0 : }
1601 0 :
1602 0 : named_request_span(
1603 0 : request,
1604 0 : |request| async move { handler(service, request).await },
1605 0 : request_name,
1606 0 : )
1607 0 : .await
1608 0 : }
1609 :
1610 : /// Check if the required scope is held in the request's token, or if the request has
1611 : /// a token with 'admin' scope then always permit it.
1612 0 : fn check_permissions(request: &Request<Body>, required_scope: Scope) -> Result<(), ApiError> {
1613 0 : check_permission_with(request, |claims| {
1614 0 : match crate::auth::check_permission(claims, required_scope) {
1615 0 : Err(e) => match crate::auth::check_permission(claims, Scope::Admin) {
1616 0 : Ok(()) => Ok(()),
1617 0 : Err(_) => Err(e),
1618 : },
1619 0 : Ok(()) => Ok(()),
1620 : }
1621 0 : })
1622 0 : }
1623 :
1624 : #[derive(Clone, Debug)]
1625 : struct RequestMeta {
1626 : method: hyper::http::Method,
1627 : at: Instant,
1628 : }
1629 :
1630 0 : pub fn prologue_leadership_status_check_middleware<
1631 0 : B: hyper::body::HttpBody + Send + Sync + 'static,
1632 0 : >() -> Middleware<B, ApiError> {
1633 0 : Middleware::pre(move |req| async move {
1634 0 : let state = get_state(&req);
1635 0 : let leadership_status = state.service.get_leadership_status();
1636 :
1637 : enum AllowedRoutes {
1638 : All,
1639 : Some(&'static [&'static str]),
1640 : }
1641 :
1642 0 : let allowed_routes = match leadership_status {
1643 0 : LeadershipStatus::Leader => AllowedRoutes::All,
1644 0 : LeadershipStatus::SteppedDown => AllowedRoutes::All,
1645 0 : LeadershipStatus::Candidate => AllowedRoutes::Some(&[
1646 0 : "/ready",
1647 0 : "/status",
1648 0 : "/metrics",
1649 0 : "/profile/cpu",
1650 0 : "/profile/heap",
1651 0 : ]),
1652 : };
1653 :
1654 0 : match allowed_routes {
1655 0 : AllowedRoutes::All => Ok(req),
1656 0 : AllowedRoutes::Some(allowed) if allowed.contains(&req.uri().path()) => Ok(req),
1657 : _ => {
1658 0 : tracing::info!(
1659 0 : "Request {} not allowed due to current leadership state",
1660 0 : req.uri()
1661 : );
1662 :
1663 0 : Err(ApiError::ResourceUnavailable(
1664 0 : format!("Current leadership status is {leadership_status}").into(),
1665 0 : ))
1666 : }
1667 : }
1668 0 : })
1669 0 : }
1670 :
1671 0 : fn prologue_metrics_middleware<B: hyper::body::HttpBody + Send + Sync + 'static>()
1672 0 : -> Middleware<B, ApiError> {
1673 0 : Middleware::pre(move |req| async move {
1674 0 : let meta = RequestMeta {
1675 0 : method: req.method().clone(),
1676 0 : at: Instant::now(),
1677 0 : };
1678 0 :
1679 0 : req.set_context(meta);
1680 0 :
1681 0 : Ok(req)
1682 0 : })
1683 0 : }
1684 :
1685 0 : fn epilogue_metrics_middleware<B: hyper::body::HttpBody + Send + Sync + 'static>()
1686 0 : -> Middleware<B, ApiError> {
1687 0 : Middleware::post_with_info(move |resp, req_info| async move {
1688 0 : let request_name = match req_info.context::<RequestName>() {
1689 0 : Some(name) => name,
1690 : None => {
1691 0 : return Ok(resp);
1692 : }
1693 : };
1694 :
1695 0 : if let Some(meta) = req_info.context::<RequestMeta>() {
1696 0 : let status = &crate::metrics::METRICS_REGISTRY
1697 0 : .metrics_group
1698 0 : .storage_controller_http_request_status;
1699 0 : let latency = &crate::metrics::METRICS_REGISTRY
1700 0 : .metrics_group
1701 0 : .storage_controller_http_request_latency;
1702 0 :
1703 0 : status.inc(HttpRequestStatusLabelGroup {
1704 0 : path: request_name.0,
1705 0 : method: meta.method.clone().into(),
1706 0 : status: crate::metrics::StatusCode(resp.status()),
1707 0 : });
1708 0 :
1709 0 : latency.observe(
1710 0 : HttpRequestLatencyLabelGroup {
1711 0 : path: request_name.0,
1712 0 : method: meta.method.into(),
1713 0 : },
1714 0 : meta.at.elapsed().as_secs_f64(),
1715 0 : );
1716 0 : }
1717 0 : Ok(resp)
1718 0 : })
1719 0 : }
1720 :
1721 0 : pub async fn measured_metrics_handler(req: Request<Body>) -> Result<Response<Body>, ApiError> {
1722 : pub const TEXT_FORMAT: &str = "text/plain; version=0.0.4";
1723 :
1724 0 : let req = match maybe_forward(req).await {
1725 0 : ForwardOutcome::Forwarded(res) => {
1726 0 : return res;
1727 : }
1728 0 : ForwardOutcome::NotForwarded(req) => req,
1729 0 : };
1730 0 :
1731 0 : let state = get_state(&req);
1732 0 : let payload = crate::metrics::METRICS_REGISTRY.encode(&state.neon_metrics);
1733 0 : let response = Response::builder()
1734 0 : .status(200)
1735 0 : .header(CONTENT_TYPE, TEXT_FORMAT)
1736 0 : .body(payload.into())
1737 0 : .unwrap();
1738 0 :
1739 0 : Ok(response)
1740 0 : }
1741 :
1742 : #[derive(Clone)]
1743 : struct RequestName(&'static str);
1744 :
1745 0 : async fn named_request_span<R, H>(
1746 0 : request: Request<Body>,
1747 0 : handler: H,
1748 0 : name: RequestName,
1749 0 : ) -> R::Output
1750 0 : where
1751 0 : R: Future<Output = Result<Response<Body>, ApiError>> + Send + 'static,
1752 0 : H: FnOnce(Request<Body>) -> R + Send + Sync + 'static,
1753 0 : {
1754 0 : request.set_context(name);
1755 0 : request_span(request, handler).await
1756 0 : }
1757 :
1758 : enum ForwardOutcome {
1759 : Forwarded(Result<Response<Body>, ApiError>),
1760 : NotForwarded(Request<Body>),
1761 : }
1762 :
1763 : /// Potentially forward the request to the current storage controler leader.
1764 : /// More specifically we forward when:
1765 : /// 1. Request is not one of:
1766 : /// ["/control/v1/step_down", "/status", "/ready", "/metrics", "/profile/cpu", "/profile/heap"]
1767 : /// 2. Current instance is in [`LeadershipStatus::SteppedDown`] state
1768 : /// 3. There is a leader in the database to forward to
1769 : /// 4. Leader from step (3) is not the current instance
1770 : ///
1771 : /// Why forward?
1772 : /// It turns out that we can't rely on external orchestration to promptly route trafic to the
1773 : /// new leader. This is downtime inducing. Forwarding provides a safe way out.
1774 : ///
1775 : /// Why is it safe?
1776 : /// If a storcon instance is persisted in the database, then we know that it is the current leader.
1777 : /// There's one exception: time between handling step-down request and the new leader updating the
1778 : /// database.
1779 : ///
1780 : /// Let's treat the happy case first. The stepped down node does not produce any side effects,
1781 : /// since all request handling happens on the leader.
1782 : ///
1783 : /// As for the edge case, we are guaranteed to always have a maximum of two running instances.
1784 : /// Hence, if we are in the edge case scenario the leader persisted in the database is the
1785 : /// stepped down instance that received the request. Condition (4) above covers this scenario.
1786 0 : async fn maybe_forward(req: Request<Body>) -> ForwardOutcome {
1787 : const NOT_FOR_FORWARD: &[&str] = &[
1788 : "/control/v1/step_down",
1789 : "/status",
1790 : "/live",
1791 : "/ready",
1792 : "/metrics",
1793 : "/profile/cpu",
1794 : "/profile/heap",
1795 : ];
1796 :
1797 0 : let uri = req.uri();
1798 0 : let uri_for_forward = !NOT_FOR_FORWARD.contains(&uri.path());
1799 0 :
1800 0 : // Fast return before trying to take any Service locks, if we will never forward anyway
1801 0 : if !uri_for_forward {
1802 0 : return ForwardOutcome::NotForwarded(req);
1803 0 : }
1804 0 :
1805 0 : let state = get_state(&req);
1806 0 : let leadership_status = state.service.get_leadership_status();
1807 0 :
1808 0 : if leadership_status != LeadershipStatus::SteppedDown {
1809 0 : return ForwardOutcome::NotForwarded(req);
1810 0 : }
1811 :
1812 0 : let leader = state.service.get_leader().await;
1813 0 : let leader = {
1814 0 : match leader {
1815 0 : Ok(Some(leader)) => leader,
1816 : Ok(None) => {
1817 0 : return ForwardOutcome::Forwarded(Err(ApiError::ResourceUnavailable(
1818 0 : "No leader to forward to while in stepped down state".into(),
1819 0 : )));
1820 : }
1821 0 : Err(err) => {
1822 0 : return ForwardOutcome::Forwarded(Err(ApiError::InternalServerError(
1823 0 : anyhow::anyhow!(
1824 0 : "Failed to get leader for forwarding while in stepped down state: {err}"
1825 0 : ),
1826 0 : )));
1827 : }
1828 : }
1829 : };
1830 :
1831 0 : let cfg = state.service.get_config();
1832 0 : if let Some(ref self_addr) = cfg.address_for_peers {
1833 0 : let leader_addr = match Uri::from_str(leader.address.as_str()) {
1834 0 : Ok(uri) => uri,
1835 0 : Err(err) => {
1836 0 : return ForwardOutcome::Forwarded(Err(ApiError::InternalServerError(
1837 0 : anyhow::anyhow!(
1838 0 : "Failed to parse leader uri for forwarding while in stepped down state: {err}"
1839 0 : ),
1840 0 : )));
1841 : }
1842 : };
1843 :
1844 0 : if *self_addr == leader_addr {
1845 0 : return ForwardOutcome::Forwarded(Err(ApiError::ResourceUnavailable(
1846 0 : "Leader is stepped down instance".into(),
1847 0 : )));
1848 0 : }
1849 0 : }
1850 :
1851 0 : tracing::info!("Forwarding {} to leader at {}", uri, leader.address);
1852 :
1853 : // Use [`RECONCILE_TIMEOUT`] as the max amount of time a request should block for and
1854 : // include some leeway to get the timeout for proxied requests.
1855 : const PROXIED_REQUEST_TIMEOUT: Duration = Duration::from_secs(RECONCILE_TIMEOUT.as_secs() + 10);
1856 :
1857 0 : let client = state.service.get_http_client().clone();
1858 :
1859 0 : let request: reqwest::Request = match convert_request(
1860 0 : req,
1861 0 : &client,
1862 0 : leader.address,
1863 0 : PROXIED_REQUEST_TIMEOUT,
1864 0 : )
1865 0 : .await
1866 : {
1867 0 : Ok(r) => r,
1868 0 : Err(err) => {
1869 0 : return ForwardOutcome::Forwarded(Err(ApiError::InternalServerError(anyhow::anyhow!(
1870 0 : "Failed to convert request for forwarding while in stepped down state: {err}"
1871 0 : ))));
1872 : }
1873 : };
1874 :
1875 0 : let response = match client.execute(request).await {
1876 0 : Ok(r) => r,
1877 0 : Err(err) => {
1878 0 : return ForwardOutcome::Forwarded(Err(ApiError::InternalServerError(anyhow::anyhow!(
1879 0 : "Failed to forward while in stepped down state: {err}"
1880 0 : ))));
1881 : }
1882 : };
1883 :
1884 0 : ForwardOutcome::Forwarded(convert_response(response).await)
1885 0 : }
1886 :
1887 : /// Convert a [`reqwest::Response`] to a [hyper::Response`] by passing through
1888 : /// a stable representation (string, bytes or integer)
1889 : ///
1890 : /// Ideally, we would not have to do this since both types use the http crate
1891 : /// under the hood. However, they use different versions of the crate and keeping
1892 : /// second order dependencies in sync is difficult.
1893 0 : async fn convert_response(resp: reqwest::Response) -> Result<hyper::Response<Body>, ApiError> {
1894 : use std::str::FromStr;
1895 :
1896 0 : let mut builder = hyper::Response::builder().status(resp.status().as_u16());
1897 0 : for (key, value) in resp.headers().into_iter() {
1898 0 : let key = hyper::header::HeaderName::from_str(key.as_str()).map_err(|err| {
1899 0 : ApiError::InternalServerError(anyhow::anyhow!("Response conversion failed: {err}"))
1900 0 : })?;
1901 :
1902 0 : let value = hyper::header::HeaderValue::from_bytes(value.as_bytes()).map_err(|err| {
1903 0 : ApiError::InternalServerError(anyhow::anyhow!("Response conversion failed: {err}"))
1904 0 : })?;
1905 :
1906 0 : builder = builder.header(key, value);
1907 : }
1908 :
1909 0 : let body = http::Body::wrap_stream(resp.bytes_stream());
1910 0 :
1911 0 : builder.body(body).map_err(|err| {
1912 0 : ApiError::InternalServerError(anyhow::anyhow!("Response conversion failed: {err}"))
1913 0 : })
1914 0 : }
1915 :
1916 : /// Convert a [`reqwest::Request`] to a [hyper::Request`] by passing through
1917 : /// a stable representation (string, bytes or integer)
1918 : ///
1919 : /// See [`convert_response`] for why we are doing it this way.
1920 0 : async fn convert_request(
1921 0 : req: hyper::Request<Body>,
1922 0 : client: &reqwest::Client,
1923 0 : to_address: String,
1924 0 : timeout: Duration,
1925 0 : ) -> Result<reqwest::Request, ApiError> {
1926 : use std::str::FromStr;
1927 :
1928 0 : let (parts, body) = req.into_parts();
1929 0 : let method = reqwest::Method::from_str(parts.method.as_str()).map_err(|err| {
1930 0 : ApiError::InternalServerError(anyhow::anyhow!("Request conversion failed: {err}"))
1931 0 : })?;
1932 :
1933 0 : let path_and_query = parts.uri.path_and_query().ok_or_else(|| {
1934 0 : ApiError::InternalServerError(anyhow::anyhow!(
1935 0 : "Request conversion failed: no path and query"
1936 0 : ))
1937 0 : })?;
1938 :
1939 0 : let uri = reqwest::Url::from_str(
1940 0 : format!(
1941 0 : "{}{}",
1942 0 : to_address.trim_end_matches("/"),
1943 0 : path_and_query.as_str()
1944 0 : )
1945 0 : .as_str(),
1946 0 : )
1947 0 : .map_err(|err| {
1948 0 : ApiError::InternalServerError(anyhow::anyhow!("Request conversion failed: {err}"))
1949 0 : })?;
1950 :
1951 0 : let mut headers = reqwest::header::HeaderMap::new();
1952 0 : for (key, value) in parts.headers.into_iter() {
1953 0 : let key = match key {
1954 0 : Some(k) => k,
1955 : None => {
1956 0 : continue;
1957 : }
1958 : };
1959 :
1960 0 : let key = reqwest::header::HeaderName::from_str(key.as_str()).map_err(|err| {
1961 0 : ApiError::InternalServerError(anyhow::anyhow!("Request conversion failed: {err}"))
1962 0 : })?;
1963 :
1964 0 : let value = reqwest::header::HeaderValue::from_bytes(value.as_bytes()).map_err(|err| {
1965 0 : ApiError::InternalServerError(anyhow::anyhow!("Request conversion failed: {err}"))
1966 0 : })?;
1967 :
1968 0 : headers.insert(key, value);
1969 : }
1970 :
1971 0 : let body = hyper::body::to_bytes(body).await.map_err(|err| {
1972 0 : ApiError::InternalServerError(anyhow::anyhow!("Request conversion failed: {err}"))
1973 0 : })?;
1974 :
1975 0 : client
1976 0 : .request(method, uri)
1977 0 : .headers(headers)
1978 0 : .body(body)
1979 0 : .timeout(timeout)
1980 0 : .build()
1981 0 : .map_err(|err| {
1982 0 : ApiError::InternalServerError(anyhow::anyhow!("Request conversion failed: {err}"))
1983 0 : })
1984 0 : }
1985 :
1986 0 : pub fn make_router(
1987 0 : service: Arc<Service>,
1988 0 : auth: Option<Arc<SwappableJwtAuth>>,
1989 0 : build_info: BuildInfo,
1990 0 : ) -> RouterBuilder<hyper::Body, ApiError> {
1991 0 : let mut router = endpoint::make_router()
1992 0 : .middleware(prologue_leadership_status_check_middleware())
1993 0 : .middleware(prologue_metrics_middleware())
1994 0 : .middleware(epilogue_metrics_middleware());
1995 0 : if auth.is_some() {
1996 0 : router = router.middleware(auth_middleware(|request| {
1997 0 : let state = get_state(request);
1998 0 : if state.allowlist_routes.contains(&request.uri().path()) {
1999 0 : None
2000 : } else {
2001 0 : state.auth.as_deref()
2002 : }
2003 0 : }));
2004 0 : }
2005 :
2006 0 : router
2007 0 : .data(Arc::new(HttpState::new(service, auth, build_info)))
2008 0 : .get("/metrics", |r| {
2009 0 : named_request_span(r, measured_metrics_handler, RequestName("metrics"))
2010 0 : })
2011 0 : // Non-prefixed generic endpoints (status, metrics, profiling)
2012 0 : .get("/status", |r| {
2013 0 : named_request_span(r, handle_status, RequestName("status"))
2014 0 : })
2015 0 : .get("/live", |r| {
2016 0 : named_request_span(r, handle_live, RequestName("live"))
2017 0 : })
2018 0 : .get("/ready", |r| {
2019 0 : named_request_span(r, handle_ready, RequestName("ready"))
2020 0 : })
2021 0 : .get("/profile/cpu", |r| {
2022 0 : named_request_span(r, profile_cpu_handler, RequestName("profile_cpu"))
2023 0 : })
2024 0 : .get("/profile/heap", |r| {
2025 0 : named_request_span(r, profile_heap_handler, RequestName("profile_heap"))
2026 0 : })
2027 0 : // Upcalls for the pageserver: point the pageserver's `control_plane_api` config to this prefix
2028 0 : .post("/upcall/v1/re-attach", |r| {
2029 0 : named_request_span(r, handle_re_attach, RequestName("upcall_v1_reattach"))
2030 0 : })
2031 0 : .post("/upcall/v1/validate", |r| {
2032 0 : named_request_span(r, handle_validate, RequestName("upcall_v1_validate"))
2033 0 : })
2034 0 : .get("/upcall/v1/timeline_import_status", |r| {
2035 0 : named_request_span(
2036 0 : r,
2037 0 : handle_get_timeline_import_status,
2038 0 : RequestName("upcall_v1_timeline_import_status"),
2039 0 : )
2040 0 : })
2041 0 : .post("/upcall/v1/timeline_import_status", |r| {
2042 0 : named_request_span(
2043 0 : r,
2044 0 : handle_put_timeline_import_status,
2045 0 : RequestName("upcall_v1_timeline_import_status"),
2046 0 : )
2047 0 : })
2048 0 : // Test/dev/debug endpoints
2049 0 : .post("/debug/v1/attach-hook", |r| {
2050 0 : named_request_span(r, handle_attach_hook, RequestName("debug_v1_attach_hook"))
2051 0 : })
2052 0 : .post("/debug/v1/inspect", |r| {
2053 0 : named_request_span(r, handle_inspect, RequestName("debug_v1_inspect"))
2054 0 : })
2055 0 : .post("/debug/v1/tenant/:tenant_id/drop", |r| {
2056 0 : named_request_span(r, handle_tenant_drop, RequestName("debug_v1_tenant_drop"))
2057 0 : })
2058 0 : .post("/debug/v1/node/:node_id/drop", |r| {
2059 0 : named_request_span(r, handle_node_drop, RequestName("debug_v1_node_drop"))
2060 0 : })
2061 0 : .post("/debug/v1/tenant/:tenant_id/import", |r| {
2062 0 : named_request_span(
2063 0 : r,
2064 0 : handle_tenant_import,
2065 0 : RequestName("debug_v1_tenant_import"),
2066 0 : )
2067 0 : })
2068 0 : .get("/debug/v1/tenant", |r| {
2069 0 : named_request_span(r, handle_tenants_dump, RequestName("debug_v1_tenant"))
2070 0 : })
2071 0 : .get("/debug/v1/tenant/:tenant_id/locate", |r| {
2072 0 : tenant_service_handler(
2073 0 : r,
2074 0 : handle_tenant_locate,
2075 0 : RequestName("debug_v1_tenant_locate"),
2076 0 : )
2077 0 : })
2078 0 : .post(
2079 0 : "/debug/v1/tenant/:tenant_id/timeline/:timeline_id/import",
2080 0 : |r| {
2081 0 : named_request_span(
2082 0 : r,
2083 0 : handle_timeline_import,
2084 0 : RequestName("debug_v1_timeline_import"),
2085 0 : )
2086 0 : },
2087 0 : )
2088 0 : .get("/debug/v1/scheduler", |r| {
2089 0 : named_request_span(r, handle_scheduler_dump, RequestName("debug_v1_scheduler"))
2090 0 : })
2091 0 : .post("/debug/v1/consistency_check", |r| {
2092 0 : named_request_span(
2093 0 : r,
2094 0 : handle_consistency_check,
2095 0 : RequestName("debug_v1_consistency_check"),
2096 0 : )
2097 0 : })
2098 0 : .post("/debug/v1/reconcile_all", |r| {
2099 0 : request_span(r, handle_reconcile_all)
2100 0 : })
2101 0 : .put("/debug/v1/failpoints", |r| {
2102 0 : request_span(r, |r| failpoints_handler(r, CancellationToken::new()))
2103 0 : })
2104 0 : // Node operations
2105 0 : .post("/control/v1/node", |r| {
2106 0 : named_request_span(r, handle_node_register, RequestName("control_v1_node"))
2107 0 : })
2108 0 : .delete("/control/v1/node/:node_id", |r| {
2109 0 : named_request_span(r, handle_node_delete, RequestName("control_v1_node_delete"))
2110 0 : })
2111 0 : .get("/control/v1/node", |r| {
2112 0 : named_request_span(r, handle_node_list, RequestName("control_v1_node"))
2113 0 : })
2114 0 : .put("/control/v1/node/:node_id/config", |r| {
2115 0 : named_request_span(
2116 0 : r,
2117 0 : handle_node_configure,
2118 0 : RequestName("control_v1_node_config"),
2119 0 : )
2120 0 : })
2121 0 : .get("/control/v1/node/:node_id", |r| {
2122 0 : named_request_span(r, handle_node_status, RequestName("control_v1_node_status"))
2123 0 : })
2124 0 : .get("/control/v1/node/:node_id/shards", |r| {
2125 0 : named_request_span(
2126 0 : r,
2127 0 : handle_node_shards,
2128 0 : RequestName("control_v1_node_describe"),
2129 0 : )
2130 0 : })
2131 0 : .get("/control/v1/leader", |r| {
2132 0 : named_request_span(r, handle_get_leader, RequestName("control_v1_get_leader"))
2133 0 : })
2134 0 : .put("/control/v1/node/:node_id/drain", |r| {
2135 0 : named_request_span(r, handle_node_drain, RequestName("control_v1_node_drain"))
2136 0 : })
2137 0 : .delete("/control/v1/node/:node_id/drain", |r| {
2138 0 : named_request_span(
2139 0 : r,
2140 0 : handle_cancel_node_drain,
2141 0 : RequestName("control_v1_cancel_node_drain"),
2142 0 : )
2143 0 : })
2144 0 : .put("/control/v1/node/:node_id/fill", |r| {
2145 0 : named_request_span(r, handle_node_fill, RequestName("control_v1_node_fill"))
2146 0 : })
2147 0 : .delete("/control/v1/node/:node_id/fill", |r| {
2148 0 : named_request_span(
2149 0 : r,
2150 0 : handle_cancel_node_fill,
2151 0 : RequestName("control_v1_cancel_node_fill"),
2152 0 : )
2153 0 : })
2154 0 : // Metadata health operations
2155 0 : .post("/control/v1/metadata_health/update", |r| {
2156 0 : named_request_span(
2157 0 : r,
2158 0 : handle_metadata_health_update,
2159 0 : RequestName("control_v1_metadata_health_update"),
2160 0 : )
2161 0 : })
2162 0 : .get("/control/v1/metadata_health/unhealthy", |r| {
2163 0 : named_request_span(
2164 0 : r,
2165 0 : handle_metadata_health_list_unhealthy,
2166 0 : RequestName("control_v1_metadata_health_list_unhealthy"),
2167 0 : )
2168 0 : })
2169 0 : .post("/control/v1/metadata_health/outdated", |r| {
2170 0 : named_request_span(
2171 0 : r,
2172 0 : handle_metadata_health_list_outdated,
2173 0 : RequestName("control_v1_metadata_health_list_outdated"),
2174 0 : )
2175 0 : })
2176 0 : // Safekeepers
2177 0 : .get("/control/v1/safekeeper", |r| {
2178 0 : named_request_span(
2179 0 : r,
2180 0 : handle_safekeeper_list,
2181 0 : RequestName("control_v1_safekeeper_list"),
2182 0 : )
2183 0 : })
2184 0 : .get("/control/v1/safekeeper/:id", |r| {
2185 0 : named_request_span(r, handle_get_safekeeper, RequestName("v1_safekeeper"))
2186 0 : })
2187 0 : .post("/control/v1/safekeeper/:id", |r| {
2188 0 : // id is in the body
2189 0 : named_request_span(
2190 0 : r,
2191 0 : handle_upsert_safekeeper,
2192 0 : RequestName("v1_safekeeper_post"),
2193 0 : )
2194 0 : })
2195 0 : .post("/control/v1/safekeeper/:id/scheduling_policy", |r| {
2196 0 : named_request_span(
2197 0 : r,
2198 0 : handle_safekeeper_scheduling_policy,
2199 0 : RequestName("v1_safekeeper_status"),
2200 0 : )
2201 0 : })
2202 0 : // Tenant Shard operations
2203 0 : .put("/control/v1/tenant/:tenant_shard_id/migrate", |r| {
2204 0 : tenant_service_handler(
2205 0 : r,
2206 0 : handle_tenant_shard_migrate,
2207 0 : RequestName("control_v1_tenant_migrate"),
2208 0 : )
2209 0 : })
2210 0 : .put(
2211 0 : "/control/v1/tenant/:tenant_shard_id/migrate_secondary",
2212 0 : |r| {
2213 0 : tenant_service_handler(
2214 0 : r,
2215 0 : handle_tenant_shard_migrate_secondary,
2216 0 : RequestName("control_v1_tenant_migrate_secondary"),
2217 0 : )
2218 0 : },
2219 0 : )
2220 0 : .put(
2221 0 : "/control/v1/tenant/:tenant_shard_id/cancel_reconcile",
2222 0 : |r| {
2223 0 : tenant_service_handler(
2224 0 : r,
2225 0 : handle_tenant_shard_cancel_reconcile,
2226 0 : RequestName("control_v1_tenant_cancel_reconcile"),
2227 0 : )
2228 0 : },
2229 0 : )
2230 0 : .put("/control/v1/tenant/:tenant_id/shard_split", |r| {
2231 0 : tenant_service_handler(
2232 0 : r,
2233 0 : handle_tenant_shard_split,
2234 0 : RequestName("control_v1_tenant_shard_split"),
2235 0 : )
2236 0 : })
2237 0 : .get("/control/v1/tenant/:tenant_id", |r| {
2238 0 : tenant_service_handler(
2239 0 : r,
2240 0 : handle_tenant_describe,
2241 0 : RequestName("control_v1_tenant_describe"),
2242 0 : )
2243 0 : })
2244 0 : .get("/control/v1/tenant", |r| {
2245 0 : tenant_service_handler(r, handle_tenant_list, RequestName("control_v1_tenant_list"))
2246 0 : })
2247 0 : .put("/control/v1/tenant/:tenant_id/policy", |r| {
2248 0 : named_request_span(
2249 0 : r,
2250 0 : handle_tenant_update_policy,
2251 0 : RequestName("control_v1_tenant_policy"),
2252 0 : )
2253 0 : })
2254 0 : .put("/control/v1/preferred_azs", |r| {
2255 0 : named_request_span(
2256 0 : r,
2257 0 : handle_update_preferred_azs,
2258 0 : RequestName("control_v1_preferred_azs"),
2259 0 : )
2260 0 : })
2261 0 : .put("/control/v1/step_down", |r| {
2262 0 : named_request_span(r, handle_step_down, RequestName("control_v1_step_down"))
2263 0 : })
2264 0 : // Tenant operations
2265 0 : // The ^/v1/ endpoints act as a "Virtual Pageserver", enabling shard-naive clients to call into
2266 0 : // this service to manage tenants that actually consist of many tenant shards, as if they are a single entity.
2267 0 : .post("/v1/tenant", |r| {
2268 0 : tenant_service_handler(r, handle_tenant_create, RequestName("v1_tenant"))
2269 0 : })
2270 0 : .delete("/v1/tenant/:tenant_id", |r| {
2271 0 : tenant_service_handler(r, handle_tenant_delete, RequestName("v1_tenant"))
2272 0 : })
2273 0 : .patch("/v1/tenant/config", |r| {
2274 0 : tenant_service_handler(
2275 0 : r,
2276 0 : handle_tenant_config_patch,
2277 0 : RequestName("v1_tenant_config"),
2278 0 : )
2279 0 : })
2280 0 : .put("/v1/tenant/config", |r| {
2281 0 : tenant_service_handler(r, handle_tenant_config_set, RequestName("v1_tenant_config"))
2282 0 : })
2283 0 : .get("/v1/tenant/:tenant_id/config", |r| {
2284 0 : tenant_service_handler(r, handle_tenant_config_get, RequestName("v1_tenant_config"))
2285 0 : })
2286 0 : .put("/v1/tenant/:tenant_shard_id/location_config", |r| {
2287 0 : tenant_service_handler(
2288 0 : r,
2289 0 : handle_tenant_location_config,
2290 0 : RequestName("v1_tenant_location_config"),
2291 0 : )
2292 0 : })
2293 0 : .put("/v1/tenant/:tenant_id/time_travel_remote_storage", |r| {
2294 0 : tenant_service_handler(
2295 0 : r,
2296 0 : handle_tenant_time_travel_remote_storage,
2297 0 : RequestName("v1_tenant_time_travel_remote_storage"),
2298 0 : )
2299 0 : })
2300 0 : .post("/v1/tenant/:tenant_id/secondary/download", |r| {
2301 0 : tenant_service_handler(
2302 0 : r,
2303 0 : handle_tenant_secondary_download,
2304 0 : RequestName("v1_tenant_secondary_download"),
2305 0 : )
2306 0 : })
2307 0 : // Timeline operations
2308 0 : .delete("/v1/tenant/:tenant_id/timeline/:timeline_id", |r| {
2309 0 : tenant_service_handler(
2310 0 : r,
2311 0 : handle_tenant_timeline_delete,
2312 0 : RequestName("v1_tenant_timeline"),
2313 0 : )
2314 0 : })
2315 0 : .post("/v1/tenant/:tenant_id/timeline", |r| {
2316 0 : tenant_service_handler(
2317 0 : r,
2318 0 : handle_tenant_timeline_create,
2319 0 : RequestName("v1_tenant_timeline"),
2320 0 : )
2321 0 : })
2322 0 : .put(
2323 0 : "/v1/tenant/:tenant_id/timeline/:timeline_id/archival_config",
2324 0 : |r| {
2325 0 : tenant_service_handler(
2326 0 : r,
2327 0 : handle_tenant_timeline_archival_config,
2328 0 : RequestName("v1_tenant_timeline_archival_config"),
2329 0 : )
2330 0 : },
2331 0 : )
2332 0 : .put(
2333 0 : "/v1/tenant/:tenant_id/timeline/:timeline_id/detach_ancestor",
2334 0 : |r| {
2335 0 : tenant_service_handler(
2336 0 : r,
2337 0 : handle_tenant_timeline_detach_ancestor,
2338 0 : RequestName("v1_tenant_timeline_detach_ancestor"),
2339 0 : )
2340 0 : },
2341 0 : )
2342 0 : .post(
2343 0 : "/v1/tenant/:tenant_id/timeline/:timeline_id/block_gc",
2344 0 : |r| {
2345 0 : tenant_service_handler(
2346 0 : r,
2347 0 : |s, r| handle_tenant_timeline_block_unblock_gc(s, r, BlockUnblock::Block),
2348 0 : RequestName("v1_tenant_timeline_block_unblock_gc"),
2349 0 : )
2350 0 : },
2351 0 : )
2352 0 : .post(
2353 0 : "/v1/tenant/:tenant_id/timeline/:timeline_id/unblock_gc",
2354 0 : |r| {
2355 0 : tenant_service_handler(
2356 0 : r,
2357 0 : |s, r| handle_tenant_timeline_block_unblock_gc(s, r, BlockUnblock::Unblock),
2358 0 : RequestName("v1_tenant_timeline_block_unblock_gc"),
2359 0 : )
2360 0 : },
2361 0 : )
2362 0 : .post(
2363 0 : "/v1/tenant/:tenant_shard_id/timeline/:timeline_id/download_heatmap_layers",
2364 0 : |r| {
2365 0 : tenant_service_handler(
2366 0 : r,
2367 0 : handle_tenant_timeline_download_heatmap_layers,
2368 0 : RequestName("v1_tenant_timeline_download_heatmap_layers"),
2369 0 : )
2370 0 : },
2371 0 : )
2372 0 : // LSN lease passthrough to all shards
2373 0 : .post(
2374 0 : "/v1/tenant/:tenant_id/timeline/:timeline_id/lsn_lease",
2375 0 : |r| {
2376 0 : tenant_service_handler(
2377 0 : r,
2378 0 : handle_tenant_timeline_lsn_lease,
2379 0 : RequestName("v1_tenant_timeline_lsn_lease"),
2380 0 : )
2381 0 : },
2382 0 : )
2383 0 : // Tenant detail GET passthrough to shard zero:
2384 0 : .get("/v1/tenant/:tenant_id", |r| {
2385 0 : tenant_service_handler(
2386 0 : r,
2387 0 : handle_tenant_timeline_passthrough,
2388 0 : RequestName("v1_tenant_passthrough"),
2389 0 : )
2390 0 : })
2391 0 : // The `*` in the URL is a wildcard: any tenant/timeline GET APIs on the pageserver
2392 0 : // are implicitly exposed here. This must be last in the list to avoid
2393 0 : // taking precedence over other GET methods we might implement by hand.
2394 0 : .get("/v1/tenant/:tenant_id/*", |r| {
2395 0 : tenant_service_handler(
2396 0 : r,
2397 0 : handle_tenant_timeline_passthrough,
2398 0 : RequestName("v1_tenant_passthrough"),
2399 0 : )
2400 0 : })
2401 0 : // Tenant timeline mark_invisible passthrough to shard zero
2402 0 : .put(
2403 0 : "/v1/tenant/:tenant_id/timeline/:timeline_id/mark_invisible",
2404 0 : |r| {
2405 0 : tenant_service_handler(
2406 0 : r,
2407 0 : handle_tenant_timeline_passthrough,
2408 0 : RequestName("v1_tenant_timeline_mark_invisible_passthrough"),
2409 0 : )
2410 0 : },
2411 0 : )
2412 0 : }
2413 :
2414 : #[cfg(test)]
2415 : mod test {
2416 :
2417 : use super::path_without_ids;
2418 :
2419 : #[test]
2420 1 : fn test_path_without_ids() {
2421 1 : assert_eq!(
2422 1 : path_without_ids(
2423 1 : "/v1/tenant/1a2b3344556677881122334455667788/timeline/AA223344556677881122334455667788"
2424 1 : ),
2425 1 : "/v1/tenant//timeline/"
2426 1 : );
2427 1 : assert_eq!(
2428 1 : path_without_ids(
2429 1 : "/v1/tenant/1a2b3344556677881122334455667788-0108/timeline/AA223344556677881122334455667788"
2430 1 : ),
2431 1 : "/v1/tenant//timeline/"
2432 1 : );
2433 1 : assert_eq!(
2434 1 : path_without_ids(
2435 1 : "/v1/tenant/1a2b3344556677881122334455667788-0108/timeline/AA223344556677881122334455667788?parameter=foo"
2436 1 : ),
2437 1 : "/v1/tenant//timeline/"
2438 1 : );
2439 1 : }
2440 : }
|