Line data Source code
1 : use crate::metrics::{
2 : HttpRequestLatencyLabelGroup, HttpRequestStatusLabelGroup, PageserverRequestLabelGroup,
3 : METRICS_REGISTRY,
4 : };
5 : use crate::persistence::SafekeeperPersistence;
6 : use crate::reconciler::ReconcileError;
7 : use crate::service::{LeadershipStatus, Service, STARTUP_RECONCILE_TIMEOUT};
8 : use anyhow::Context;
9 : use futures::Future;
10 : use hyper::header::CONTENT_TYPE;
11 : use hyper::{Body, Request, Response};
12 : use hyper::{StatusCode, Uri};
13 : use metrics::{BuildInfo, NeonMetrics};
14 : use pageserver_api::controller_api::{
15 : MetadataHealthListOutdatedRequest, MetadataHealthListOutdatedResponse,
16 : MetadataHealthListUnhealthyResponse, MetadataHealthUpdateRequest, MetadataHealthUpdateResponse,
17 : ShardsPreferredAzsRequest, TenantCreateRequest,
18 : };
19 : use pageserver_api::models::{
20 : TenantConfigRequest, TenantLocationConfigRequest, TenantShardSplitRequest,
21 : TenantTimeTravelRequest, TimelineArchivalConfigRequest, TimelineCreateRequest,
22 : };
23 : use pageserver_api::shard::TenantShardId;
24 : use pageserver_client::mgmt_api;
25 : use std::sync::Arc;
26 : use std::time::{Duration, Instant};
27 : use tokio_util::sync::CancellationToken;
28 : use utils::auth::{Scope, SwappableJwtAuth};
29 : use utils::failpoint_support::failpoints_handler;
30 : use utils::http::endpoint::{auth_middleware, check_permission_with, request_span};
31 : use utils::http::request::{must_get_query_param, parse_query_param, parse_request_param};
32 : use utils::id::{TenantId, TimelineId};
33 :
34 : use utils::{
35 : http::{
36 : endpoint::{self},
37 : error::ApiError,
38 : json::{json_request, json_response},
39 : RequestExt, RouterBuilder,
40 : },
41 : id::NodeId,
42 : };
43 :
44 : use pageserver_api::controller_api::{
45 : NodeAvailability, NodeConfigureRequest, NodeRegisterRequest, TenantPolicyRequest,
46 : TenantShardMigrateRequest,
47 : };
48 : use pageserver_api::upcall_api::{ReAttachRequest, ValidateRequest};
49 :
50 : use control_plane::storage_controller::{AttachHookRequest, InspectRequest};
51 :
52 : use routerify::Middleware;
53 :
54 : /// State available to HTTP request handlers
55 : pub struct HttpState {
56 : service: Arc<crate::service::Service>,
57 : auth: Option<Arc<SwappableJwtAuth>>,
58 : neon_metrics: NeonMetrics,
59 : allowlist_routes: Vec<Uri>,
60 : }
61 :
62 : impl HttpState {
63 0 : pub fn new(
64 0 : service: Arc<crate::service::Service>,
65 0 : auth: Option<Arc<SwappableJwtAuth>>,
66 0 : build_info: BuildInfo,
67 0 : ) -> Self {
68 0 : let allowlist_routes = ["/status", "/ready", "/metrics"]
69 0 : .iter()
70 0 : .map(|v| v.parse().unwrap())
71 0 : .collect::<Vec<_>>();
72 0 : Self {
73 0 : service,
74 0 : auth,
75 0 : neon_metrics: NeonMetrics::new(build_info),
76 0 : allowlist_routes,
77 0 : }
78 0 : }
79 : }
80 :
81 : #[inline(always)]
82 0 : fn get_state(request: &Request<Body>) -> &HttpState {
83 0 : request
84 0 : .data::<Arc<HttpState>>()
85 0 : .expect("unknown state type")
86 0 : .as_ref()
87 0 : }
88 :
89 : /// Pageserver calls into this on startup, to learn which tenants it should attach
90 0 : async fn handle_re_attach(mut req: Request<Body>) -> Result<Response<Body>, ApiError> {
91 0 : check_permissions(&req, Scope::GenerationsApi)?;
92 :
93 0 : let reattach_req = json_request::<ReAttachRequest>(&mut req).await?;
94 0 : let state = get_state(&req);
95 0 : json_response(StatusCode::OK, state.service.re_attach(reattach_req).await?)
96 0 : }
97 :
98 : /// Pageserver calls into this before doing deletions, to confirm that it still
99 : /// holds the latest generation for the tenants with deletions enqueued
100 0 : async fn handle_validate(mut req: Request<Body>) -> Result<Response<Body>, ApiError> {
101 0 : check_permissions(&req, Scope::GenerationsApi)?;
102 :
103 0 : let validate_req = json_request::<ValidateRequest>(&mut req).await?;
104 0 : let state = get_state(&req);
105 0 : json_response(StatusCode::OK, state.service.validate(validate_req).await?)
106 0 : }
107 :
108 : /// Call into this before attaching a tenant to a pageserver, to acquire a generation number
109 : /// (in the real control plane this is unnecessary, because the same program is managing
110 : /// generation numbers and doing attachments).
111 0 : async fn handle_attach_hook(mut req: Request<Body>) -> Result<Response<Body>, ApiError> {
112 0 : check_permissions(&req, Scope::Admin)?;
113 :
114 0 : let attach_req = json_request::<AttachHookRequest>(&mut req).await?;
115 0 : let state = get_state(&req);
116 0 :
117 0 : json_response(
118 0 : StatusCode::OK,
119 0 : state
120 0 : .service
121 0 : .attach_hook(attach_req)
122 0 : .await
123 0 : .map_err(ApiError::InternalServerError)?,
124 : )
125 0 : }
126 :
127 0 : async fn handle_inspect(mut req: Request<Body>) -> Result<Response<Body>, ApiError> {
128 0 : check_permissions(&req, Scope::Admin)?;
129 :
130 0 : let inspect_req = json_request::<InspectRequest>(&mut req).await?;
131 :
132 0 : let state = get_state(&req);
133 0 :
134 0 : json_response(StatusCode::OK, state.service.inspect(inspect_req))
135 0 : }
136 :
137 0 : async fn handle_tenant_create(
138 0 : service: Arc<Service>,
139 0 : mut req: Request<Body>,
140 0 : ) -> Result<Response<Body>, ApiError> {
141 0 : check_permissions(&req, Scope::PageServerApi)?;
142 :
143 0 : let create_req = json_request::<TenantCreateRequest>(&mut req).await?;
144 :
145 : json_response(
146 : StatusCode::CREATED,
147 0 : service.tenant_create(create_req).await?,
148 : )
149 0 : }
150 :
151 0 : async fn handle_tenant_location_config(
152 0 : service: Arc<Service>,
153 0 : mut req: Request<Body>,
154 0 : ) -> Result<Response<Body>, ApiError> {
155 0 : let tenant_shard_id: TenantShardId = parse_request_param(&req, "tenant_shard_id")?;
156 0 : check_permissions(&req, Scope::PageServerApi)?;
157 :
158 0 : let config_req = json_request::<TenantLocationConfigRequest>(&mut req).await?;
159 : json_response(
160 : StatusCode::OK,
161 0 : service
162 0 : .tenant_location_config(tenant_shard_id, config_req)
163 0 : .await?,
164 : )
165 0 : }
166 :
167 0 : async fn handle_tenant_config_set(
168 0 : service: Arc<Service>,
169 0 : mut req: Request<Body>,
170 0 : ) -> Result<Response<Body>, ApiError> {
171 0 : check_permissions(&req, Scope::PageServerApi)?;
172 :
173 0 : let config_req = json_request::<TenantConfigRequest>(&mut req).await?;
174 :
175 0 : json_response(StatusCode::OK, service.tenant_config_set(config_req).await?)
176 0 : }
177 :
178 0 : async fn handle_tenant_config_get(
179 0 : service: Arc<Service>,
180 0 : req: Request<Body>,
181 0 : ) -> Result<Response<Body>, ApiError> {
182 0 : let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
183 0 : check_permissions(&req, Scope::PageServerApi)?;
184 :
185 0 : json_response(StatusCode::OK, service.tenant_config_get(tenant_id)?)
186 0 : }
187 :
188 0 : async fn handle_tenant_time_travel_remote_storage(
189 0 : service: Arc<Service>,
190 0 : mut req: Request<Body>,
191 0 : ) -> Result<Response<Body>, ApiError> {
192 0 : let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
193 0 : check_permissions(&req, Scope::PageServerApi)?;
194 :
195 0 : let time_travel_req = json_request::<TenantTimeTravelRequest>(&mut req).await?;
196 :
197 0 : let timestamp_raw = must_get_query_param(&req, "travel_to")?;
198 0 : let _timestamp = humantime::parse_rfc3339(×tamp_raw).map_err(|_e| {
199 0 : ApiError::BadRequest(anyhow::anyhow!(
200 0 : "Invalid time for travel_to: {timestamp_raw:?}"
201 0 : ))
202 0 : })?;
203 :
204 0 : let done_if_after_raw = must_get_query_param(&req, "done_if_after")?;
205 0 : let _done_if_after = humantime::parse_rfc3339(&done_if_after_raw).map_err(|_e| {
206 0 : ApiError::BadRequest(anyhow::anyhow!(
207 0 : "Invalid time for done_if_after: {done_if_after_raw:?}"
208 0 : ))
209 0 : })?;
210 :
211 0 : service
212 0 : .tenant_time_travel_remote_storage(
213 0 : &time_travel_req,
214 0 : tenant_id,
215 0 : timestamp_raw,
216 0 : done_if_after_raw,
217 0 : )
218 0 : .await?;
219 0 : json_response(StatusCode::OK, ())
220 0 : }
221 :
222 0 : fn map_reqwest_hyper_status(status: reqwest::StatusCode) -> Result<hyper::StatusCode, ApiError> {
223 0 : hyper::StatusCode::from_u16(status.as_u16())
224 0 : .context("invalid status code")
225 0 : .map_err(ApiError::InternalServerError)
226 0 : }
227 :
228 0 : async fn handle_tenant_secondary_download(
229 0 : service: Arc<Service>,
230 0 : req: Request<Body>,
231 0 : ) -> Result<Response<Body>, ApiError> {
232 0 : let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
233 0 : let wait = parse_query_param(&req, "wait_ms")?.map(Duration::from_millis);
234 :
235 0 : let (status, progress) = service.tenant_secondary_download(tenant_id, wait).await?;
236 0 : json_response(map_reqwest_hyper_status(status)?, progress)
237 0 : }
238 :
239 0 : async fn handle_tenant_delete(
240 0 : service: Arc<Service>,
241 0 : req: Request<Body>,
242 0 : ) -> Result<Response<Body>, ApiError> {
243 0 : let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
244 0 : check_permissions(&req, Scope::PageServerApi)?;
245 :
246 0 : let status_code = service
247 0 : .tenant_delete(tenant_id)
248 0 : .await
249 0 : .and_then(map_reqwest_hyper_status)?;
250 :
251 0 : if status_code == StatusCode::NOT_FOUND {
252 : // The pageserver uses 404 for successful deletion, but we use 200
253 0 : json_response(StatusCode::OK, ())
254 : } else {
255 0 : json_response(status_code, ())
256 : }
257 0 : }
258 :
259 0 : async fn handle_tenant_timeline_create(
260 0 : service: Arc<Service>,
261 0 : mut req: Request<Body>,
262 0 : ) -> Result<Response<Body>, ApiError> {
263 0 : let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
264 0 : check_permissions(&req, Scope::PageServerApi)?;
265 :
266 0 : let create_req = json_request::<TimelineCreateRequest>(&mut req).await?;
267 : json_response(
268 : StatusCode::CREATED,
269 0 : service
270 0 : .tenant_timeline_create(tenant_id, create_req)
271 0 : .await?,
272 : )
273 0 : }
274 :
275 0 : async fn handle_tenant_timeline_delete(
276 0 : service: Arc<Service>,
277 0 : req: Request<Body>,
278 0 : ) -> Result<Response<Body>, ApiError> {
279 0 : let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
280 0 : check_permissions(&req, Scope::PageServerApi)?;
281 :
282 0 : let timeline_id: TimelineId = parse_request_param(&req, "timeline_id")?;
283 :
284 : // For timeline deletions, which both implement an "initially return 202, then 404 once
285 : // we're done" semantic, we wrap with a retry loop to expose a simpler API upstream.
286 0 : async fn deletion_wrapper<R, F>(service: Arc<Service>, f: F) -> Result<Response<Body>, ApiError>
287 0 : where
288 0 : R: std::future::Future<Output = Result<StatusCode, ApiError>> + Send + 'static,
289 0 : F: Fn(Arc<Service>) -> R + Send + Sync + 'static,
290 0 : {
291 0 : let started_at = Instant::now();
292 0 : // To keep deletion reasonably snappy for small tenants, initially check after 1 second if deletion
293 0 : // completed.
294 0 : let mut retry_period = Duration::from_secs(1);
295 0 : // On subsequent retries, wait longer.
296 0 : let max_retry_period = Duration::from_secs(5);
297 0 : // Enable callers with a 30 second request timeout to reliably get a response
298 0 : let max_wait = Duration::from_secs(25);
299 :
300 : loop {
301 0 : let status = f(service.clone()).await?;
302 0 : match status {
303 : StatusCode::ACCEPTED => {
304 0 : tracing::info!("Deletion accepted, waiting to try again...");
305 0 : tokio::time::sleep(retry_period).await;
306 0 : retry_period = max_retry_period;
307 : }
308 : StatusCode::NOT_FOUND => {
309 0 : tracing::info!("Deletion complete");
310 0 : return json_response(StatusCode::OK, ());
311 : }
312 : _ => {
313 0 : tracing::warn!("Unexpected status {status}");
314 0 : return json_response(status, ());
315 : }
316 : }
317 :
318 0 : let now = Instant::now();
319 0 : if now + retry_period > started_at + max_wait {
320 0 : tracing::info!("Deletion timed out waiting for 404");
321 : // REQUEST_TIMEOUT would be more appropriate, but CONFLICT is already part of
322 : // the pageserver's swagger definition for this endpoint, and has the same desired
323 : // effect of causing the control plane to retry later.
324 0 : return json_response(StatusCode::CONFLICT, ());
325 0 : }
326 : }
327 0 : }
328 :
329 0 : deletion_wrapper(service, move |service| async move {
330 0 : service
331 0 : .tenant_timeline_delete(tenant_id, timeline_id)
332 0 : .await
333 0 : .and_then(map_reqwest_hyper_status)
334 0 : })
335 0 : .await
336 0 : }
337 :
338 0 : async fn handle_tenant_timeline_archival_config(
339 0 : service: Arc<Service>,
340 0 : mut req: Request<Body>,
341 0 : ) -> Result<Response<Body>, ApiError> {
342 0 : let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
343 0 : check_permissions(&req, Scope::PageServerApi)?;
344 :
345 0 : let timeline_id: TimelineId = parse_request_param(&req, "timeline_id")?;
346 :
347 0 : let create_req = json_request::<TimelineArchivalConfigRequest>(&mut req).await?;
348 :
349 0 : service
350 0 : .tenant_timeline_archival_config(tenant_id, timeline_id, create_req)
351 0 : .await?;
352 :
353 0 : json_response(StatusCode::OK, ())
354 0 : }
355 :
356 0 : async fn handle_tenant_timeline_detach_ancestor(
357 0 : service: Arc<Service>,
358 0 : req: Request<Body>,
359 0 : ) -> Result<Response<Body>, ApiError> {
360 0 : let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
361 0 : check_permissions(&req, Scope::PageServerApi)?;
362 :
363 0 : let timeline_id: TimelineId = parse_request_param(&req, "timeline_id")?;
364 :
365 0 : let res = service
366 0 : .tenant_timeline_detach_ancestor(tenant_id, timeline_id)
367 0 : .await?;
368 :
369 0 : json_response(StatusCode::OK, res)
370 0 : }
371 :
372 0 : async fn handle_tenant_timeline_passthrough(
373 0 : service: Arc<Service>,
374 0 : req: Request<Body>,
375 0 : ) -> Result<Response<Body>, ApiError> {
376 0 : let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
377 0 : check_permissions(&req, Scope::PageServerApi)?;
378 :
379 0 : let Some(path) = req.uri().path_and_query() else {
380 : // This should never happen, our request router only calls us if there is a path
381 0 : return Err(ApiError::BadRequest(anyhow::anyhow!("Missing path")));
382 : };
383 :
384 0 : tracing::info!("Proxying request for tenant {} ({})", tenant_id, path);
385 :
386 : // Find the node that holds shard zero
387 0 : let (node, tenant_shard_id) = service.tenant_shard0_node(tenant_id)?;
388 :
389 : // Callers will always pass an unsharded tenant ID. Before proxying, we must
390 : // rewrite this to a shard-aware shard zero ID.
391 0 : let path = format!("{}", path);
392 0 : let tenant_str = tenant_id.to_string();
393 0 : let tenant_shard_str = format!("{}", tenant_shard_id);
394 0 : let path = path.replace(&tenant_str, &tenant_shard_str);
395 0 :
396 0 : let latency = &METRICS_REGISTRY
397 0 : .metrics_group
398 0 : .storage_controller_passthrough_request_latency;
399 0 :
400 0 : // This is a bit awkward. We remove the param from the request
401 0 : // and join the words by '_' to get a label for the request.
402 0 : let just_path = path.replace(&tenant_shard_str, "");
403 0 : let path_label = just_path
404 0 : .split('/')
405 0 : .filter(|token| !token.is_empty())
406 0 : .collect::<Vec<_>>()
407 0 : .join("_");
408 0 : let labels = PageserverRequestLabelGroup {
409 0 : pageserver_id: &node.get_id().to_string(),
410 0 : path: &path_label,
411 0 : method: crate::metrics::Method::Get,
412 0 : };
413 0 :
414 0 : let _timer = latency.start_timer(labels.clone());
415 0 :
416 0 : let client = mgmt_api::Client::new(node.base_url(), service.get_config().jwt_token.as_deref());
417 0 : let resp = client.get_raw(path).await.map_err(|_e|
418 : // FIXME: give APiError a proper Unavailable variant. We return 503 here because
419 : // if we can't successfully send a request to the pageserver, we aren't available.
420 0 : ApiError::ShuttingDown)?;
421 :
422 0 : if !resp.status().is_success() {
423 0 : let error_counter = &METRICS_REGISTRY
424 0 : .metrics_group
425 0 : .storage_controller_passthrough_request_error;
426 0 : error_counter.inc(labels);
427 0 : }
428 :
429 : // We have a reqest::Response, would like a http::Response
430 0 : let mut builder = hyper::Response::builder().status(map_reqwest_hyper_status(resp.status())?);
431 0 : for (k, v) in resp.headers() {
432 0 : builder = builder.header(k.as_str(), v.as_bytes());
433 0 : }
434 :
435 0 : let response = builder
436 0 : .body(Body::wrap_stream(resp.bytes_stream()))
437 0 : .map_err(|e| ApiError::InternalServerError(e.into()))?;
438 :
439 0 : Ok(response)
440 0 : }
441 :
442 0 : async fn handle_tenant_locate(
443 0 : service: Arc<Service>,
444 0 : req: Request<Body>,
445 0 : ) -> Result<Response<Body>, ApiError> {
446 0 : check_permissions(&req, Scope::Admin)?;
447 :
448 0 : let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
449 0 : json_response(StatusCode::OK, service.tenant_locate(tenant_id)?)
450 0 : }
451 :
452 0 : async fn handle_tenant_describe(
453 0 : service: Arc<Service>,
454 0 : req: Request<Body>,
455 0 : ) -> Result<Response<Body>, ApiError> {
456 0 : check_permissions(&req, Scope::Scrubber)?;
457 :
458 0 : let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
459 0 : json_response(StatusCode::OK, service.tenant_describe(tenant_id)?)
460 0 : }
461 :
462 0 : async fn handle_tenant_list(
463 0 : service: Arc<Service>,
464 0 : req: Request<Body>,
465 0 : ) -> Result<Response<Body>, ApiError> {
466 0 : check_permissions(&req, Scope::Admin)?;
467 :
468 0 : json_response(StatusCode::OK, service.tenant_list())
469 0 : }
470 :
471 0 : async fn handle_node_register(mut req: Request<Body>) -> Result<Response<Body>, ApiError> {
472 0 : check_permissions(&req, Scope::Admin)?;
473 :
474 0 : let register_req = json_request::<NodeRegisterRequest>(&mut req).await?;
475 0 : let state = get_state(&req);
476 0 : state.service.node_register(register_req).await?;
477 0 : json_response(StatusCode::OK, ())
478 0 : }
479 :
480 0 : async fn handle_node_list(req: Request<Body>) -> Result<Response<Body>, ApiError> {
481 0 : check_permissions(&req, Scope::Admin)?;
482 :
483 0 : let state = get_state(&req);
484 0 : let nodes = state.service.node_list().await?;
485 0 : let api_nodes = nodes.into_iter().map(|n| n.describe()).collect::<Vec<_>>();
486 0 :
487 0 : json_response(StatusCode::OK, api_nodes)
488 0 : }
489 :
490 0 : async fn handle_node_drop(req: Request<Body>) -> Result<Response<Body>, ApiError> {
491 0 : check_permissions(&req, Scope::Admin)?;
492 :
493 0 : let state = get_state(&req);
494 0 : let node_id: NodeId = parse_request_param(&req, "node_id")?;
495 0 : json_response(StatusCode::OK, state.service.node_drop(node_id).await?)
496 0 : }
497 :
498 0 : async fn handle_node_delete(req: Request<Body>) -> Result<Response<Body>, ApiError> {
499 0 : check_permissions(&req, Scope::Admin)?;
500 :
501 0 : let state = get_state(&req);
502 0 : let node_id: NodeId = parse_request_param(&req, "node_id")?;
503 0 : json_response(StatusCode::OK, state.service.node_delete(node_id).await?)
504 0 : }
505 :
506 0 : async fn handle_node_configure(mut req: Request<Body>) -> Result<Response<Body>, ApiError> {
507 0 : check_permissions(&req, Scope::Admin)?;
508 :
509 0 : let node_id: NodeId = parse_request_param(&req, "node_id")?;
510 0 : let config_req = json_request::<NodeConfigureRequest>(&mut req).await?;
511 0 : if node_id != config_req.node_id {
512 0 : return Err(ApiError::BadRequest(anyhow::anyhow!(
513 0 : "Path and body node_id differ"
514 0 : )));
515 0 : }
516 0 : let state = get_state(&req);
517 0 :
518 0 : json_response(
519 0 : StatusCode::OK,
520 0 : state
521 0 : .service
522 0 : .external_node_configure(
523 0 : config_req.node_id,
524 0 : config_req.availability.map(NodeAvailability::from),
525 0 : config_req.scheduling,
526 0 : )
527 0 : .await?,
528 : )
529 0 : }
530 :
531 0 : async fn handle_node_status(req: Request<Body>) -> Result<Response<Body>, ApiError> {
532 0 : check_permissions(&req, Scope::Admin)?;
533 :
534 0 : let state = get_state(&req);
535 0 : let node_id: NodeId = parse_request_param(&req, "node_id")?;
536 :
537 0 : let node_status = state.service.get_node(node_id).await?;
538 :
539 0 : json_response(StatusCode::OK, node_status)
540 0 : }
541 :
542 0 : async fn handle_get_leader(req: Request<Body>) -> Result<Response<Body>, ApiError> {
543 0 : check_permissions(&req, Scope::Admin)?;
544 :
545 0 : let state = get_state(&req);
546 0 : let leader = state.service.get_leader().await.map_err(|err| {
547 0 : ApiError::InternalServerError(anyhow::anyhow!(
548 0 : "Failed to read leader from database: {err}"
549 0 : ))
550 0 : })?;
551 :
552 0 : json_response(StatusCode::OK, leader)
553 0 : }
554 :
555 0 : async fn handle_node_drain(req: Request<Body>) -> Result<Response<Body>, ApiError> {
556 0 : check_permissions(&req, Scope::Admin)?;
557 :
558 0 : let state = get_state(&req);
559 0 : let node_id: NodeId = parse_request_param(&req, "node_id")?;
560 :
561 0 : state.service.start_node_drain(node_id).await?;
562 :
563 0 : json_response(StatusCode::ACCEPTED, ())
564 0 : }
565 :
566 0 : async fn handle_cancel_node_drain(req: Request<Body>) -> Result<Response<Body>, ApiError> {
567 0 : check_permissions(&req, Scope::Admin)?;
568 :
569 0 : let state = get_state(&req);
570 0 : let node_id: NodeId = parse_request_param(&req, "node_id")?;
571 :
572 0 : state.service.cancel_node_drain(node_id).await?;
573 :
574 0 : json_response(StatusCode::ACCEPTED, ())
575 0 : }
576 :
577 0 : async fn handle_node_fill(req: Request<Body>) -> Result<Response<Body>, ApiError> {
578 0 : check_permissions(&req, Scope::Admin)?;
579 :
580 0 : let state = get_state(&req);
581 0 : let node_id: NodeId = parse_request_param(&req, "node_id")?;
582 :
583 0 : state.service.start_node_fill(node_id).await?;
584 :
585 0 : json_response(StatusCode::ACCEPTED, ())
586 0 : }
587 :
588 0 : async fn handle_cancel_node_fill(req: Request<Body>) -> Result<Response<Body>, ApiError> {
589 0 : check_permissions(&req, Scope::Admin)?;
590 :
591 0 : let state = get_state(&req);
592 0 : let node_id: NodeId = parse_request_param(&req, "node_id")?;
593 :
594 0 : state.service.cancel_node_fill(node_id).await?;
595 :
596 0 : json_response(StatusCode::ACCEPTED, ())
597 0 : }
598 :
599 0 : async fn handle_metadata_health_update(mut req: Request<Body>) -> Result<Response<Body>, ApiError> {
600 0 : check_permissions(&req, Scope::Scrubber)?;
601 :
602 0 : let update_req = json_request::<MetadataHealthUpdateRequest>(&mut req).await?;
603 0 : let state = get_state(&req);
604 0 :
605 0 : state.service.metadata_health_update(update_req).await?;
606 :
607 0 : json_response(StatusCode::OK, MetadataHealthUpdateResponse {})
608 0 : }
609 :
610 0 : async fn handle_metadata_health_list_unhealthy(
611 0 : req: Request<Body>,
612 0 : ) -> Result<Response<Body>, ApiError> {
613 0 : check_permissions(&req, Scope::Admin)?;
614 :
615 0 : let state = get_state(&req);
616 0 : let unhealthy_tenant_shards = state.service.metadata_health_list_unhealthy().await?;
617 :
618 0 : json_response(
619 0 : StatusCode::OK,
620 0 : MetadataHealthListUnhealthyResponse {
621 0 : unhealthy_tenant_shards,
622 0 : },
623 0 : )
624 0 : }
625 :
626 0 : async fn handle_metadata_health_list_outdated(
627 0 : mut req: Request<Body>,
628 0 : ) -> Result<Response<Body>, ApiError> {
629 0 : check_permissions(&req, Scope::Admin)?;
630 :
631 0 : let list_outdated_req = json_request::<MetadataHealthListOutdatedRequest>(&mut req).await?;
632 0 : let state = get_state(&req);
633 0 : let health_records = state
634 0 : .service
635 0 : .metadata_health_list_outdated(list_outdated_req.not_scrubbed_for)
636 0 : .await?;
637 :
638 0 : json_response(
639 0 : StatusCode::OK,
640 0 : MetadataHealthListOutdatedResponse { health_records },
641 0 : )
642 0 : }
643 :
644 0 : async fn handle_tenant_shard_split(
645 0 : service: Arc<Service>,
646 0 : mut req: Request<Body>,
647 0 : ) -> Result<Response<Body>, ApiError> {
648 0 : check_permissions(&req, Scope::Admin)?;
649 :
650 0 : let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
651 0 : let split_req = json_request::<TenantShardSplitRequest>(&mut req).await?;
652 :
653 : json_response(
654 : StatusCode::OK,
655 0 : service.tenant_shard_split(tenant_id, split_req).await?,
656 : )
657 0 : }
658 :
659 0 : async fn handle_tenant_shard_migrate(
660 0 : service: Arc<Service>,
661 0 : mut req: Request<Body>,
662 0 : ) -> Result<Response<Body>, ApiError> {
663 0 : check_permissions(&req, Scope::Admin)?;
664 :
665 0 : let tenant_shard_id: TenantShardId = parse_request_param(&req, "tenant_shard_id")?;
666 0 : let migrate_req = json_request::<TenantShardMigrateRequest>(&mut req).await?;
667 : json_response(
668 : StatusCode::OK,
669 0 : service
670 0 : .tenant_shard_migrate(tenant_shard_id, migrate_req)
671 0 : .await?,
672 : )
673 0 : }
674 :
675 0 : async fn handle_tenant_update_policy(mut req: Request<Body>) -> Result<Response<Body>, ApiError> {
676 0 : check_permissions(&req, Scope::Admin)?;
677 :
678 0 : let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
679 0 : let update_req = json_request::<TenantPolicyRequest>(&mut req).await?;
680 0 : let state = get_state(&req);
681 0 :
682 0 : json_response(
683 0 : StatusCode::OK,
684 0 : state
685 0 : .service
686 0 : .tenant_update_policy(tenant_id, update_req)
687 0 : .await?,
688 : )
689 0 : }
690 :
691 0 : async fn handle_update_preferred_azs(mut req: Request<Body>) -> Result<Response<Body>, ApiError> {
692 0 : check_permissions(&req, Scope::Admin)?;
693 :
694 0 : let azs_req = json_request::<ShardsPreferredAzsRequest>(&mut req).await?;
695 0 : let state = get_state(&req);
696 0 :
697 0 : json_response(
698 0 : StatusCode::OK,
699 0 : state.service.update_shards_preferred_azs(azs_req).await?,
700 : )
701 0 : }
702 :
703 0 : async fn handle_step_down(req: Request<Body>) -> Result<Response<Body>, ApiError> {
704 0 : check_permissions(&req, Scope::Admin)?;
705 :
706 0 : let state = get_state(&req);
707 0 : json_response(StatusCode::OK, state.service.step_down().await)
708 0 : }
709 :
710 0 : async fn handle_tenant_drop(req: Request<Body>) -> Result<Response<Body>, ApiError> {
711 0 : let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
712 0 : check_permissions(&req, Scope::PageServerApi)?;
713 :
714 0 : let state = get_state(&req);
715 0 :
716 0 : json_response(StatusCode::OK, state.service.tenant_drop(tenant_id).await?)
717 0 : }
718 :
719 0 : async fn handle_tenant_import(req: Request<Body>) -> Result<Response<Body>, ApiError> {
720 0 : let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
721 0 : check_permissions(&req, Scope::PageServerApi)?;
722 :
723 0 : let state = get_state(&req);
724 0 :
725 0 : json_response(
726 0 : StatusCode::OK,
727 0 : state.service.tenant_import(tenant_id).await?,
728 : )
729 0 : }
730 :
731 0 : async fn handle_tenants_dump(req: Request<Body>) -> Result<Response<Body>, ApiError> {
732 0 : check_permissions(&req, Scope::Admin)?;
733 :
734 0 : let state = get_state(&req);
735 0 : state.service.tenants_dump()
736 0 : }
737 :
738 0 : async fn handle_scheduler_dump(req: Request<Body>) -> Result<Response<Body>, ApiError> {
739 0 : check_permissions(&req, Scope::Admin)?;
740 :
741 0 : let state = get_state(&req);
742 0 : state.service.scheduler_dump()
743 0 : }
744 :
745 0 : async fn handle_consistency_check(req: Request<Body>) -> Result<Response<Body>, ApiError> {
746 0 : check_permissions(&req, Scope::Admin)?;
747 :
748 0 : let state = get_state(&req);
749 0 :
750 0 : json_response(StatusCode::OK, state.service.consistency_check().await?)
751 0 : }
752 :
753 0 : async fn handle_reconcile_all(req: Request<Body>) -> Result<Response<Body>, ApiError> {
754 0 : check_permissions(&req, Scope::Admin)?;
755 :
756 0 : let state = get_state(&req);
757 0 :
758 0 : json_response(StatusCode::OK, state.service.reconcile_all_now().await?)
759 0 : }
760 :
761 : /// Status endpoint is just used for checking that our HTTP listener is up
762 0 : async fn handle_status(_req: Request<Body>) -> Result<Response<Body>, ApiError> {
763 0 : json_response(StatusCode::OK, ())
764 0 : }
765 :
766 : /// Readiness endpoint indicates when we're done doing startup I/O (e.g. reconciling
767 : /// with remote pageserver nodes). This is intended for use as a kubernetes readiness probe.
768 0 : async fn handle_ready(req: Request<Body>) -> Result<Response<Body>, ApiError> {
769 0 : let state = get_state(&req);
770 0 : if state.service.startup_complete.is_ready() {
771 0 : json_response(StatusCode::OK, ())
772 : } else {
773 0 : json_response(StatusCode::SERVICE_UNAVAILABLE, ())
774 : }
775 0 : }
776 :
777 : impl From<ReconcileError> for ApiError {
778 0 : fn from(value: ReconcileError) -> Self {
779 0 : ApiError::Conflict(format!("Reconciliation error: {}", value))
780 0 : }
781 : }
782 :
783 : /// Return the safekeeper record by instance id, or 404.
784 : ///
785 : /// Not used by anything except manual testing.
786 0 : async fn handle_get_safekeeper(req: Request<Body>) -> Result<Response<Body>, ApiError> {
787 0 : check_permissions(&req, Scope::Admin)?;
788 :
789 0 : let id = parse_request_param::<i64>(&req, "id")?;
790 :
791 0 : let state = get_state(&req);
792 :
793 0 : let res = state.service.get_safekeeper(id).await;
794 :
795 0 : match res {
796 0 : Ok(b) => json_response(StatusCode::OK, b),
797 : Err(crate::persistence::DatabaseError::Query(diesel::result::Error::NotFound)) => {
798 0 : Err(ApiError::NotFound("unknown instance_id".into()))
799 : }
800 0 : Err(other) => Err(other.into()),
801 : }
802 0 : }
803 :
804 : /// Used as part of deployment scripts.
805 : ///
806 : /// Assumes information is only relayed to storage controller after first selecting an unique id on
807 : /// control plane database, which means we have an id field in the request and payload.
808 0 : async fn handle_upsert_safekeeper(mut req: Request<Body>) -> Result<Response<Body>, ApiError> {
809 0 : check_permissions(&req, Scope::Admin)?;
810 :
811 0 : let body = json_request::<SafekeeperPersistence>(&mut req).await?;
812 0 : let id = parse_request_param::<i64>(&req, "id")?;
813 :
814 0 : if id != body.id {
815 : // it should be repeated
816 0 : return Err(ApiError::BadRequest(anyhow::anyhow!(
817 0 : "id mismatch: url={id:?}, body={:?}",
818 0 : body.id
819 0 : )));
820 0 : }
821 0 :
822 0 : let state = get_state(&req);
823 0 :
824 0 : state.service.upsert_safekeeper(body).await?;
825 :
826 0 : Ok(Response::builder()
827 0 : .status(StatusCode::NO_CONTENT)
828 0 : .body(Body::empty())
829 0 : .unwrap())
830 0 : }
831 :
832 : /// Common wrapper for request handlers that call into Service and will operate on tenants: they must only
833 : /// be allowed to run if Service has finished its initial reconciliation.
834 0 : async fn tenant_service_handler<R, H>(
835 0 : request: Request<Body>,
836 0 : handler: H,
837 0 : request_name: RequestName,
838 0 : ) -> R::Output
839 0 : where
840 0 : R: std::future::Future<Output = Result<Response<Body>, ApiError>> + Send + 'static,
841 0 : H: FnOnce(Arc<Service>, Request<Body>) -> R + Send + Sync + 'static,
842 0 : {
843 0 : let state = get_state(&request);
844 0 : let service = state.service.clone();
845 0 :
846 0 : let startup_complete = service.startup_complete.clone();
847 0 : if tokio::time::timeout(STARTUP_RECONCILE_TIMEOUT, startup_complete.wait())
848 0 : .await
849 0 : .is_err()
850 : {
851 : // This shouldn't happen: it is the responsibilty of [`Service::startup_reconcile`] to use appropriate
852 : // timeouts around its remote calls, to bound its runtime.
853 0 : return Err(ApiError::Timeout(
854 0 : "Timed out waiting for service readiness".into(),
855 0 : ));
856 0 : }
857 0 :
858 0 : named_request_span(
859 0 : request,
860 0 : |request| async move { handler(service, request).await },
861 0 : request_name,
862 0 : )
863 0 : .await
864 0 : }
865 :
866 : /// Check if the required scope is held in the request's token, or if the request has
867 : /// a token with 'admin' scope then always permit it.
868 0 : fn check_permissions(request: &Request<Body>, required_scope: Scope) -> Result<(), ApiError> {
869 0 : check_permission_with(request, |claims| {
870 0 : match crate::auth::check_permission(claims, required_scope) {
871 0 : Err(e) => match crate::auth::check_permission(claims, Scope::Admin) {
872 0 : Ok(()) => Ok(()),
873 0 : Err(_) => Err(e),
874 : },
875 0 : Ok(()) => Ok(()),
876 : }
877 0 : })
878 0 : }
879 :
880 : #[derive(Clone, Debug)]
881 : struct RequestMeta {
882 : method: hyper::http::Method,
883 : at: Instant,
884 : }
885 :
886 0 : pub fn prologue_leadership_status_check_middleware<
887 0 : B: hyper::body::HttpBody + Send + Sync + 'static,
888 0 : >() -> Middleware<B, ApiError> {
889 0 : Middleware::pre(move |req| async move {
890 0 : let state = get_state(&req);
891 0 : let leadership_status = state.service.get_leadership_status();
892 :
893 : enum AllowedRoutes<'a> {
894 : All,
895 : Some(Vec<&'a str>),
896 : }
897 :
898 0 : let allowed_routes = match leadership_status {
899 0 : LeadershipStatus::Leader => AllowedRoutes::All,
900 : LeadershipStatus::SteppedDown => {
901 : // TODO: does it make sense to allow /status here?
902 0 : AllowedRoutes::Some(["/control/v1/step_down", "/status", "/metrics"].to_vec())
903 : }
904 : LeadershipStatus::Candidate => {
905 0 : AllowedRoutes::Some(["/ready", "/status", "/metrics"].to_vec())
906 : }
907 : };
908 :
909 0 : let uri = req.uri().to_string();
910 0 : match allowed_routes {
911 0 : AllowedRoutes::All => Ok(req),
912 0 : AllowedRoutes::Some(allowed) if allowed.contains(&uri.as_str()) => Ok(req),
913 : _ => {
914 0 : tracing::info!(
915 0 : "Request {} not allowed due to current leadership state",
916 0 : req.uri()
917 : );
918 :
919 0 : Err(ApiError::ResourceUnavailable(
920 0 : format!("Current leadership status is {leadership_status}").into(),
921 0 : ))
922 : }
923 : }
924 0 : })
925 0 : }
926 :
927 0 : fn prologue_metrics_middleware<B: hyper::body::HttpBody + Send + Sync + 'static>(
928 0 : ) -> Middleware<B, ApiError> {
929 0 : Middleware::pre(move |req| async move {
930 0 : let meta = RequestMeta {
931 0 : method: req.method().clone(),
932 0 : at: Instant::now(),
933 0 : };
934 0 :
935 0 : req.set_context(meta);
936 0 :
937 0 : Ok(req)
938 0 : })
939 0 : }
940 :
941 0 : fn epilogue_metrics_middleware<B: hyper::body::HttpBody + Send + Sync + 'static>(
942 0 : ) -> Middleware<B, ApiError> {
943 0 : Middleware::post_with_info(move |resp, req_info| async move {
944 0 : let request_name = match req_info.context::<RequestName>() {
945 0 : Some(name) => name,
946 : None => {
947 0 : return Ok(resp);
948 : }
949 : };
950 :
951 0 : if let Some(meta) = req_info.context::<RequestMeta>() {
952 0 : let status = &crate::metrics::METRICS_REGISTRY
953 0 : .metrics_group
954 0 : .storage_controller_http_request_status;
955 0 : let latency = &crate::metrics::METRICS_REGISTRY
956 0 : .metrics_group
957 0 : .storage_controller_http_request_latency;
958 0 :
959 0 : status.inc(HttpRequestStatusLabelGroup {
960 0 : path: request_name.0,
961 0 : method: meta.method.clone().into(),
962 0 : status: crate::metrics::StatusCode(resp.status()),
963 0 : });
964 0 :
965 0 : latency.observe(
966 0 : HttpRequestLatencyLabelGroup {
967 0 : path: request_name.0,
968 0 : method: meta.method.into(),
969 0 : },
970 0 : meta.at.elapsed().as_secs_f64(),
971 0 : );
972 0 : }
973 0 : Ok(resp)
974 0 : })
975 0 : }
976 :
977 0 : pub async fn measured_metrics_handler(req: Request<Body>) -> Result<Response<Body>, ApiError> {
978 : pub const TEXT_FORMAT: &str = "text/plain; version=0.0.4";
979 :
980 0 : let state = get_state(&req);
981 0 : let payload = crate::metrics::METRICS_REGISTRY.encode(&state.neon_metrics);
982 0 : let response = Response::builder()
983 0 : .status(200)
984 0 : .header(CONTENT_TYPE, TEXT_FORMAT)
985 0 : .body(payload.into())
986 0 : .unwrap();
987 0 :
988 0 : Ok(response)
989 0 : }
990 :
991 : #[derive(Clone)]
992 : struct RequestName(&'static str);
993 :
994 0 : async fn named_request_span<R, H>(
995 0 : request: Request<Body>,
996 0 : handler: H,
997 0 : name: RequestName,
998 0 : ) -> R::Output
999 0 : where
1000 0 : R: Future<Output = Result<Response<Body>, ApiError>> + Send + 'static,
1001 0 : H: FnOnce(Request<Body>) -> R + Send + Sync + 'static,
1002 0 : {
1003 0 : request.set_context(name);
1004 0 : request_span(request, handler).await
1005 0 : }
1006 :
1007 0 : pub fn make_router(
1008 0 : service: Arc<Service>,
1009 0 : auth: Option<Arc<SwappableJwtAuth>>,
1010 0 : build_info: BuildInfo,
1011 0 : ) -> RouterBuilder<hyper::Body, ApiError> {
1012 0 : let mut router = endpoint::make_router()
1013 0 : .middleware(prologue_leadership_status_check_middleware())
1014 0 : .middleware(prologue_metrics_middleware())
1015 0 : .middleware(epilogue_metrics_middleware());
1016 0 : if auth.is_some() {
1017 0 : router = router.middleware(auth_middleware(|request| {
1018 0 : let state = get_state(request);
1019 0 : if state.allowlist_routes.contains(request.uri()) {
1020 0 : None
1021 : } else {
1022 0 : state.auth.as_deref()
1023 : }
1024 0 : }));
1025 0 : }
1026 :
1027 0 : router
1028 0 : .data(Arc::new(HttpState::new(service, auth, build_info)))
1029 0 : .get("/metrics", |r| {
1030 0 : named_request_span(r, measured_metrics_handler, RequestName("metrics"))
1031 0 : })
1032 0 : // Non-prefixed generic endpoints (status, metrics)
1033 0 : .get("/status", |r| {
1034 0 : named_request_span(r, handle_status, RequestName("status"))
1035 0 : })
1036 0 : .get("/ready", |r| {
1037 0 : named_request_span(r, handle_ready, RequestName("ready"))
1038 0 : })
1039 0 : // Upcalls for the pageserver: point the pageserver's `control_plane_api` config to this prefix
1040 0 : .post("/upcall/v1/re-attach", |r| {
1041 0 : named_request_span(r, handle_re_attach, RequestName("upcall_v1_reattach"))
1042 0 : })
1043 0 : .post("/upcall/v1/validate", |r| {
1044 0 : named_request_span(r, handle_validate, RequestName("upcall_v1_validate"))
1045 0 : })
1046 0 : // Test/dev/debug endpoints
1047 0 : .post("/debug/v1/attach-hook", |r| {
1048 0 : named_request_span(r, handle_attach_hook, RequestName("debug_v1_attach_hook"))
1049 0 : })
1050 0 : .post("/debug/v1/inspect", |r| {
1051 0 : named_request_span(r, handle_inspect, RequestName("debug_v1_inspect"))
1052 0 : })
1053 0 : .post("/debug/v1/tenant/:tenant_id/drop", |r| {
1054 0 : named_request_span(r, handle_tenant_drop, RequestName("debug_v1_tenant_drop"))
1055 0 : })
1056 0 : .post("/debug/v1/node/:node_id/drop", |r| {
1057 0 : named_request_span(r, handle_node_drop, RequestName("debug_v1_node_drop"))
1058 0 : })
1059 0 : .post("/debug/v1/tenant/:tenant_id/import", |r| {
1060 0 : named_request_span(
1061 0 : r,
1062 0 : handle_tenant_import,
1063 0 : RequestName("debug_v1_tenant_import"),
1064 0 : )
1065 0 : })
1066 0 : .get("/debug/v1/tenant", |r| {
1067 0 : named_request_span(r, handle_tenants_dump, RequestName("debug_v1_tenant"))
1068 0 : })
1069 0 : .get("/debug/v1/tenant/:tenant_id/locate", |r| {
1070 0 : tenant_service_handler(
1071 0 : r,
1072 0 : handle_tenant_locate,
1073 0 : RequestName("debug_v1_tenant_locate"),
1074 0 : )
1075 0 : })
1076 0 : .get("/debug/v1/scheduler", |r| {
1077 0 : named_request_span(r, handle_scheduler_dump, RequestName("debug_v1_scheduler"))
1078 0 : })
1079 0 : .post("/debug/v1/consistency_check", |r| {
1080 0 : named_request_span(
1081 0 : r,
1082 0 : handle_consistency_check,
1083 0 : RequestName("debug_v1_consistency_check"),
1084 0 : )
1085 0 : })
1086 0 : .post("/debug/v1/reconcile_all", |r| {
1087 0 : request_span(r, handle_reconcile_all)
1088 0 : })
1089 0 : .put("/debug/v1/failpoints", |r| {
1090 0 : request_span(r, |r| failpoints_handler(r, CancellationToken::new()))
1091 0 : })
1092 0 : // Node operations
1093 0 : .post("/control/v1/node", |r| {
1094 0 : named_request_span(r, handle_node_register, RequestName("control_v1_node"))
1095 0 : })
1096 0 : .delete("/control/v1/node/:node_id", |r| {
1097 0 : named_request_span(r, handle_node_delete, RequestName("control_v1_node_delete"))
1098 0 : })
1099 0 : .get("/control/v1/node", |r| {
1100 0 : named_request_span(r, handle_node_list, RequestName("control_v1_node"))
1101 0 : })
1102 0 : .put("/control/v1/node/:node_id/config", |r| {
1103 0 : named_request_span(
1104 0 : r,
1105 0 : handle_node_configure,
1106 0 : RequestName("control_v1_node_config"),
1107 0 : )
1108 0 : })
1109 0 : .get("/control/v1/node/:node_id", |r| {
1110 0 : named_request_span(r, handle_node_status, RequestName("control_v1_node_status"))
1111 0 : })
1112 0 : .get("/control/v1/leader", |r| {
1113 0 : named_request_span(r, handle_get_leader, RequestName("control_v1_get_leader"))
1114 0 : })
1115 0 : .put("/control/v1/node/:node_id/drain", |r| {
1116 0 : named_request_span(r, handle_node_drain, RequestName("control_v1_node_drain"))
1117 0 : })
1118 0 : .delete("/control/v1/node/:node_id/drain", |r| {
1119 0 : named_request_span(
1120 0 : r,
1121 0 : handle_cancel_node_drain,
1122 0 : RequestName("control_v1_cancel_node_drain"),
1123 0 : )
1124 0 : })
1125 0 : .put("/control/v1/node/:node_id/fill", |r| {
1126 0 : named_request_span(r, handle_node_fill, RequestName("control_v1_node_fill"))
1127 0 : })
1128 0 : .delete("/control/v1/node/:node_id/fill", |r| {
1129 0 : named_request_span(
1130 0 : r,
1131 0 : handle_cancel_node_fill,
1132 0 : RequestName("control_v1_cancel_node_fill"),
1133 0 : )
1134 0 : })
1135 0 : // Metadata health operations
1136 0 : .post("/control/v1/metadata_health/update", |r| {
1137 0 : named_request_span(
1138 0 : r,
1139 0 : handle_metadata_health_update,
1140 0 : RequestName("control_v1_metadata_health_update"),
1141 0 : )
1142 0 : })
1143 0 : .get("/control/v1/metadata_health/unhealthy", |r| {
1144 0 : named_request_span(
1145 0 : r,
1146 0 : handle_metadata_health_list_unhealthy,
1147 0 : RequestName("control_v1_metadata_health_list_unhealthy"),
1148 0 : )
1149 0 : })
1150 0 : .post("/control/v1/metadata_health/outdated", |r| {
1151 0 : named_request_span(
1152 0 : r,
1153 0 : handle_metadata_health_list_outdated,
1154 0 : RequestName("control_v1_metadata_health_list_outdated"),
1155 0 : )
1156 0 : })
1157 0 : // Tenant Shard operations
1158 0 : .put("/control/v1/tenant/:tenant_shard_id/migrate", |r| {
1159 0 : tenant_service_handler(
1160 0 : r,
1161 0 : handle_tenant_shard_migrate,
1162 0 : RequestName("control_v1_tenant_migrate"),
1163 0 : )
1164 0 : })
1165 0 : .put("/control/v1/tenant/:tenant_id/shard_split", |r| {
1166 0 : tenant_service_handler(
1167 0 : r,
1168 0 : handle_tenant_shard_split,
1169 0 : RequestName("control_v1_tenant_shard_split"),
1170 0 : )
1171 0 : })
1172 0 : .get("/control/v1/tenant/:tenant_id", |r| {
1173 0 : tenant_service_handler(
1174 0 : r,
1175 0 : handle_tenant_describe,
1176 0 : RequestName("control_v1_tenant_describe"),
1177 0 : )
1178 0 : })
1179 0 : .get("/control/v1/tenant", |r| {
1180 0 : tenant_service_handler(r, handle_tenant_list, RequestName("control_v1_tenant_list"))
1181 0 : })
1182 0 : .put("/control/v1/tenant/:tenant_id/policy", |r| {
1183 0 : named_request_span(
1184 0 : r,
1185 0 : handle_tenant_update_policy,
1186 0 : RequestName("control_v1_tenant_policy"),
1187 0 : )
1188 0 : })
1189 0 : .put("/control/v1/preferred_azs", |r| {
1190 0 : named_request_span(
1191 0 : r,
1192 0 : handle_update_preferred_azs,
1193 0 : RequestName("control_v1_preferred_azs"),
1194 0 : )
1195 0 : })
1196 0 : .put("/control/v1/step_down", |r| {
1197 0 : named_request_span(r, handle_step_down, RequestName("control_v1_step_down"))
1198 0 : })
1199 0 : .get("/control/v1/safekeeper/:id", |r| {
1200 0 : named_request_span(r, handle_get_safekeeper, RequestName("v1_safekeeper"))
1201 0 : })
1202 0 : .post("/control/v1/safekeeper/:id", |r| {
1203 0 : // id is in the body
1204 0 : named_request_span(r, handle_upsert_safekeeper, RequestName("v1_safekeeper"))
1205 0 : })
1206 0 : // Tenant operations
1207 0 : // The ^/v1/ endpoints act as a "Virtual Pageserver", enabling shard-naive clients to call into
1208 0 : // this service to manage tenants that actually consist of many tenant shards, as if they are a single entity.
1209 0 : .post("/v1/tenant", |r| {
1210 0 : tenant_service_handler(r, handle_tenant_create, RequestName("v1_tenant"))
1211 0 : })
1212 0 : .delete("/v1/tenant/:tenant_id", |r| {
1213 0 : tenant_service_handler(r, handle_tenant_delete, RequestName("v1_tenant"))
1214 0 : })
1215 0 : .put("/v1/tenant/config", |r| {
1216 0 : tenant_service_handler(r, handle_tenant_config_set, RequestName("v1_tenant_config"))
1217 0 : })
1218 0 : .get("/v1/tenant/:tenant_id/config", |r| {
1219 0 : tenant_service_handler(r, handle_tenant_config_get, RequestName("v1_tenant_config"))
1220 0 : })
1221 0 : .put("/v1/tenant/:tenant_shard_id/location_config", |r| {
1222 0 : tenant_service_handler(
1223 0 : r,
1224 0 : handle_tenant_location_config,
1225 0 : RequestName("v1_tenant_location_config"),
1226 0 : )
1227 0 : })
1228 0 : .put("/v1/tenant/:tenant_id/time_travel_remote_storage", |r| {
1229 0 : tenant_service_handler(
1230 0 : r,
1231 0 : handle_tenant_time_travel_remote_storage,
1232 0 : RequestName("v1_tenant_time_travel_remote_storage"),
1233 0 : )
1234 0 : })
1235 0 : .post("/v1/tenant/:tenant_id/secondary/download", |r| {
1236 0 : tenant_service_handler(
1237 0 : r,
1238 0 : handle_tenant_secondary_download,
1239 0 : RequestName("v1_tenant_secondary_download"),
1240 0 : )
1241 0 : })
1242 0 : // Timeline operations
1243 0 : .delete("/v1/tenant/:tenant_id/timeline/:timeline_id", |r| {
1244 0 : tenant_service_handler(
1245 0 : r,
1246 0 : handle_tenant_timeline_delete,
1247 0 : RequestName("v1_tenant_timeline"),
1248 0 : )
1249 0 : })
1250 0 : .post("/v1/tenant/:tenant_id/timeline", |r| {
1251 0 : tenant_service_handler(
1252 0 : r,
1253 0 : handle_tenant_timeline_create,
1254 0 : RequestName("v1_tenant_timeline"),
1255 0 : )
1256 0 : })
1257 0 : .post(
1258 0 : "/v1/tenant/:tenant_id/timeline/:timeline_id/archival_config",
1259 0 : |r| {
1260 0 : tenant_service_handler(
1261 0 : r,
1262 0 : handle_tenant_timeline_archival_config,
1263 0 : RequestName("v1_tenant_timeline_archival_config"),
1264 0 : )
1265 0 : },
1266 0 : )
1267 0 : .put(
1268 0 : "/v1/tenant/:tenant_id/timeline/:timeline_id/detach_ancestor",
1269 0 : |r| {
1270 0 : tenant_service_handler(
1271 0 : r,
1272 0 : handle_tenant_timeline_detach_ancestor,
1273 0 : RequestName("v1_tenant_timeline_detach_ancestor"),
1274 0 : )
1275 0 : },
1276 0 : )
1277 0 : // Tenant detail GET passthrough to shard zero:
1278 0 : .get("/v1/tenant/:tenant_id", |r| {
1279 0 : tenant_service_handler(
1280 0 : r,
1281 0 : handle_tenant_timeline_passthrough,
1282 0 : RequestName("v1_tenant_passthrough"),
1283 0 : )
1284 0 : })
1285 0 : // The `*` in the URL is a wildcard: any tenant/timeline GET APIs on the pageserver
1286 0 : // are implicitly exposed here. This must be last in the list to avoid
1287 0 : // taking precedence over other GET methods we might implement by hand.
1288 0 : .get("/v1/tenant/:tenant_id/*", |r| {
1289 0 : tenant_service_handler(
1290 0 : r,
1291 0 : handle_tenant_timeline_passthrough,
1292 0 : RequestName("v1_tenant_passthrough"),
1293 0 : )
1294 0 : })
1295 0 : }
|