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