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