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