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_download_heatmap_layers(
520 0 : service: Arc<Service>,
521 0 : req: Request<Body>,
522 0 : ) -> Result<Response<Body>, ApiError> {
523 0 : let tenant_shard_id: TenantShardId = parse_request_param(&req, "tenant_shard_id")?;
524 :
525 0 : check_permissions(&req, Scope::PageServerApi)?;
526 :
527 0 : let timeline_id: TimelineId = parse_request_param(&req, "timeline_id")?;
528 0 : let concurrency: Option<usize> = parse_query_param(&req, "concurrency")?;
529 :
530 0 : service
531 0 : .tenant_timeline_download_heatmap_layers(tenant_shard_id, timeline_id, concurrency)
532 0 : .await?;
533 :
534 0 : json_response(StatusCode::OK, ())
535 0 : }
536 :
537 : // For metric labels where we would like to include the approximate path, but exclude high-cardinality fields like query parameters
538 : // and tenant/timeline IDs. Since we are proxying to arbitrary paths, we don't have routing templates to
539 : // compare to, so we can just filter out our well known ID format with regexes.
540 3 : fn path_without_ids(path: &str) -> String {
541 : static ID_REGEX: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
542 3 : ID_REGEX
543 3 : .get_or_init(|| regex::Regex::new(r"([0-9a-fA-F]{32}(-[0-9]{4})?|\?.*)").unwrap())
544 3 : .replace_all(path, "")
545 3 : .to_string()
546 3 : }
547 :
548 0 : async fn handle_tenant_timeline_passthrough(
549 0 : service: Arc<Service>,
550 0 : req: Request<Body>,
551 0 : ) -> Result<Response<Body>, ApiError> {
552 0 : let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
553 0 : check_permissions(&req, Scope::PageServerApi)?;
554 :
555 0 : let req = match maybe_forward(req).await {
556 0 : ForwardOutcome::Forwarded(res) => {
557 0 : return res;
558 : }
559 0 : ForwardOutcome::NotForwarded(req) => req,
560 : };
561 :
562 0 : let Some(path) = req.uri().path_and_query() else {
563 : // This should never happen, our request router only calls us if there is a path
564 0 : return Err(ApiError::BadRequest(anyhow::anyhow!("Missing path")));
565 : };
566 :
567 0 : tracing::info!("Proxying request for tenant {} ({})", tenant_id, path);
568 :
569 : // Find the node that holds shard zero
570 0 : let (node, tenant_shard_id) = service.tenant_shard0_node(tenant_id).await?;
571 :
572 : // Callers will always pass an unsharded tenant ID. Before proxying, we must
573 : // rewrite this to a shard-aware shard zero ID.
574 0 : let path = format!("{}", path);
575 0 : let tenant_str = tenant_id.to_string();
576 0 : let tenant_shard_str = format!("{}", tenant_shard_id);
577 0 : let path = path.replace(&tenant_str, &tenant_shard_str);
578 0 :
579 0 : let latency = &METRICS_REGISTRY
580 0 : .metrics_group
581 0 : .storage_controller_passthrough_request_latency;
582 0 :
583 0 : let path_label = path_without_ids(&path)
584 0 : .split('/')
585 0 : .filter(|token| !token.is_empty())
586 0 : .collect::<Vec<_>>()
587 0 : .join("_");
588 0 : let labels = PageserverRequestLabelGroup {
589 0 : pageserver_id: &node.get_id().to_string(),
590 0 : path: &path_label,
591 0 : method: crate::metrics::Method::Get,
592 0 : };
593 0 :
594 0 : let _timer = latency.start_timer(labels.clone());
595 0 :
596 0 : let client = mgmt_api::Client::new(node.base_url(), service.get_config().jwt_token.as_deref());
597 0 : let resp = client.get_raw(path).await.map_err(|e|
598 : // We return 503 here because if we can't successfully send a request to the pageserver,
599 : // either we aren't available or the pageserver is unavailable.
600 0 : ApiError::ResourceUnavailable(format!("Error sending pageserver API request to {node}: {e}").into()))?;
601 :
602 0 : if !resp.status().is_success() {
603 0 : let error_counter = &METRICS_REGISTRY
604 0 : .metrics_group
605 0 : .storage_controller_passthrough_request_error;
606 0 : error_counter.inc(labels);
607 0 : }
608 :
609 : // Transform 404 into 503 if we raced with a migration
610 0 : if resp.status() == reqwest::StatusCode::NOT_FOUND {
611 : // Look up node again: if we migrated it will be different
612 0 : let (new_node, _tenant_shard_id) = service.tenant_shard0_node(tenant_id).await?;
613 0 : if new_node.get_id() != node.get_id() {
614 : // Rather than retry here, send the client a 503 to prompt a retry: this matches
615 : // the pageserver's use of 503, and all clients calling this API should retry on 503.
616 0 : return Err(ApiError::ResourceUnavailable(
617 0 : format!("Pageserver {node} returned 404, was migrated to {new_node}").into(),
618 0 : ));
619 0 : }
620 0 : }
621 :
622 : // We have a reqest::Response, would like a http::Response
623 0 : let mut builder = hyper::Response::builder().status(map_reqwest_hyper_status(resp.status())?);
624 0 : for (k, v) in resp.headers() {
625 0 : builder = builder.header(k.as_str(), v.as_bytes());
626 0 : }
627 :
628 0 : let response = builder
629 0 : .body(Body::wrap_stream(resp.bytes_stream()))
630 0 : .map_err(|e| ApiError::InternalServerError(e.into()))?;
631 :
632 0 : Ok(response)
633 0 : }
634 :
635 0 : async fn handle_tenant_locate(
636 0 : service: Arc<Service>,
637 0 : req: Request<Body>,
638 0 : ) -> Result<Response<Body>, ApiError> {
639 0 : let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
640 :
641 0 : check_permissions(&req, Scope::Admin)?;
642 :
643 0 : match maybe_forward(req).await {
644 0 : ForwardOutcome::Forwarded(res) => {
645 0 : return res;
646 : }
647 0 : ForwardOutcome::NotForwarded(_req) => {}
648 0 : };
649 0 :
650 0 : json_response(StatusCode::OK, service.tenant_locate(tenant_id)?)
651 0 : }
652 :
653 0 : async fn handle_tenant_describe(
654 0 : service: Arc<Service>,
655 0 : req: Request<Body>,
656 0 : ) -> Result<Response<Body>, ApiError> {
657 0 : check_permissions(&req, Scope::Scrubber)?;
658 :
659 0 : let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
660 :
661 0 : match maybe_forward(req).await {
662 0 : ForwardOutcome::Forwarded(res) => {
663 0 : return res;
664 : }
665 0 : ForwardOutcome::NotForwarded(_req) => {}
666 0 : };
667 0 :
668 0 : json_response(StatusCode::OK, service.tenant_describe(tenant_id)?)
669 0 : }
670 :
671 0 : async fn handle_tenant_list(
672 0 : service: Arc<Service>,
673 0 : req: Request<Body>,
674 0 : ) -> Result<Response<Body>, ApiError> {
675 0 : check_permissions(&req, Scope::Admin)?;
676 :
677 0 : let limit: Option<usize> = parse_query_param(&req, "limit")?;
678 0 : let start_after: Option<TenantId> = parse_query_param(&req, "start_after")?;
679 0 : tracing::info!("start_after: {:?}", start_after);
680 :
681 0 : match maybe_forward(req).await {
682 0 : ForwardOutcome::Forwarded(res) => {
683 0 : return res;
684 : }
685 0 : ForwardOutcome::NotForwarded(_req) => {}
686 0 : };
687 0 :
688 0 : json_response(StatusCode::OK, service.tenant_list(limit, start_after))
689 0 : }
690 :
691 0 : async fn handle_node_register(req: Request<Body>) -> Result<Response<Body>, ApiError> {
692 0 : check_permissions(&req, Scope::Infra)?;
693 :
694 0 : let mut req = match maybe_forward(req).await {
695 0 : ForwardOutcome::Forwarded(res) => {
696 0 : return res;
697 : }
698 0 : ForwardOutcome::NotForwarded(req) => req,
699 : };
700 :
701 0 : let register_req = json_request::<NodeRegisterRequest>(&mut req).await?;
702 0 : let state = get_state(&req);
703 0 : state.service.node_register(register_req).await?;
704 0 : json_response(StatusCode::OK, ())
705 0 : }
706 :
707 0 : async fn handle_node_list(req: Request<Body>) -> Result<Response<Body>, ApiError> {
708 0 : check_permissions(&req, Scope::Infra)?;
709 :
710 0 : let req = match maybe_forward(req).await {
711 0 : ForwardOutcome::Forwarded(res) => {
712 0 : return res;
713 : }
714 0 : ForwardOutcome::NotForwarded(req) => req,
715 0 : };
716 0 :
717 0 : let state = get_state(&req);
718 0 : let mut nodes = state.service.node_list().await?;
719 0 : nodes.sort_by_key(|n| n.get_id());
720 0 : let api_nodes = nodes.into_iter().map(|n| n.describe()).collect::<Vec<_>>();
721 0 :
722 0 : json_response(StatusCode::OK, api_nodes)
723 0 : }
724 :
725 0 : async fn handle_node_drop(req: Request<Body>) -> Result<Response<Body>, ApiError> {
726 0 : check_permissions(&req, Scope::Admin)?;
727 :
728 0 : let req = match maybe_forward(req).await {
729 0 : ForwardOutcome::Forwarded(res) => {
730 0 : return res;
731 : }
732 0 : ForwardOutcome::NotForwarded(req) => req,
733 0 : };
734 0 :
735 0 : let state = get_state(&req);
736 0 : let node_id: NodeId = parse_request_param(&req, "node_id")?;
737 0 : json_response(StatusCode::OK, state.service.node_drop(node_id).await?)
738 0 : }
739 :
740 0 : async fn handle_node_delete(req: Request<Body>) -> Result<Response<Body>, ApiError> {
741 0 : check_permissions(&req, Scope::Admin)?;
742 :
743 0 : let req = match maybe_forward(req).await {
744 0 : ForwardOutcome::Forwarded(res) => {
745 0 : return res;
746 : }
747 0 : ForwardOutcome::NotForwarded(req) => req,
748 0 : };
749 0 :
750 0 : let state = get_state(&req);
751 0 : let node_id: NodeId = parse_request_param(&req, "node_id")?;
752 0 : json_response(StatusCode::OK, state.service.node_delete(node_id).await?)
753 0 : }
754 :
755 0 : async fn handle_node_configure(req: Request<Body>) -> Result<Response<Body>, ApiError> {
756 0 : check_permissions(&req, Scope::Admin)?;
757 :
758 0 : let mut req = match maybe_forward(req).await {
759 0 : ForwardOutcome::Forwarded(res) => {
760 0 : return res;
761 : }
762 0 : ForwardOutcome::NotForwarded(req) => req,
763 : };
764 :
765 0 : let node_id: NodeId = parse_request_param(&req, "node_id")?;
766 0 : let config_req = json_request::<NodeConfigureRequest>(&mut req).await?;
767 0 : if node_id != config_req.node_id {
768 0 : return Err(ApiError::BadRequest(anyhow::anyhow!(
769 0 : "Path and body node_id differ"
770 0 : )));
771 0 : }
772 0 : let state = get_state(&req);
773 0 :
774 0 : json_response(
775 0 : StatusCode::OK,
776 0 : state
777 0 : .service
778 0 : .external_node_configure(
779 0 : config_req.node_id,
780 0 : config_req.availability.map(NodeAvailability::from),
781 0 : config_req.scheduling,
782 0 : )
783 0 : .await?,
784 : )
785 0 : }
786 :
787 0 : async fn handle_node_status(req: Request<Body>) -> Result<Response<Body>, ApiError> {
788 0 : check_permissions(&req, Scope::Infra)?;
789 :
790 0 : let req = match maybe_forward(req).await {
791 0 : ForwardOutcome::Forwarded(res) => {
792 0 : return res;
793 : }
794 0 : ForwardOutcome::NotForwarded(req) => req,
795 0 : };
796 0 :
797 0 : let state = get_state(&req);
798 0 : let node_id: NodeId = parse_request_param(&req, "node_id")?;
799 :
800 0 : let node_status = state.service.get_node(node_id).await?;
801 :
802 0 : json_response(StatusCode::OK, node_status)
803 0 : }
804 :
805 0 : async fn handle_node_shards(req: Request<Body>) -> Result<Response<Body>, ApiError> {
806 0 : check_permissions(&req, Scope::Admin)?;
807 :
808 0 : let state = get_state(&req);
809 0 : let node_id: NodeId = parse_request_param(&req, "node_id")?;
810 :
811 0 : let node_status = state.service.get_node_shards(node_id).await?;
812 :
813 0 : json_response(StatusCode::OK, node_status)
814 0 : }
815 :
816 0 : async fn handle_get_leader(req: Request<Body>) -> Result<Response<Body>, ApiError> {
817 0 : check_permissions(&req, Scope::Admin)?;
818 :
819 0 : let req = match maybe_forward(req).await {
820 0 : ForwardOutcome::Forwarded(res) => {
821 0 : return res;
822 : }
823 0 : ForwardOutcome::NotForwarded(req) => req,
824 0 : };
825 0 :
826 0 : let state = get_state(&req);
827 0 : let leader = state.service.get_leader().await.map_err(|err| {
828 0 : ApiError::InternalServerError(anyhow::anyhow!(
829 0 : "Failed to read leader from database: {err}"
830 0 : ))
831 0 : })?;
832 :
833 0 : json_response(StatusCode::OK, leader)
834 0 : }
835 :
836 0 : async fn handle_node_drain(req: Request<Body>) -> Result<Response<Body>, ApiError> {
837 0 : check_permissions(&req, Scope::Infra)?;
838 :
839 0 : let req = match maybe_forward(req).await {
840 0 : ForwardOutcome::Forwarded(res) => {
841 0 : return res;
842 : }
843 0 : ForwardOutcome::NotForwarded(req) => req,
844 0 : };
845 0 :
846 0 : let state = get_state(&req);
847 0 : let node_id: NodeId = parse_request_param(&req, "node_id")?;
848 :
849 0 : state.service.start_node_drain(node_id).await?;
850 :
851 0 : json_response(StatusCode::ACCEPTED, ())
852 0 : }
853 :
854 0 : async fn handle_cancel_node_drain(req: Request<Body>) -> Result<Response<Body>, ApiError> {
855 0 : check_permissions(&req, Scope::Infra)?;
856 :
857 0 : let req = match maybe_forward(req).await {
858 0 : ForwardOutcome::Forwarded(res) => {
859 0 : return res;
860 : }
861 0 : ForwardOutcome::NotForwarded(req) => req,
862 0 : };
863 0 :
864 0 : let state = get_state(&req);
865 0 : let node_id: NodeId = parse_request_param(&req, "node_id")?;
866 :
867 0 : state.service.cancel_node_drain(node_id).await?;
868 :
869 0 : json_response(StatusCode::ACCEPTED, ())
870 0 : }
871 :
872 0 : async fn handle_node_fill(req: Request<Body>) -> Result<Response<Body>, ApiError> {
873 0 : check_permissions(&req, Scope::Infra)?;
874 :
875 0 : let req = match maybe_forward(req).await {
876 0 : ForwardOutcome::Forwarded(res) => {
877 0 : return res;
878 : }
879 0 : ForwardOutcome::NotForwarded(req) => req,
880 0 : };
881 0 :
882 0 : let state = get_state(&req);
883 0 : let node_id: NodeId = parse_request_param(&req, "node_id")?;
884 :
885 0 : state.service.start_node_fill(node_id).await?;
886 :
887 0 : json_response(StatusCode::ACCEPTED, ())
888 0 : }
889 :
890 0 : async fn handle_cancel_node_fill(req: Request<Body>) -> Result<Response<Body>, ApiError> {
891 0 : check_permissions(&req, Scope::Infra)?;
892 :
893 0 : let req = match maybe_forward(req).await {
894 0 : ForwardOutcome::Forwarded(res) => {
895 0 : return res;
896 : }
897 0 : ForwardOutcome::NotForwarded(req) => req,
898 0 : };
899 0 :
900 0 : let state = get_state(&req);
901 0 : let node_id: NodeId = parse_request_param(&req, "node_id")?;
902 :
903 0 : state.service.cancel_node_fill(node_id).await?;
904 :
905 0 : json_response(StatusCode::ACCEPTED, ())
906 0 : }
907 :
908 0 : async fn handle_safekeeper_list(req: Request<Body>) -> Result<Response<Body>, ApiError> {
909 0 : check_permissions(&req, Scope::Infra)?;
910 :
911 0 : let req = match maybe_forward(req).await {
912 0 : ForwardOutcome::Forwarded(res) => {
913 0 : return res;
914 : }
915 0 : ForwardOutcome::NotForwarded(req) => req,
916 0 : };
917 0 :
918 0 : let state = get_state(&req);
919 0 : let safekeepers = state.service.safekeepers_list().await?;
920 0 : json_response(StatusCode::OK, safekeepers)
921 0 : }
922 :
923 0 : async fn handle_metadata_health_update(req: Request<Body>) -> Result<Response<Body>, ApiError> {
924 0 : check_permissions(&req, Scope::Scrubber)?;
925 :
926 0 : let mut req = match maybe_forward(req).await {
927 0 : ForwardOutcome::Forwarded(res) => {
928 0 : return res;
929 : }
930 0 : ForwardOutcome::NotForwarded(req) => req,
931 : };
932 :
933 0 : let update_req = json_request::<MetadataHealthUpdateRequest>(&mut req).await?;
934 0 : let state = get_state(&req);
935 0 :
936 0 : state.service.metadata_health_update(update_req).await?;
937 :
938 0 : json_response(StatusCode::OK, MetadataHealthUpdateResponse {})
939 0 : }
940 :
941 0 : async fn handle_metadata_health_list_unhealthy(
942 0 : req: Request<Body>,
943 0 : ) -> Result<Response<Body>, ApiError> {
944 0 : check_permissions(&req, Scope::Admin)?;
945 :
946 0 : let req = match maybe_forward(req).await {
947 0 : ForwardOutcome::Forwarded(res) => {
948 0 : return res;
949 : }
950 0 : ForwardOutcome::NotForwarded(req) => req,
951 0 : };
952 0 :
953 0 : let state = get_state(&req);
954 0 : let unhealthy_tenant_shards = state.service.metadata_health_list_unhealthy().await?;
955 :
956 0 : json_response(
957 0 : StatusCode::OK,
958 0 : MetadataHealthListUnhealthyResponse {
959 0 : unhealthy_tenant_shards,
960 0 : },
961 0 : )
962 0 : }
963 :
964 0 : async fn handle_metadata_health_list_outdated(
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 list_outdated_req = json_request::<MetadataHealthListOutdatedRequest>(&mut req).await?;
977 0 : let state = get_state(&req);
978 0 : let health_records = state
979 0 : .service
980 0 : .metadata_health_list_outdated(list_outdated_req.not_scrubbed_for)
981 0 : .await?;
982 :
983 0 : json_response(
984 0 : StatusCode::OK,
985 0 : MetadataHealthListOutdatedResponse { health_records },
986 0 : )
987 0 : }
988 :
989 0 : async fn handle_tenant_shard_split(
990 0 : service: Arc<Service>,
991 0 : req: Request<Body>,
992 0 : ) -> Result<Response<Body>, ApiError> {
993 0 : check_permissions(&req, Scope::Admin)?;
994 :
995 0 : let mut req = match maybe_forward(req).await {
996 0 : ForwardOutcome::Forwarded(res) => {
997 0 : return res;
998 : }
999 0 : ForwardOutcome::NotForwarded(req) => req,
1000 : };
1001 :
1002 0 : let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
1003 0 : let split_req = json_request::<TenantShardSplitRequest>(&mut req).await?;
1004 :
1005 : json_response(
1006 : StatusCode::OK,
1007 0 : service.tenant_shard_split(tenant_id, split_req).await?,
1008 : )
1009 0 : }
1010 :
1011 0 : async fn handle_tenant_shard_migrate(
1012 0 : service: Arc<Service>,
1013 0 : req: Request<Body>,
1014 0 : ) -> Result<Response<Body>, ApiError> {
1015 0 : check_permissions(&req, Scope::Admin)?;
1016 :
1017 0 : let mut req = match maybe_forward(req).await {
1018 0 : ForwardOutcome::Forwarded(res) => {
1019 0 : return res;
1020 : }
1021 0 : ForwardOutcome::NotForwarded(req) => req,
1022 : };
1023 :
1024 0 : let tenant_shard_id: TenantShardId = parse_request_param(&req, "tenant_shard_id")?;
1025 0 : let migrate_req = json_request::<TenantShardMigrateRequest>(&mut req).await?;
1026 : json_response(
1027 : StatusCode::OK,
1028 0 : service
1029 0 : .tenant_shard_migrate(tenant_shard_id, migrate_req)
1030 0 : .await?,
1031 : )
1032 0 : }
1033 :
1034 0 : async fn handle_tenant_shard_migrate_secondary(
1035 0 : service: Arc<Service>,
1036 0 : req: Request<Body>,
1037 0 : ) -> Result<Response<Body>, ApiError> {
1038 0 : check_permissions(&req, Scope::Admin)?;
1039 :
1040 0 : let mut req = match maybe_forward(req).await {
1041 0 : ForwardOutcome::Forwarded(res) => {
1042 0 : return res;
1043 : }
1044 0 : ForwardOutcome::NotForwarded(req) => req,
1045 : };
1046 :
1047 0 : let tenant_shard_id: TenantShardId = parse_request_param(&req, "tenant_shard_id")?;
1048 0 : let migrate_req = json_request::<TenantShardMigrateRequest>(&mut req).await?;
1049 : json_response(
1050 : StatusCode::OK,
1051 0 : service
1052 0 : .tenant_shard_migrate_secondary(tenant_shard_id, migrate_req)
1053 0 : .await?,
1054 : )
1055 0 : }
1056 :
1057 0 : async fn handle_tenant_shard_cancel_reconcile(
1058 0 : service: Arc<Service>,
1059 0 : req: Request<Body>,
1060 0 : ) -> Result<Response<Body>, ApiError> {
1061 0 : check_permissions(&req, Scope::Admin)?;
1062 :
1063 0 : let req = match maybe_forward(req).await {
1064 0 : ForwardOutcome::Forwarded(res) => {
1065 0 : return res;
1066 : }
1067 0 : ForwardOutcome::NotForwarded(req) => req,
1068 : };
1069 :
1070 0 : let tenant_shard_id: TenantShardId = parse_request_param(&req, "tenant_shard_id")?;
1071 : json_response(
1072 : StatusCode::OK,
1073 0 : service
1074 0 : .tenant_shard_cancel_reconcile(tenant_shard_id)
1075 0 : .await?,
1076 : )
1077 0 : }
1078 :
1079 0 : async fn handle_tenant_update_policy(req: Request<Body>) -> Result<Response<Body>, ApiError> {
1080 0 : check_permissions(&req, Scope::Admin)?;
1081 :
1082 0 : let mut req = match maybe_forward(req).await {
1083 0 : ForwardOutcome::Forwarded(res) => {
1084 0 : return res;
1085 : }
1086 0 : ForwardOutcome::NotForwarded(req) => req,
1087 : };
1088 :
1089 0 : let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
1090 0 : let update_req = json_request::<TenantPolicyRequest>(&mut req).await?;
1091 0 : let state = get_state(&req);
1092 0 :
1093 0 : json_response(
1094 0 : StatusCode::OK,
1095 0 : state
1096 0 : .service
1097 0 : .tenant_update_policy(tenant_id, update_req)
1098 0 : .await?,
1099 : )
1100 0 : }
1101 :
1102 0 : async fn handle_update_preferred_azs(req: Request<Body>) -> Result<Response<Body>, ApiError> {
1103 0 : check_permissions(&req, Scope::Admin)?;
1104 :
1105 0 : let mut req = match maybe_forward(req).await {
1106 0 : ForwardOutcome::Forwarded(res) => {
1107 0 : return res;
1108 : }
1109 0 : ForwardOutcome::NotForwarded(req) => req,
1110 : };
1111 :
1112 0 : let azs_req = json_request::<ShardsPreferredAzsRequest>(&mut req).await?;
1113 0 : let state = get_state(&req);
1114 0 :
1115 0 : json_response(
1116 0 : StatusCode::OK,
1117 0 : state.service.update_shards_preferred_azs(azs_req).await?,
1118 : )
1119 0 : }
1120 :
1121 0 : async fn handle_step_down(req: Request<Body>) -> Result<Response<Body>, ApiError> {
1122 0 : check_permissions(&req, Scope::ControllerPeer)?;
1123 :
1124 0 : let req = match maybe_forward(req).await {
1125 0 : ForwardOutcome::Forwarded(res) => {
1126 0 : return res;
1127 : }
1128 0 : ForwardOutcome::NotForwarded(req) => req,
1129 0 : };
1130 0 :
1131 0 : let state = get_state(&req);
1132 0 : json_response(StatusCode::OK, state.service.step_down().await)
1133 0 : }
1134 :
1135 0 : async fn handle_tenant_drop(req: Request<Body>) -> Result<Response<Body>, ApiError> {
1136 0 : check_permissions(&req, Scope::PageServerApi)?;
1137 :
1138 0 : let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
1139 :
1140 0 : let req = match maybe_forward(req).await {
1141 0 : ForwardOutcome::Forwarded(res) => {
1142 0 : return res;
1143 : }
1144 0 : ForwardOutcome::NotForwarded(req) => req,
1145 0 : };
1146 0 :
1147 0 : let state = get_state(&req);
1148 0 :
1149 0 : json_response(StatusCode::OK, state.service.tenant_drop(tenant_id).await?)
1150 0 : }
1151 :
1152 0 : async fn handle_tenant_import(req: Request<Body>) -> Result<Response<Body>, ApiError> {
1153 0 : check_permissions(&req, Scope::PageServerApi)?;
1154 :
1155 0 : let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
1156 :
1157 0 : let req = match maybe_forward(req).await {
1158 0 : ForwardOutcome::Forwarded(res) => {
1159 0 : return res;
1160 : }
1161 0 : ForwardOutcome::NotForwarded(req) => req,
1162 0 : };
1163 0 :
1164 0 : let state = get_state(&req);
1165 0 :
1166 0 : json_response(
1167 0 : StatusCode::OK,
1168 0 : state.service.tenant_import(tenant_id).await?,
1169 : )
1170 0 : }
1171 :
1172 0 : async fn handle_tenants_dump(req: Request<Body>) -> Result<Response<Body>, ApiError> {
1173 0 : check_permissions(&req, Scope::Admin)?;
1174 :
1175 0 : let req = match maybe_forward(req).await {
1176 0 : ForwardOutcome::Forwarded(res) => {
1177 0 : return res;
1178 : }
1179 0 : ForwardOutcome::NotForwarded(req) => req,
1180 0 : };
1181 0 :
1182 0 : let state = get_state(&req);
1183 0 : state.service.tenants_dump()
1184 0 : }
1185 :
1186 0 : async fn handle_scheduler_dump(req: Request<Body>) -> Result<Response<Body>, ApiError> {
1187 0 : check_permissions(&req, Scope::Admin)?;
1188 :
1189 0 : let req = match maybe_forward(req).await {
1190 0 : ForwardOutcome::Forwarded(res) => {
1191 0 : return res;
1192 : }
1193 0 : ForwardOutcome::NotForwarded(req) => req,
1194 0 : };
1195 0 :
1196 0 : let state = get_state(&req);
1197 0 : state.service.scheduler_dump()
1198 0 : }
1199 :
1200 0 : async fn handle_consistency_check(req: Request<Body>) -> Result<Response<Body>, ApiError> {
1201 0 : check_permissions(&req, Scope::Admin)?;
1202 :
1203 0 : let req = match maybe_forward(req).await {
1204 0 : ForwardOutcome::Forwarded(res) => {
1205 0 : return res;
1206 : }
1207 0 : ForwardOutcome::NotForwarded(req) => req,
1208 0 : };
1209 0 :
1210 0 : let state = get_state(&req);
1211 0 :
1212 0 : json_response(StatusCode::OK, state.service.consistency_check().await?)
1213 0 : }
1214 :
1215 0 : async fn handle_reconcile_all(req: Request<Body>) -> Result<Response<Body>, ApiError> {
1216 0 : check_permissions(&req, Scope::Admin)?;
1217 :
1218 0 : let req = match maybe_forward(req).await {
1219 0 : ForwardOutcome::Forwarded(res) => {
1220 0 : return res;
1221 : }
1222 0 : ForwardOutcome::NotForwarded(req) => req,
1223 0 : };
1224 0 :
1225 0 : let state = get_state(&req);
1226 0 :
1227 0 : json_response(StatusCode::OK, state.service.reconcile_all_now().await?)
1228 0 : }
1229 :
1230 : /// Status endpoint is just used for checking that our HTTP listener is up
1231 0 : async fn handle_status(req: Request<Body>) -> Result<Response<Body>, ApiError> {
1232 0 : match maybe_forward(req).await {
1233 0 : ForwardOutcome::Forwarded(res) => {
1234 0 : return res;
1235 : }
1236 0 : ForwardOutcome::NotForwarded(_req) => {}
1237 0 : };
1238 0 :
1239 0 : json_response(StatusCode::OK, ())
1240 0 : }
1241 :
1242 : /// Readiness endpoint indicates when we're done doing startup I/O (e.g. reconciling
1243 : /// with remote pageserver nodes). This is intended for use as a kubernetes readiness probe.
1244 0 : async fn handle_ready(req: Request<Body>) -> Result<Response<Body>, ApiError> {
1245 0 : let req = match maybe_forward(req).await {
1246 0 : ForwardOutcome::Forwarded(res) => {
1247 0 : return res;
1248 : }
1249 0 : ForwardOutcome::NotForwarded(req) => req,
1250 0 : };
1251 0 :
1252 0 : let state = get_state(&req);
1253 0 : if state.service.startup_complete.is_ready() {
1254 0 : json_response(StatusCode::OK, ())
1255 : } else {
1256 0 : json_response(StatusCode::SERVICE_UNAVAILABLE, ())
1257 : }
1258 0 : }
1259 :
1260 : impl From<ReconcileError> for ApiError {
1261 0 : fn from(value: ReconcileError) -> Self {
1262 0 : ApiError::Conflict(format!("Reconciliation error: {}", value))
1263 0 : }
1264 : }
1265 :
1266 : /// Return the safekeeper record by instance id, or 404.
1267 : ///
1268 : /// Not used by anything except manual testing.
1269 0 : async fn handle_get_safekeeper(req: Request<Body>) -> Result<Response<Body>, ApiError> {
1270 0 : check_permissions(&req, Scope::Infra)?;
1271 :
1272 0 : let id = parse_request_param::<i64>(&req, "id")?;
1273 :
1274 0 : let req = match maybe_forward(req).await {
1275 0 : ForwardOutcome::Forwarded(res) => {
1276 0 : return res;
1277 : }
1278 0 : ForwardOutcome::NotForwarded(req) => req,
1279 0 : };
1280 0 :
1281 0 : let state = get_state(&req);
1282 :
1283 0 : let res = state.service.get_safekeeper(id).await;
1284 :
1285 0 : match res {
1286 0 : Ok(b) => json_response(StatusCode::OK, b),
1287 : Err(crate::persistence::DatabaseError::Query(diesel::result::Error::NotFound)) => {
1288 0 : Err(ApiError::NotFound("unknown instance id".into()))
1289 : }
1290 0 : Err(other) => Err(other.into()),
1291 : }
1292 0 : }
1293 :
1294 : /// Used as part of deployment scripts.
1295 : ///
1296 : /// Assumes information is only relayed to storage controller after first selecting an unique id on
1297 : /// control plane database, which means we have an id field in the request and payload.
1298 0 : async fn handle_upsert_safekeeper(mut req: Request<Body>) -> Result<Response<Body>, ApiError> {
1299 0 : check_permissions(&req, Scope::Infra)?;
1300 :
1301 0 : let body = json_request::<SafekeeperUpsert>(&mut req).await?;
1302 0 : let id = parse_request_param::<i64>(&req, "id")?;
1303 :
1304 0 : if id != body.id {
1305 : // it should be repeated
1306 0 : return Err(ApiError::BadRequest(anyhow::anyhow!(
1307 0 : "id mismatch: url={id:?}, body={:?}",
1308 0 : body.id
1309 0 : )));
1310 0 : }
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.service.upsert_safekeeper(body).await?;
1322 :
1323 0 : Ok(Response::builder()
1324 0 : .status(StatusCode::NO_CONTENT)
1325 0 : .body(Body::empty())
1326 0 : .unwrap())
1327 0 : }
1328 :
1329 : /// Sets the scheduling policy of the specified safekeeper
1330 0 : async fn handle_safekeeper_scheduling_policy(
1331 0 : mut req: Request<Body>,
1332 0 : ) -> Result<Response<Body>, ApiError> {
1333 0 : check_permissions(&req, Scope::Admin)?;
1334 :
1335 0 : let body = json_request::<SafekeeperSchedulingPolicyRequest>(&mut req).await?;
1336 0 : let id = parse_request_param::<i64>(&req, "id")?;
1337 :
1338 0 : let req = match maybe_forward(req).await {
1339 0 : ForwardOutcome::Forwarded(res) => {
1340 0 : return res;
1341 : }
1342 0 : ForwardOutcome::NotForwarded(req) => req,
1343 0 : };
1344 0 :
1345 0 : let state = get_state(&req);
1346 0 :
1347 0 : state
1348 0 : .service
1349 0 : .set_safekeeper_scheduling_policy(id, body.scheduling_policy)
1350 0 : .await?;
1351 :
1352 0 : Ok(Response::builder()
1353 0 : .status(StatusCode::NO_CONTENT)
1354 0 : .body(Body::empty())
1355 0 : .unwrap())
1356 0 : }
1357 :
1358 : /// Common wrapper for request handlers that call into Service and will operate on tenants: they must only
1359 : /// be allowed to run if Service has finished its initial reconciliation.
1360 0 : async fn tenant_service_handler<R, H>(
1361 0 : request: Request<Body>,
1362 0 : handler: H,
1363 0 : request_name: RequestName,
1364 0 : ) -> R::Output
1365 0 : where
1366 0 : R: std::future::Future<Output = Result<Response<Body>, ApiError>> + Send + 'static,
1367 0 : H: FnOnce(Arc<Service>, Request<Body>) -> R + Send + Sync + 'static,
1368 0 : {
1369 0 : let state = get_state(&request);
1370 0 : let service = state.service.clone();
1371 0 :
1372 0 : let startup_complete = service.startup_complete.clone();
1373 0 : if tokio::time::timeout(STARTUP_RECONCILE_TIMEOUT, startup_complete.wait())
1374 0 : .await
1375 0 : .is_err()
1376 : {
1377 : // This shouldn't happen: it is the responsibilty of [`Service::startup_reconcile`] to use appropriate
1378 : // timeouts around its remote calls, to bound its runtime.
1379 0 : return Err(ApiError::Timeout(
1380 0 : "Timed out waiting for service readiness".into(),
1381 0 : ));
1382 0 : }
1383 0 :
1384 0 : named_request_span(
1385 0 : request,
1386 0 : |request| async move { handler(service, request).await },
1387 0 : request_name,
1388 0 : )
1389 0 : .await
1390 0 : }
1391 :
1392 : /// Check if the required scope is held in the request's token, or if the request has
1393 : /// a token with 'admin' scope then always permit it.
1394 0 : fn check_permissions(request: &Request<Body>, required_scope: Scope) -> Result<(), ApiError> {
1395 0 : check_permission_with(request, |claims| {
1396 0 : match crate::auth::check_permission(claims, required_scope) {
1397 0 : Err(e) => match crate::auth::check_permission(claims, Scope::Admin) {
1398 0 : Ok(()) => Ok(()),
1399 0 : Err(_) => Err(e),
1400 : },
1401 0 : Ok(()) => Ok(()),
1402 : }
1403 0 : })
1404 0 : }
1405 :
1406 : #[derive(Clone, Debug)]
1407 : struct RequestMeta {
1408 : method: hyper::http::Method,
1409 : at: Instant,
1410 : }
1411 :
1412 0 : pub fn prologue_leadership_status_check_middleware<
1413 0 : B: hyper::body::HttpBody + Send + Sync + 'static,
1414 0 : >() -> Middleware<B, ApiError> {
1415 0 : Middleware::pre(move |req| async move {
1416 0 : let state = get_state(&req);
1417 0 : let leadership_status = state.service.get_leadership_status();
1418 :
1419 : enum AllowedRoutes<'a> {
1420 : All,
1421 : Some(Vec<&'a str>),
1422 : }
1423 :
1424 0 : let allowed_routes = match leadership_status {
1425 0 : LeadershipStatus::Leader => AllowedRoutes::All,
1426 0 : LeadershipStatus::SteppedDown => AllowedRoutes::All,
1427 : LeadershipStatus::Candidate => {
1428 0 : AllowedRoutes::Some(["/ready", "/status", "/metrics"].to_vec())
1429 : }
1430 : };
1431 :
1432 0 : let uri = req.uri().to_string();
1433 0 : match allowed_routes {
1434 0 : AllowedRoutes::All => Ok(req),
1435 0 : AllowedRoutes::Some(allowed) if allowed.contains(&uri.as_str()) => Ok(req),
1436 : _ => {
1437 0 : tracing::info!(
1438 0 : "Request {} not allowed due to current leadership state",
1439 0 : req.uri()
1440 : );
1441 :
1442 0 : Err(ApiError::ResourceUnavailable(
1443 0 : format!("Current leadership status is {leadership_status}").into(),
1444 0 : ))
1445 : }
1446 : }
1447 0 : })
1448 0 : }
1449 :
1450 0 : fn prologue_metrics_middleware<B: hyper::body::HttpBody + Send + Sync + 'static>(
1451 0 : ) -> Middleware<B, ApiError> {
1452 0 : Middleware::pre(move |req| async move {
1453 0 : let meta = RequestMeta {
1454 0 : method: req.method().clone(),
1455 0 : at: Instant::now(),
1456 0 : };
1457 0 :
1458 0 : req.set_context(meta);
1459 0 :
1460 0 : Ok(req)
1461 0 : })
1462 0 : }
1463 :
1464 0 : fn epilogue_metrics_middleware<B: hyper::body::HttpBody + Send + Sync + 'static>(
1465 0 : ) -> Middleware<B, ApiError> {
1466 0 : Middleware::post_with_info(move |resp, req_info| async move {
1467 0 : let request_name = match req_info.context::<RequestName>() {
1468 0 : Some(name) => name,
1469 : None => {
1470 0 : return Ok(resp);
1471 : }
1472 : };
1473 :
1474 0 : if let Some(meta) = req_info.context::<RequestMeta>() {
1475 0 : let status = &crate::metrics::METRICS_REGISTRY
1476 0 : .metrics_group
1477 0 : .storage_controller_http_request_status;
1478 0 : let latency = &crate::metrics::METRICS_REGISTRY
1479 0 : .metrics_group
1480 0 : .storage_controller_http_request_latency;
1481 0 :
1482 0 : status.inc(HttpRequestStatusLabelGroup {
1483 0 : path: request_name.0,
1484 0 : method: meta.method.clone().into(),
1485 0 : status: crate::metrics::StatusCode(resp.status()),
1486 0 : });
1487 0 :
1488 0 : latency.observe(
1489 0 : HttpRequestLatencyLabelGroup {
1490 0 : path: request_name.0,
1491 0 : method: meta.method.into(),
1492 0 : },
1493 0 : meta.at.elapsed().as_secs_f64(),
1494 0 : );
1495 0 : }
1496 0 : Ok(resp)
1497 0 : })
1498 0 : }
1499 :
1500 0 : pub async fn measured_metrics_handler(req: Request<Body>) -> Result<Response<Body>, ApiError> {
1501 : pub const TEXT_FORMAT: &str = "text/plain; version=0.0.4";
1502 :
1503 0 : let req = match maybe_forward(req).await {
1504 0 : ForwardOutcome::Forwarded(res) => {
1505 0 : return res;
1506 : }
1507 0 : ForwardOutcome::NotForwarded(req) => req,
1508 0 : };
1509 0 :
1510 0 : let state = get_state(&req);
1511 0 : let payload = crate::metrics::METRICS_REGISTRY.encode(&state.neon_metrics);
1512 0 : let response = Response::builder()
1513 0 : .status(200)
1514 0 : .header(CONTENT_TYPE, TEXT_FORMAT)
1515 0 : .body(payload.into())
1516 0 : .unwrap();
1517 0 :
1518 0 : Ok(response)
1519 0 : }
1520 :
1521 : #[derive(Clone)]
1522 : struct RequestName(&'static str);
1523 :
1524 0 : async fn named_request_span<R, H>(
1525 0 : request: Request<Body>,
1526 0 : handler: H,
1527 0 : name: RequestName,
1528 0 : ) -> R::Output
1529 0 : where
1530 0 : R: Future<Output = Result<Response<Body>, ApiError>> + Send + 'static,
1531 0 : H: FnOnce(Request<Body>) -> R + Send + Sync + 'static,
1532 0 : {
1533 0 : request.set_context(name);
1534 0 : request_span(request, handler).await
1535 0 : }
1536 :
1537 : enum ForwardOutcome {
1538 : Forwarded(Result<Response<Body>, ApiError>),
1539 : NotForwarded(Request<Body>),
1540 : }
1541 :
1542 : /// Potentially forward the request to the current storage controler leader.
1543 : /// More specifically we forward when:
1544 : /// 1. Request is not one of ["/control/v1/step_down", "/status", "/ready", "/metrics"]
1545 : /// 2. Current instance is in [`LeadershipStatus::SteppedDown`] state
1546 : /// 3. There is a leader in the database to forward to
1547 : /// 4. Leader from step (3) is not the current instance
1548 : ///
1549 : /// Why forward?
1550 : /// It turns out that we can't rely on external orchestration to promptly route trafic to the
1551 : /// new leader. This is downtime inducing. Forwarding provides a safe way out.
1552 : ///
1553 : /// Why is it safe?
1554 : /// If a storcon instance is persisted in the database, then we know that it is the current leader.
1555 : /// There's one exception: time between handling step-down request and the new leader updating the
1556 : /// database.
1557 : ///
1558 : /// Let's treat the happy case first. The stepped down node does not produce any side effects,
1559 : /// since all request handling happens on the leader.
1560 : ///
1561 : /// As for the edge case, we are guaranteed to always have a maximum of two running instances.
1562 : /// Hence, if we are in the edge case scenario the leader persisted in the database is the
1563 : /// stepped down instance that received the request. Condition (4) above covers this scenario.
1564 0 : async fn maybe_forward(req: Request<Body>) -> ForwardOutcome {
1565 : const NOT_FOR_FORWARD: [&str; 4] = ["/control/v1/step_down", "/status", "/ready", "/metrics"];
1566 :
1567 0 : let uri = req.uri().to_string();
1568 0 : let uri_for_forward = !NOT_FOR_FORWARD.contains(&uri.as_str());
1569 0 :
1570 0 : // Fast return before trying to take any Service locks, if we will never forward anyway
1571 0 : if !uri_for_forward {
1572 0 : return ForwardOutcome::NotForwarded(req);
1573 0 : }
1574 0 :
1575 0 : let state = get_state(&req);
1576 0 : let leadership_status = state.service.get_leadership_status();
1577 0 :
1578 0 : if leadership_status != LeadershipStatus::SteppedDown {
1579 0 : return ForwardOutcome::NotForwarded(req);
1580 0 : }
1581 :
1582 0 : let leader = state.service.get_leader().await;
1583 0 : let leader = {
1584 0 : match leader {
1585 0 : Ok(Some(leader)) => leader,
1586 : Ok(None) => {
1587 0 : return ForwardOutcome::Forwarded(Err(ApiError::ResourceUnavailable(
1588 0 : "No leader to forward to while in stepped down state".into(),
1589 0 : )));
1590 : }
1591 0 : Err(err) => {
1592 0 : return ForwardOutcome::Forwarded(Err(ApiError::InternalServerError(
1593 0 : anyhow::anyhow!(
1594 0 : "Failed to get leader for forwarding while in stepped down state: {err}"
1595 0 : ),
1596 0 : )));
1597 : }
1598 : }
1599 : };
1600 :
1601 0 : let cfg = state.service.get_config();
1602 0 : if let Some(ref self_addr) = cfg.address_for_peers {
1603 0 : let leader_addr = match Uri::from_str(leader.address.as_str()) {
1604 0 : Ok(uri) => uri,
1605 0 : Err(err) => {
1606 0 : return ForwardOutcome::Forwarded(Err(ApiError::InternalServerError(
1607 0 : anyhow::anyhow!(
1608 0 : "Failed to parse leader uri for forwarding while in stepped down state: {err}"
1609 0 : ),
1610 0 : )));
1611 : }
1612 : };
1613 :
1614 0 : if *self_addr == leader_addr {
1615 0 : return ForwardOutcome::Forwarded(Err(ApiError::InternalServerError(anyhow::anyhow!(
1616 0 : "Leader is stepped down instance"
1617 0 : ))));
1618 0 : }
1619 0 : }
1620 :
1621 0 : tracing::info!("Forwarding {} to leader at {}", uri, leader.address);
1622 :
1623 : // Use [`RECONCILE_TIMEOUT`] as the max amount of time a request should block for and
1624 : // include some leeway to get the timeout for proxied requests.
1625 : const PROXIED_REQUEST_TIMEOUT: Duration = Duration::from_secs(RECONCILE_TIMEOUT.as_secs() + 10);
1626 0 : let client = reqwest::ClientBuilder::new()
1627 0 : .timeout(PROXIED_REQUEST_TIMEOUT)
1628 0 : .build();
1629 0 : let client = match client {
1630 0 : Ok(client) => client,
1631 0 : Err(err) => {
1632 0 : return ForwardOutcome::Forwarded(Err(ApiError::InternalServerError(anyhow::anyhow!(
1633 0 : "Failed to build leader client for forwarding while in stepped down state: {err}"
1634 0 : ))));
1635 : }
1636 : };
1637 :
1638 0 : let request: reqwest::Request = match convert_request(req, &client, leader.address).await {
1639 0 : Ok(r) => r,
1640 0 : Err(err) => {
1641 0 : return ForwardOutcome::Forwarded(Err(ApiError::InternalServerError(anyhow::anyhow!(
1642 0 : "Failed to convert request for forwarding while in stepped down state: {err}"
1643 0 : ))));
1644 : }
1645 : };
1646 :
1647 0 : let response = match client.execute(request).await {
1648 0 : Ok(r) => r,
1649 0 : Err(err) => {
1650 0 : return ForwardOutcome::Forwarded(Err(ApiError::InternalServerError(anyhow::anyhow!(
1651 0 : "Failed to forward while in stepped down state: {err}"
1652 0 : ))));
1653 : }
1654 : };
1655 :
1656 0 : ForwardOutcome::Forwarded(convert_response(response).await)
1657 0 : }
1658 :
1659 : /// Convert a [`reqwest::Response`] to a [hyper::Response`] by passing through
1660 : /// a stable representation (string, bytes or integer)
1661 : ///
1662 : /// Ideally, we would not have to do this since both types use the http crate
1663 : /// under the hood. However, they use different versions of the crate and keeping
1664 : /// second order dependencies in sync is difficult.
1665 0 : async fn convert_response(resp: reqwest::Response) -> Result<hyper::Response<Body>, ApiError> {
1666 : use std::str::FromStr;
1667 :
1668 0 : let mut builder = hyper::Response::builder().status(resp.status().as_u16());
1669 0 : for (key, value) in resp.headers().into_iter() {
1670 0 : let key = hyper::header::HeaderName::from_str(key.as_str()).map_err(|err| {
1671 0 : ApiError::InternalServerError(anyhow::anyhow!("Response conversion failed: {err}"))
1672 0 : })?;
1673 :
1674 0 : let value = hyper::header::HeaderValue::from_bytes(value.as_bytes()).map_err(|err| {
1675 0 : ApiError::InternalServerError(anyhow::anyhow!("Response conversion failed: {err}"))
1676 0 : })?;
1677 :
1678 0 : builder = builder.header(key, value);
1679 : }
1680 :
1681 0 : let body = http::Body::wrap_stream(resp.bytes_stream());
1682 0 :
1683 0 : builder.body(body).map_err(|err| {
1684 0 : ApiError::InternalServerError(anyhow::anyhow!("Response conversion failed: {err}"))
1685 0 : })
1686 0 : }
1687 :
1688 : /// Convert a [`reqwest::Request`] to a [hyper::Request`] by passing through
1689 : /// a stable representation (string, bytes or integer)
1690 : ///
1691 : /// See [`convert_response`] for why we are doing it this way.
1692 0 : async fn convert_request(
1693 0 : req: hyper::Request<Body>,
1694 0 : client: &reqwest::Client,
1695 0 : to_address: String,
1696 0 : ) -> Result<reqwest::Request, ApiError> {
1697 : use std::str::FromStr;
1698 :
1699 0 : let (parts, body) = req.into_parts();
1700 0 : let method = reqwest::Method::from_str(parts.method.as_str()).map_err(|err| {
1701 0 : ApiError::InternalServerError(anyhow::anyhow!("Request conversion failed: {err}"))
1702 0 : })?;
1703 :
1704 0 : let path_and_query = parts.uri.path_and_query().ok_or_else(|| {
1705 0 : ApiError::InternalServerError(anyhow::anyhow!(
1706 0 : "Request conversion failed: no path and query"
1707 0 : ))
1708 0 : })?;
1709 :
1710 0 : let uri = reqwest::Url::from_str(
1711 0 : format!(
1712 0 : "{}{}",
1713 0 : to_address.trim_end_matches("/"),
1714 0 : path_and_query.as_str()
1715 0 : )
1716 0 : .as_str(),
1717 0 : )
1718 0 : .map_err(|err| {
1719 0 : ApiError::InternalServerError(anyhow::anyhow!("Request conversion failed: {err}"))
1720 0 : })?;
1721 :
1722 0 : let mut headers = reqwest::header::HeaderMap::new();
1723 0 : for (key, value) in parts.headers.into_iter() {
1724 0 : let key = match key {
1725 0 : Some(k) => k,
1726 : None => {
1727 0 : continue;
1728 : }
1729 : };
1730 :
1731 0 : let key = reqwest::header::HeaderName::from_str(key.as_str()).map_err(|err| {
1732 0 : ApiError::InternalServerError(anyhow::anyhow!("Request conversion failed: {err}"))
1733 0 : })?;
1734 :
1735 0 : let value = reqwest::header::HeaderValue::from_bytes(value.as_bytes()).map_err(|err| {
1736 0 : ApiError::InternalServerError(anyhow::anyhow!("Request conversion failed: {err}"))
1737 0 : })?;
1738 :
1739 0 : headers.insert(key, value);
1740 : }
1741 :
1742 0 : let body = hyper::body::to_bytes(body).await.map_err(|err| {
1743 0 : ApiError::InternalServerError(anyhow::anyhow!("Request conversion failed: {err}"))
1744 0 : })?;
1745 :
1746 0 : client
1747 0 : .request(method, uri)
1748 0 : .headers(headers)
1749 0 : .body(body)
1750 0 : .build()
1751 0 : .map_err(|err| {
1752 0 : ApiError::InternalServerError(anyhow::anyhow!("Request conversion failed: {err}"))
1753 0 : })
1754 0 : }
1755 :
1756 0 : pub fn make_router(
1757 0 : service: Arc<Service>,
1758 0 : auth: Option<Arc<SwappableJwtAuth>>,
1759 0 : build_info: BuildInfo,
1760 0 : ) -> RouterBuilder<hyper::Body, ApiError> {
1761 0 : let mut router = endpoint::make_router()
1762 0 : .middleware(prologue_leadership_status_check_middleware())
1763 0 : .middleware(prologue_metrics_middleware())
1764 0 : .middleware(epilogue_metrics_middleware());
1765 0 : if auth.is_some() {
1766 0 : router = router.middleware(auth_middleware(|request| {
1767 0 : let state = get_state(request);
1768 0 : if state.allowlist_routes.contains(request.uri()) {
1769 0 : None
1770 : } else {
1771 0 : state.auth.as_deref()
1772 : }
1773 0 : }));
1774 0 : }
1775 :
1776 0 : router
1777 0 : .data(Arc::new(HttpState::new(service, auth, build_info)))
1778 0 : .get("/metrics", |r| {
1779 0 : named_request_span(r, measured_metrics_handler, RequestName("metrics"))
1780 0 : })
1781 0 : // Non-prefixed generic endpoints (status, metrics)
1782 0 : .get("/status", |r| {
1783 0 : named_request_span(r, handle_status, RequestName("status"))
1784 0 : })
1785 0 : .get("/ready", |r| {
1786 0 : named_request_span(r, handle_ready, RequestName("ready"))
1787 0 : })
1788 0 : // Upcalls for the pageserver: point the pageserver's `control_plane_api` config to this prefix
1789 0 : .post("/upcall/v1/re-attach", |r| {
1790 0 : named_request_span(r, handle_re_attach, RequestName("upcall_v1_reattach"))
1791 0 : })
1792 0 : .post("/upcall/v1/validate", |r| {
1793 0 : named_request_span(r, handle_validate, RequestName("upcall_v1_validate"))
1794 0 : })
1795 0 : // Test/dev/debug endpoints
1796 0 : .post("/debug/v1/attach-hook", |r| {
1797 0 : named_request_span(r, handle_attach_hook, RequestName("debug_v1_attach_hook"))
1798 0 : })
1799 0 : .post("/debug/v1/inspect", |r| {
1800 0 : named_request_span(r, handle_inspect, RequestName("debug_v1_inspect"))
1801 0 : })
1802 0 : .post("/debug/v1/tenant/:tenant_id/drop", |r| {
1803 0 : named_request_span(r, handle_tenant_drop, RequestName("debug_v1_tenant_drop"))
1804 0 : })
1805 0 : .post("/debug/v1/node/:node_id/drop", |r| {
1806 0 : named_request_span(r, handle_node_drop, RequestName("debug_v1_node_drop"))
1807 0 : })
1808 0 : .post("/debug/v1/tenant/:tenant_id/import", |r| {
1809 0 : named_request_span(
1810 0 : r,
1811 0 : handle_tenant_import,
1812 0 : RequestName("debug_v1_tenant_import"),
1813 0 : )
1814 0 : })
1815 0 : .get("/debug/v1/tenant", |r| {
1816 0 : named_request_span(r, handle_tenants_dump, RequestName("debug_v1_tenant"))
1817 0 : })
1818 0 : .get("/debug/v1/tenant/:tenant_id/locate", |r| {
1819 0 : tenant_service_handler(
1820 0 : r,
1821 0 : handle_tenant_locate,
1822 0 : RequestName("debug_v1_tenant_locate"),
1823 0 : )
1824 0 : })
1825 0 : .get("/debug/v1/scheduler", |r| {
1826 0 : named_request_span(r, handle_scheduler_dump, RequestName("debug_v1_scheduler"))
1827 0 : })
1828 0 : .post("/debug/v1/consistency_check", |r| {
1829 0 : named_request_span(
1830 0 : r,
1831 0 : handle_consistency_check,
1832 0 : RequestName("debug_v1_consistency_check"),
1833 0 : )
1834 0 : })
1835 0 : .post("/debug/v1/reconcile_all", |r| {
1836 0 : request_span(r, handle_reconcile_all)
1837 0 : })
1838 0 : .put("/debug/v1/failpoints", |r| {
1839 0 : request_span(r, |r| failpoints_handler(r, CancellationToken::new()))
1840 0 : })
1841 0 : // Node operations
1842 0 : .post("/control/v1/node", |r| {
1843 0 : named_request_span(r, handle_node_register, RequestName("control_v1_node"))
1844 0 : })
1845 0 : .delete("/control/v1/node/:node_id", |r| {
1846 0 : named_request_span(r, handle_node_delete, RequestName("control_v1_node_delete"))
1847 0 : })
1848 0 : .get("/control/v1/node", |r| {
1849 0 : named_request_span(r, handle_node_list, RequestName("control_v1_node"))
1850 0 : })
1851 0 : .put("/control/v1/node/:node_id/config", |r| {
1852 0 : named_request_span(
1853 0 : r,
1854 0 : handle_node_configure,
1855 0 : RequestName("control_v1_node_config"),
1856 0 : )
1857 0 : })
1858 0 : .get("/control/v1/node/:node_id", |r| {
1859 0 : named_request_span(r, handle_node_status, RequestName("control_v1_node_status"))
1860 0 : })
1861 0 : .get("/control/v1/node/:node_id/shards", |r| {
1862 0 : named_request_span(
1863 0 : r,
1864 0 : handle_node_shards,
1865 0 : RequestName("control_v1_node_describe"),
1866 0 : )
1867 0 : })
1868 0 : .get("/control/v1/leader", |r| {
1869 0 : named_request_span(r, handle_get_leader, RequestName("control_v1_get_leader"))
1870 0 : })
1871 0 : .put("/control/v1/node/:node_id/drain", |r| {
1872 0 : named_request_span(r, handle_node_drain, RequestName("control_v1_node_drain"))
1873 0 : })
1874 0 : .delete("/control/v1/node/:node_id/drain", |r| {
1875 0 : named_request_span(
1876 0 : r,
1877 0 : handle_cancel_node_drain,
1878 0 : RequestName("control_v1_cancel_node_drain"),
1879 0 : )
1880 0 : })
1881 0 : .put("/control/v1/node/:node_id/fill", |r| {
1882 0 : named_request_span(r, handle_node_fill, RequestName("control_v1_node_fill"))
1883 0 : })
1884 0 : .delete("/control/v1/node/:node_id/fill", |r| {
1885 0 : named_request_span(
1886 0 : r,
1887 0 : handle_cancel_node_fill,
1888 0 : RequestName("control_v1_cancel_node_fill"),
1889 0 : )
1890 0 : })
1891 0 : // Metadata health operations
1892 0 : .post("/control/v1/metadata_health/update", |r| {
1893 0 : named_request_span(
1894 0 : r,
1895 0 : handle_metadata_health_update,
1896 0 : RequestName("control_v1_metadata_health_update"),
1897 0 : )
1898 0 : })
1899 0 : .get("/control/v1/metadata_health/unhealthy", |r| {
1900 0 : named_request_span(
1901 0 : r,
1902 0 : handle_metadata_health_list_unhealthy,
1903 0 : RequestName("control_v1_metadata_health_list_unhealthy"),
1904 0 : )
1905 0 : })
1906 0 : .post("/control/v1/metadata_health/outdated", |r| {
1907 0 : named_request_span(
1908 0 : r,
1909 0 : handle_metadata_health_list_outdated,
1910 0 : RequestName("control_v1_metadata_health_list_outdated"),
1911 0 : )
1912 0 : })
1913 0 : // Safekeepers
1914 0 : .get("/control/v1/safekeeper", |r| {
1915 0 : named_request_span(
1916 0 : r,
1917 0 : handle_safekeeper_list,
1918 0 : RequestName("control_v1_safekeeper_list"),
1919 0 : )
1920 0 : })
1921 0 : .get("/control/v1/safekeeper/:id", |r| {
1922 0 : named_request_span(r, handle_get_safekeeper, RequestName("v1_safekeeper"))
1923 0 : })
1924 0 : .post("/control/v1/safekeeper/:id", |r| {
1925 0 : // id is in the body
1926 0 : named_request_span(
1927 0 : r,
1928 0 : handle_upsert_safekeeper,
1929 0 : RequestName("v1_safekeeper_post"),
1930 0 : )
1931 0 : })
1932 0 : .post("/control/v1/safekeeper/:id/scheduling_policy", |r| {
1933 0 : named_request_span(
1934 0 : r,
1935 0 : handle_safekeeper_scheduling_policy,
1936 0 : RequestName("v1_safekeeper_status"),
1937 0 : )
1938 0 : })
1939 0 : // Tenant Shard operations
1940 0 : .put("/control/v1/tenant/:tenant_shard_id/migrate", |r| {
1941 0 : tenant_service_handler(
1942 0 : r,
1943 0 : handle_tenant_shard_migrate,
1944 0 : RequestName("control_v1_tenant_migrate"),
1945 0 : )
1946 0 : })
1947 0 : .put(
1948 0 : "/control/v1/tenant/:tenant_shard_id/migrate_secondary",
1949 0 : |r| {
1950 0 : tenant_service_handler(
1951 0 : r,
1952 0 : handle_tenant_shard_migrate_secondary,
1953 0 : RequestName("control_v1_tenant_migrate_secondary"),
1954 0 : )
1955 0 : },
1956 0 : )
1957 0 : .put(
1958 0 : "/control/v1/tenant/:tenant_shard_id/cancel_reconcile",
1959 0 : |r| {
1960 0 : tenant_service_handler(
1961 0 : r,
1962 0 : handle_tenant_shard_cancel_reconcile,
1963 0 : RequestName("control_v1_tenant_cancel_reconcile"),
1964 0 : )
1965 0 : },
1966 0 : )
1967 0 : .put("/control/v1/tenant/:tenant_id/shard_split", |r| {
1968 0 : tenant_service_handler(
1969 0 : r,
1970 0 : handle_tenant_shard_split,
1971 0 : RequestName("control_v1_tenant_shard_split"),
1972 0 : )
1973 0 : })
1974 0 : .get("/control/v1/tenant/:tenant_id", |r| {
1975 0 : tenant_service_handler(
1976 0 : r,
1977 0 : handle_tenant_describe,
1978 0 : RequestName("control_v1_tenant_describe"),
1979 0 : )
1980 0 : })
1981 0 : .get("/control/v1/tenant", |r| {
1982 0 : tenant_service_handler(r, handle_tenant_list, RequestName("control_v1_tenant_list"))
1983 0 : })
1984 0 : .put("/control/v1/tenant/:tenant_id/policy", |r| {
1985 0 : named_request_span(
1986 0 : r,
1987 0 : handle_tenant_update_policy,
1988 0 : RequestName("control_v1_tenant_policy"),
1989 0 : )
1990 0 : })
1991 0 : .put("/control/v1/preferred_azs", |r| {
1992 0 : named_request_span(
1993 0 : r,
1994 0 : handle_update_preferred_azs,
1995 0 : RequestName("control_v1_preferred_azs"),
1996 0 : )
1997 0 : })
1998 0 : .put("/control/v1/step_down", |r| {
1999 0 : named_request_span(r, handle_step_down, RequestName("control_v1_step_down"))
2000 0 : })
2001 0 : // Tenant operations
2002 0 : // The ^/v1/ endpoints act as a "Virtual Pageserver", enabling shard-naive clients to call into
2003 0 : // this service to manage tenants that actually consist of many tenant shards, as if they are a single entity.
2004 0 : .post("/v1/tenant", |r| {
2005 0 : tenant_service_handler(r, handle_tenant_create, RequestName("v1_tenant"))
2006 0 : })
2007 0 : .delete("/v1/tenant/:tenant_id", |r| {
2008 0 : tenant_service_handler(r, handle_tenant_delete, RequestName("v1_tenant"))
2009 0 : })
2010 0 : .patch("/v1/tenant/config", |r| {
2011 0 : tenant_service_handler(
2012 0 : r,
2013 0 : handle_tenant_config_patch,
2014 0 : RequestName("v1_tenant_config"),
2015 0 : )
2016 0 : })
2017 0 : .put("/v1/tenant/config", |r| {
2018 0 : tenant_service_handler(r, handle_tenant_config_set, RequestName("v1_tenant_config"))
2019 0 : })
2020 0 : .get("/v1/tenant/:tenant_id/config", |r| {
2021 0 : tenant_service_handler(r, handle_tenant_config_get, RequestName("v1_tenant_config"))
2022 0 : })
2023 0 : .put("/v1/tenant/:tenant_shard_id/location_config", |r| {
2024 0 : tenant_service_handler(
2025 0 : r,
2026 0 : handle_tenant_location_config,
2027 0 : RequestName("v1_tenant_location_config"),
2028 0 : )
2029 0 : })
2030 0 : .put("/v1/tenant/:tenant_id/time_travel_remote_storage", |r| {
2031 0 : tenant_service_handler(
2032 0 : r,
2033 0 : handle_tenant_time_travel_remote_storage,
2034 0 : RequestName("v1_tenant_time_travel_remote_storage"),
2035 0 : )
2036 0 : })
2037 0 : .post("/v1/tenant/:tenant_id/secondary/download", |r| {
2038 0 : tenant_service_handler(
2039 0 : r,
2040 0 : handle_tenant_secondary_download,
2041 0 : RequestName("v1_tenant_secondary_download"),
2042 0 : )
2043 0 : })
2044 0 : // Timeline operations
2045 0 : .delete("/v1/tenant/:tenant_id/timeline/:timeline_id", |r| {
2046 0 : tenant_service_handler(
2047 0 : r,
2048 0 : handle_tenant_timeline_delete,
2049 0 : RequestName("v1_tenant_timeline"),
2050 0 : )
2051 0 : })
2052 0 : .post("/v1/tenant/:tenant_id/timeline", |r| {
2053 0 : tenant_service_handler(
2054 0 : r,
2055 0 : handle_tenant_timeline_create,
2056 0 : RequestName("v1_tenant_timeline"),
2057 0 : )
2058 0 : })
2059 0 : .put(
2060 0 : "/v1/tenant/:tenant_id/timeline/:timeline_id/archival_config",
2061 0 : |r| {
2062 0 : tenant_service_handler(
2063 0 : r,
2064 0 : handle_tenant_timeline_archival_config,
2065 0 : RequestName("v1_tenant_timeline_archival_config"),
2066 0 : )
2067 0 : },
2068 0 : )
2069 0 : .put(
2070 0 : "/v1/tenant/:tenant_id/timeline/:timeline_id/detach_ancestor",
2071 0 : |r| {
2072 0 : tenant_service_handler(
2073 0 : r,
2074 0 : handle_tenant_timeline_detach_ancestor,
2075 0 : RequestName("v1_tenant_timeline_detach_ancestor"),
2076 0 : )
2077 0 : },
2078 0 : )
2079 0 : .post(
2080 0 : "/v1/tenant/:tenant_id/timeline/:timeline_id/block_gc",
2081 0 : |r| {
2082 0 : tenant_service_handler(
2083 0 : r,
2084 0 : |s, r| handle_tenant_timeline_block_unblock_gc(s, r, BlockUnblock::Block),
2085 0 : RequestName("v1_tenant_timeline_block_unblock_gc"),
2086 0 : )
2087 0 : },
2088 0 : )
2089 0 : .post(
2090 0 : "/v1/tenant/:tenant_id/timeline/:timeline_id/unblock_gc",
2091 0 : |r| {
2092 0 : tenant_service_handler(
2093 0 : r,
2094 0 : |s, r| handle_tenant_timeline_block_unblock_gc(s, r, BlockUnblock::Unblock),
2095 0 : RequestName("v1_tenant_timeline_block_unblock_gc"),
2096 0 : )
2097 0 : },
2098 0 : )
2099 0 : .post(
2100 0 : "/v1/tenant/:tenant_shard_id/timeline/:timeline_id/download_heatmap_layers",
2101 0 : |r| {
2102 0 : tenant_service_handler(
2103 0 : r,
2104 0 : handle_tenant_timeline_download_heatmap_layers,
2105 0 : RequestName("v1_tenant_timeline_download_heatmap_layers"),
2106 0 : )
2107 0 : },
2108 0 : )
2109 0 : // Tenant detail GET passthrough to shard zero:
2110 0 : .get("/v1/tenant/:tenant_id", |r| {
2111 0 : tenant_service_handler(
2112 0 : r,
2113 0 : handle_tenant_timeline_passthrough,
2114 0 : RequestName("v1_tenant_passthrough"),
2115 0 : )
2116 0 : })
2117 0 : // The `*` in the URL is a wildcard: any tenant/timeline GET APIs on the pageserver
2118 0 : // are implicitly exposed here. This must be last in the list to avoid
2119 0 : // taking precedence over other GET methods we might implement by hand.
2120 0 : .get("/v1/tenant/:tenant_id/*", |r| {
2121 0 : tenant_service_handler(
2122 0 : r,
2123 0 : handle_tenant_timeline_passthrough,
2124 0 : RequestName("v1_tenant_passthrough"),
2125 0 : )
2126 0 : })
2127 0 : }
2128 :
2129 : #[cfg(test)]
2130 : mod test {
2131 :
2132 : use super::path_without_ids;
2133 :
2134 : #[test]
2135 1 : fn test_path_without_ids() {
2136 1 : assert_eq!(path_without_ids("/v1/tenant/1a2b3344556677881122334455667788/timeline/AA223344556677881122334455667788"), "/v1/tenant//timeline/");
2137 1 : assert_eq!(path_without_ids("/v1/tenant/1a2b3344556677881122334455667788-0108/timeline/AA223344556677881122334455667788"), "/v1/tenant//timeline/");
2138 1 : assert_eq!(path_without_ids("/v1/tenant/1a2b3344556677881122334455667788-0108/timeline/AA223344556677881122334455667788?parameter=foo"), "/v1/tenant//timeline/");
2139 1 : }
2140 : }
|