Line data Source code
1 : use crate::metrics::{
2 : HttpRequestLatencyLabelGroup, HttpRequestStatusLabelGroup, PageserverRequestLabelGroup,
3 : METRICS_REGISTRY,
4 : };
5 : use crate::reconciler::ReconcileError;
6 : use crate::service::{Service, STARTUP_RECONCILE_TIMEOUT};
7 : use anyhow::Context;
8 : use futures::Future;
9 : use hyper::header::CONTENT_TYPE;
10 : use hyper::{Body, Request, Response};
11 : use hyper::{StatusCode, Uri};
12 : use metrics::{BuildInfo, NeonMetrics};
13 : use pageserver_api::models::{
14 : TenantConfigRequest, TenantCreateRequest, TenantLocationConfigRequest, TenantShardSplitRequest,
15 : TenantTimeTravelRequest, TimelineCreateRequest,
16 : };
17 : use pageserver_api::shard::TenantShardId;
18 : use pageserver_client::mgmt_api;
19 : use std::sync::Arc;
20 : use std::time::{Duration, Instant};
21 : use tokio_util::sync::CancellationToken;
22 : use utils::auth::{Scope, SwappableJwtAuth};
23 : use utils::failpoint_support::failpoints_handler;
24 : use utils::http::endpoint::{auth_middleware, check_permission_with, request_span};
25 : use utils::http::request::{must_get_query_param, parse_query_param, parse_request_param};
26 : use utils::id::{TenantId, TimelineId};
27 :
28 : use utils::{
29 : http::{
30 : endpoint::{self},
31 : error::ApiError,
32 : json::{json_request, json_response},
33 : RequestExt, RouterBuilder,
34 : },
35 : id::NodeId,
36 : };
37 :
38 : use pageserver_api::controller_api::{
39 : NodeAvailability, NodeConfigureRequest, NodeRegisterRequest, TenantPolicyRequest,
40 : TenantShardMigrateRequest,
41 : };
42 : use pageserver_api::upcall_api::{ReAttachRequest, ValidateRequest};
43 :
44 : use control_plane::storage_controller::{AttachHookRequest, InspectRequest};
45 :
46 : use routerify::Middleware;
47 :
48 : /// State available to HTTP request handlers
49 : pub struct HttpState {
50 : service: Arc<crate::service::Service>,
51 : auth: Option<Arc<SwappableJwtAuth>>,
52 : neon_metrics: NeonMetrics,
53 : allowlist_routes: Vec<Uri>,
54 : }
55 :
56 : impl HttpState {
57 0 : pub fn new(
58 0 : service: Arc<crate::service::Service>,
59 0 : auth: Option<Arc<SwappableJwtAuth>>,
60 0 : build_info: BuildInfo,
61 0 : ) -> Self {
62 0 : let allowlist_routes = ["/status", "/ready", "/metrics"]
63 0 : .iter()
64 0 : .map(|v| v.parse().unwrap())
65 0 : .collect::<Vec<_>>();
66 0 : Self {
67 0 : service,
68 0 : auth,
69 0 : neon_metrics: NeonMetrics::new(build_info),
70 0 : allowlist_routes,
71 0 : }
72 0 : }
73 : }
74 :
75 : #[inline(always)]
76 0 : fn get_state(request: &Request<Body>) -> &HttpState {
77 0 : request
78 0 : .data::<Arc<HttpState>>()
79 0 : .expect("unknown state type")
80 0 : .as_ref()
81 0 : }
82 :
83 : /// Pageserver calls into this on startup, to learn which tenants it should attach
84 0 : async fn handle_re_attach(mut req: Request<Body>) -> Result<Response<Body>, ApiError> {
85 0 : check_permissions(&req, Scope::GenerationsApi)?;
86 :
87 0 : let reattach_req = json_request::<ReAttachRequest>(&mut req).await?;
88 0 : let state = get_state(&req);
89 0 : json_response(StatusCode::OK, state.service.re_attach(reattach_req).await?)
90 0 : }
91 :
92 : /// Pageserver calls into this before doing deletions, to confirm that it still
93 : /// holds the latest generation for the tenants with deletions enqueued
94 0 : async fn handle_validate(mut req: Request<Body>) -> Result<Response<Body>, ApiError> {
95 0 : check_permissions(&req, Scope::GenerationsApi)?;
96 :
97 0 : let validate_req = json_request::<ValidateRequest>(&mut req).await?;
98 0 : let state = get_state(&req);
99 0 : json_response(StatusCode::OK, state.service.validate(validate_req))
100 0 : }
101 :
102 : /// Call into this before attaching a tenant to a pageserver, to acquire a generation number
103 : /// (in the real control plane this is unnecessary, because the same program is managing
104 : /// generation numbers and doing attachments).
105 0 : async fn handle_attach_hook(mut req: Request<Body>) -> Result<Response<Body>, ApiError> {
106 0 : check_permissions(&req, Scope::Admin)?;
107 :
108 0 : let attach_req = json_request::<AttachHookRequest>(&mut req).await?;
109 0 : let state = get_state(&req);
110 0 :
111 0 : json_response(
112 0 : StatusCode::OK,
113 0 : state
114 0 : .service
115 0 : .attach_hook(attach_req)
116 0 : .await
117 0 : .map_err(ApiError::InternalServerError)?,
118 : )
119 0 : }
120 :
121 0 : async fn handle_inspect(mut req: Request<Body>) -> Result<Response<Body>, ApiError> {
122 0 : check_permissions(&req, Scope::Admin)?;
123 :
124 0 : let inspect_req = json_request::<InspectRequest>(&mut req).await?;
125 :
126 0 : let state = get_state(&req);
127 0 :
128 0 : json_response(StatusCode::OK, state.service.inspect(inspect_req))
129 0 : }
130 :
131 0 : async fn handle_tenant_create(
132 0 : service: Arc<Service>,
133 0 : mut req: Request<Body>,
134 0 : ) -> Result<Response<Body>, ApiError> {
135 0 : check_permissions(&req, Scope::PageServerApi)?;
136 :
137 0 : let create_req = json_request::<TenantCreateRequest>(&mut req).await?;
138 :
139 : json_response(
140 : StatusCode::CREATED,
141 0 : service.tenant_create(create_req).await?,
142 : )
143 0 : }
144 :
145 : // For tenant and timeline deletions, which both implement an "initially return 202, then 404 once
146 : // we're done" semantic, we wrap with a retry loop to expose a simpler API upstream. This avoids
147 : // needing to track a "deleting" state for tenants.
148 0 : async fn deletion_wrapper<R, F>(service: Arc<Service>, f: F) -> Result<Response<Body>, ApiError>
149 0 : where
150 0 : R: std::future::Future<Output = Result<StatusCode, ApiError>> + Send + 'static,
151 0 : F: Fn(Arc<Service>) -> R + Send + Sync + 'static,
152 0 : {
153 0 : let started_at = Instant::now();
154 0 : // To keep deletion reasonably snappy for small tenants, initially check after 1 second if deletion
155 0 : // completed.
156 0 : let mut retry_period = Duration::from_secs(1);
157 0 : // On subsequent retries, wait longer.
158 0 : let max_retry_period = Duration::from_secs(5);
159 0 : // Enable callers with a 30 second request timeout to reliably get a response
160 0 : let max_wait = Duration::from_secs(25);
161 :
162 : loop {
163 0 : let status = f(service.clone()).await?;
164 0 : match status {
165 : StatusCode::ACCEPTED => {
166 0 : tracing::info!("Deletion accepted, waiting to try again...");
167 0 : tokio::time::sleep(retry_period).await;
168 0 : retry_period = max_retry_period;
169 : }
170 : StatusCode::NOT_FOUND => {
171 0 : tracing::info!("Deletion complete");
172 0 : return json_response(StatusCode::OK, ());
173 : }
174 : _ => {
175 0 : tracing::warn!("Unexpected status {status}");
176 0 : return json_response(status, ());
177 : }
178 : }
179 :
180 0 : let now = Instant::now();
181 0 : if now + retry_period > started_at + max_wait {
182 0 : tracing::info!("Deletion timed out waiting for 404");
183 : // REQUEST_TIMEOUT would be more appropriate, but CONFLICT is already part of
184 : // the pageserver's swagger definition for this endpoint, and has the same desired
185 : // effect of causing the control plane to retry later.
186 0 : return json_response(StatusCode::CONFLICT, ());
187 0 : }
188 : }
189 0 : }
190 :
191 0 : async fn handle_tenant_location_config(
192 0 : service: Arc<Service>,
193 0 : mut req: Request<Body>,
194 0 : ) -> Result<Response<Body>, ApiError> {
195 0 : let tenant_shard_id: TenantShardId = parse_request_param(&req, "tenant_shard_id")?;
196 0 : check_permissions(&req, Scope::PageServerApi)?;
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_set(
208 0 : service: Arc<Service>,
209 0 : mut req: Request<Body>,
210 0 : ) -> Result<Response<Body>, ApiError> {
211 0 : check_permissions(&req, Scope::PageServerApi)?;
212 :
213 0 : let config_req = json_request::<TenantConfigRequest>(&mut req).await?;
214 :
215 0 : json_response(StatusCode::OK, service.tenant_config_set(config_req).await?)
216 0 : }
217 :
218 0 : async fn handle_tenant_config_get(
219 0 : service: Arc<Service>,
220 0 : req: Request<Body>,
221 0 : ) -> Result<Response<Body>, ApiError> {
222 0 : let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
223 0 : check_permissions(&req, Scope::PageServerApi)?;
224 :
225 0 : json_response(StatusCode::OK, service.tenant_config_get(tenant_id)?)
226 0 : }
227 :
228 0 : async fn handle_tenant_time_travel_remote_storage(
229 0 : service: Arc<Service>,
230 0 : mut req: Request<Body>,
231 0 : ) -> Result<Response<Body>, ApiError> {
232 0 : let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
233 0 : check_permissions(&req, Scope::PageServerApi)?;
234 :
235 0 : let time_travel_req = json_request::<TenantTimeTravelRequest>(&mut req).await?;
236 :
237 0 : let timestamp_raw = must_get_query_param(&req, "travel_to")?;
238 0 : let _timestamp = humantime::parse_rfc3339(×tamp_raw).map_err(|_e| {
239 0 : ApiError::BadRequest(anyhow::anyhow!(
240 0 : "Invalid time for travel_to: {timestamp_raw:?}"
241 0 : ))
242 0 : })?;
243 :
244 0 : let done_if_after_raw = must_get_query_param(&req, "done_if_after")?;
245 0 : let _done_if_after = humantime::parse_rfc3339(&done_if_after_raw).map_err(|_e| {
246 0 : ApiError::BadRequest(anyhow::anyhow!(
247 0 : "Invalid time for done_if_after: {done_if_after_raw:?}"
248 0 : ))
249 0 : })?;
250 :
251 0 : service
252 0 : .tenant_time_travel_remote_storage(
253 0 : &time_travel_req,
254 0 : tenant_id,
255 0 : timestamp_raw,
256 0 : done_if_after_raw,
257 0 : )
258 0 : .await?;
259 0 : json_response(StatusCode::OK, ())
260 0 : }
261 :
262 0 : fn map_reqwest_hyper_status(status: reqwest::StatusCode) -> Result<hyper::StatusCode, ApiError> {
263 0 : hyper::StatusCode::from_u16(status.as_u16())
264 0 : .context("invalid status code")
265 0 : .map_err(ApiError::InternalServerError)
266 0 : }
267 :
268 0 : async fn handle_tenant_secondary_download(
269 0 : service: Arc<Service>,
270 0 : req: Request<Body>,
271 0 : ) -> Result<Response<Body>, ApiError> {
272 0 : let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
273 0 : let wait = parse_query_param(&req, "wait_ms")?.map(Duration::from_millis);
274 :
275 0 : let (status, progress) = service.tenant_secondary_download(tenant_id, wait).await?;
276 0 : json_response(map_reqwest_hyper_status(status)?, progress)
277 0 : }
278 :
279 0 : async fn handle_tenant_delete(
280 0 : service: Arc<Service>,
281 0 : req: Request<Body>,
282 0 : ) -> Result<Response<Body>, ApiError> {
283 0 : let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
284 0 : check_permissions(&req, Scope::PageServerApi)?;
285 :
286 0 : deletion_wrapper(service, move |service| async move {
287 0 : service
288 0 : .tenant_delete(tenant_id)
289 0 : .await
290 0 : .and_then(map_reqwest_hyper_status)
291 0 : })
292 0 : .await
293 0 : }
294 :
295 0 : async fn handle_tenant_timeline_create(
296 0 : service: Arc<Service>,
297 0 : mut req: Request<Body>,
298 0 : ) -> Result<Response<Body>, ApiError> {
299 0 : let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
300 0 : check_permissions(&req, Scope::PageServerApi)?;
301 :
302 0 : let create_req = json_request::<TimelineCreateRequest>(&mut req).await?;
303 : json_response(
304 : StatusCode::CREATED,
305 0 : service
306 0 : .tenant_timeline_create(tenant_id, create_req)
307 0 : .await?,
308 : )
309 0 : }
310 :
311 0 : async fn handle_tenant_timeline_delete(
312 0 : service: Arc<Service>,
313 0 : req: Request<Body>,
314 0 : ) -> Result<Response<Body>, ApiError> {
315 0 : let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
316 0 : check_permissions(&req, Scope::PageServerApi)?;
317 :
318 0 : let timeline_id: TimelineId = parse_request_param(&req, "timeline_id")?;
319 :
320 0 : deletion_wrapper(service, move |service| async move {
321 0 : service
322 0 : .tenant_timeline_delete(tenant_id, timeline_id)
323 0 : .await
324 0 : .and_then(map_reqwest_hyper_status)
325 0 : })
326 0 : .await
327 0 : }
328 :
329 0 : async fn handle_tenant_timeline_passthrough(
330 0 : service: Arc<Service>,
331 0 : req: Request<Body>,
332 0 : ) -> Result<Response<Body>, ApiError> {
333 0 : let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
334 0 : check_permissions(&req, Scope::PageServerApi)?;
335 :
336 0 : let Some(path) = req.uri().path_and_query() else {
337 : // This should never happen, our request router only calls us if there is a path
338 0 : return Err(ApiError::BadRequest(anyhow::anyhow!("Missing path")));
339 : };
340 :
341 0 : tracing::info!("Proxying request for tenant {} ({})", tenant_id, path);
342 :
343 : // Find the node that holds shard zero
344 0 : let (node, tenant_shard_id) = service.tenant_shard0_node(tenant_id)?;
345 :
346 : // Callers will always pass an unsharded tenant ID. Before proxying, we must
347 : // rewrite this to a shard-aware shard zero ID.
348 0 : let path = format!("{}", path);
349 0 : let tenant_str = tenant_id.to_string();
350 0 : let tenant_shard_str = format!("{}", tenant_shard_id);
351 0 : let path = path.replace(&tenant_str, &tenant_shard_str);
352 0 :
353 0 : let latency = &METRICS_REGISTRY
354 0 : .metrics_group
355 0 : .storage_controller_passthrough_request_latency;
356 0 :
357 0 : // This is a bit awkward. We remove the param from the request
358 0 : // and join the words by '_' to get a label for the request.
359 0 : let just_path = path.replace(&tenant_shard_str, "");
360 0 : let path_label = just_path
361 0 : .split('/')
362 0 : .filter(|token| !token.is_empty())
363 0 : .collect::<Vec<_>>()
364 0 : .join("_");
365 0 : let labels = PageserverRequestLabelGroup {
366 0 : pageserver_id: &node.get_id().to_string(),
367 0 : path: &path_label,
368 0 : method: crate::metrics::Method::Get,
369 0 : };
370 0 :
371 0 : let _timer = latency.start_timer(labels.clone());
372 0 :
373 0 : let client = mgmt_api::Client::new(node.base_url(), service.get_config().jwt_token.as_deref());
374 0 : let resp = client.get_raw(path).await.map_err(|_e|
375 : // FIXME: give APiError a proper Unavailable variant. We return 503 here because
376 : // if we can't successfully send a request to the pageserver, we aren't available.
377 0 : ApiError::ShuttingDown)?;
378 :
379 0 : if !resp.status().is_success() {
380 0 : let error_counter = &METRICS_REGISTRY
381 0 : .metrics_group
382 0 : .storage_controller_passthrough_request_error;
383 0 : error_counter.inc(labels);
384 0 : }
385 :
386 : // We have a reqest::Response, would like a http::Response
387 0 : let mut builder = hyper::Response::builder().status(map_reqwest_hyper_status(resp.status())?);
388 0 : for (k, v) in resp.headers() {
389 0 : builder = builder.header(k.as_str(), v.as_bytes());
390 0 : }
391 :
392 0 : let response = builder
393 0 : .body(Body::wrap_stream(resp.bytes_stream()))
394 0 : .map_err(|e| ApiError::InternalServerError(e.into()))?;
395 :
396 0 : Ok(response)
397 0 : }
398 :
399 0 : async fn handle_tenant_locate(
400 0 : service: Arc<Service>,
401 0 : req: Request<Body>,
402 0 : ) -> Result<Response<Body>, ApiError> {
403 0 : check_permissions(&req, Scope::Admin)?;
404 :
405 0 : let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
406 0 : json_response(StatusCode::OK, service.tenant_locate(tenant_id)?)
407 0 : }
408 :
409 0 : async fn handle_tenant_describe(
410 0 : service: Arc<Service>,
411 0 : req: Request<Body>,
412 0 : ) -> Result<Response<Body>, ApiError> {
413 0 : check_permissions(&req, Scope::Admin)?;
414 :
415 0 : let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
416 0 : json_response(StatusCode::OK, service.tenant_describe(tenant_id)?)
417 0 : }
418 :
419 0 : async fn handle_tenant_list(
420 0 : service: Arc<Service>,
421 0 : req: Request<Body>,
422 0 : ) -> Result<Response<Body>, ApiError> {
423 0 : check_permissions(&req, Scope::Admin)?;
424 :
425 0 : json_response(StatusCode::OK, service.tenant_list())
426 0 : }
427 :
428 0 : async fn handle_node_register(mut req: Request<Body>) -> Result<Response<Body>, ApiError> {
429 0 : check_permissions(&req, Scope::Admin)?;
430 :
431 0 : let register_req = json_request::<NodeRegisterRequest>(&mut req).await?;
432 0 : let state = get_state(&req);
433 0 : state.service.node_register(register_req).await?;
434 0 : json_response(StatusCode::OK, ())
435 0 : }
436 :
437 0 : async fn handle_node_list(req: Request<Body>) -> Result<Response<Body>, ApiError> {
438 0 : check_permissions(&req, Scope::Admin)?;
439 :
440 0 : let state = get_state(&req);
441 0 : let nodes = state.service.node_list().await?;
442 0 : let api_nodes = nodes.into_iter().map(|n| n.describe()).collect::<Vec<_>>();
443 0 :
444 0 : json_response(StatusCode::OK, api_nodes)
445 0 : }
446 :
447 0 : async fn handle_node_drop(req: Request<Body>) -> Result<Response<Body>, ApiError> {
448 0 : check_permissions(&req, Scope::Admin)?;
449 :
450 0 : let state = get_state(&req);
451 0 : let node_id: NodeId = parse_request_param(&req, "node_id")?;
452 0 : json_response(StatusCode::OK, state.service.node_drop(node_id).await?)
453 0 : }
454 :
455 0 : async fn handle_node_configure(mut req: Request<Body>) -> Result<Response<Body>, ApiError> {
456 0 : check_permissions(&req, Scope::Admin)?;
457 :
458 0 : let node_id: NodeId = parse_request_param(&req, "node_id")?;
459 0 : let config_req = json_request::<NodeConfigureRequest>(&mut req).await?;
460 0 : if node_id != config_req.node_id {
461 0 : return Err(ApiError::BadRequest(anyhow::anyhow!(
462 0 : "Path and body node_id differ"
463 0 : )));
464 0 : }
465 0 : let state = get_state(&req);
466 0 :
467 0 : json_response(
468 0 : StatusCode::OK,
469 0 : state
470 0 : .service
471 0 : .node_configure(
472 0 : config_req.node_id,
473 0 : config_req.availability.map(NodeAvailability::from),
474 0 : config_req.scheduling,
475 0 : )
476 0 : .await?,
477 : )
478 0 : }
479 :
480 0 : async fn handle_tenant_shard_split(
481 0 : service: Arc<Service>,
482 0 : mut req: Request<Body>,
483 0 : ) -> Result<Response<Body>, ApiError> {
484 0 : check_permissions(&req, Scope::Admin)?;
485 :
486 0 : let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
487 0 : let split_req = json_request::<TenantShardSplitRequest>(&mut req).await?;
488 :
489 : json_response(
490 : StatusCode::OK,
491 0 : service.tenant_shard_split(tenant_id, split_req).await?,
492 : )
493 0 : }
494 :
495 0 : async fn handle_tenant_shard_migrate(
496 0 : service: Arc<Service>,
497 0 : mut req: Request<Body>,
498 0 : ) -> Result<Response<Body>, ApiError> {
499 0 : check_permissions(&req, Scope::Admin)?;
500 :
501 0 : let tenant_shard_id: TenantShardId = parse_request_param(&req, "tenant_shard_id")?;
502 0 : let migrate_req = json_request::<TenantShardMigrateRequest>(&mut req).await?;
503 : json_response(
504 : StatusCode::OK,
505 0 : service
506 0 : .tenant_shard_migrate(tenant_shard_id, migrate_req)
507 0 : .await?,
508 : )
509 0 : }
510 :
511 0 : async fn handle_tenant_update_policy(mut req: Request<Body>) -> Result<Response<Body>, ApiError> {
512 0 : check_permissions(&req, Scope::Admin)?;
513 :
514 0 : let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
515 0 : let update_req = json_request::<TenantPolicyRequest>(&mut req).await?;
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 : .tenant_update_policy(tenant_id, update_req)
523 0 : .await?,
524 : )
525 0 : }
526 :
527 0 : async fn handle_tenant_drop(req: Request<Body>) -> Result<Response<Body>, ApiError> {
528 0 : let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
529 0 : check_permissions(&req, Scope::PageServerApi)?;
530 :
531 0 : let state = get_state(&req);
532 0 :
533 0 : json_response(StatusCode::OK, state.service.tenant_drop(tenant_id).await?)
534 0 : }
535 :
536 0 : async fn handle_tenant_import(req: Request<Body>) -> Result<Response<Body>, ApiError> {
537 0 : let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
538 0 : check_permissions(&req, Scope::PageServerApi)?;
539 :
540 0 : let state = get_state(&req);
541 0 :
542 0 : json_response(
543 0 : StatusCode::OK,
544 0 : state.service.tenant_import(tenant_id).await?,
545 : )
546 0 : }
547 :
548 0 : async fn handle_tenants_dump(req: Request<Body>) -> Result<Response<Body>, ApiError> {
549 0 : check_permissions(&req, Scope::Admin)?;
550 :
551 0 : let state = get_state(&req);
552 0 : state.service.tenants_dump()
553 0 : }
554 :
555 0 : async fn handle_scheduler_dump(req: Request<Body>) -> Result<Response<Body>, ApiError> {
556 0 : check_permissions(&req, Scope::Admin)?;
557 :
558 0 : let state = get_state(&req);
559 0 : state.service.scheduler_dump()
560 0 : }
561 :
562 0 : async fn handle_consistency_check(req: Request<Body>) -> Result<Response<Body>, ApiError> {
563 0 : check_permissions(&req, Scope::Admin)?;
564 :
565 0 : let state = get_state(&req);
566 0 :
567 0 : json_response(StatusCode::OK, state.service.consistency_check().await?)
568 0 : }
569 :
570 0 : async fn handle_reconcile_all(req: Request<Body>) -> Result<Response<Body>, ApiError> {
571 0 : check_permissions(&req, Scope::Admin)?;
572 :
573 0 : let state = get_state(&req);
574 0 :
575 0 : json_response(StatusCode::OK, state.service.reconcile_all_now().await?)
576 0 : }
577 :
578 : /// Status endpoint is just used for checking that our HTTP listener is up
579 0 : async fn handle_status(_req: Request<Body>) -> Result<Response<Body>, ApiError> {
580 0 : json_response(StatusCode::OK, ())
581 0 : }
582 :
583 : /// Readiness endpoint indicates when we're done doing startup I/O (e.g. reconciling
584 : /// with remote pageserver nodes). This is intended for use as a kubernetes readiness probe.
585 0 : async fn handle_ready(req: Request<Body>) -> Result<Response<Body>, ApiError> {
586 0 : let state = get_state(&req);
587 0 : if state.service.startup_complete.is_ready() {
588 0 : json_response(StatusCode::OK, ())
589 : } else {
590 0 : json_response(StatusCode::SERVICE_UNAVAILABLE, ())
591 : }
592 0 : }
593 :
594 : impl From<ReconcileError> for ApiError {
595 0 : fn from(value: ReconcileError) -> Self {
596 0 : ApiError::Conflict(format!("Reconciliation error: {}", value))
597 0 : }
598 : }
599 :
600 : /// Common wrapper for request handlers that call into Service and will operate on tenants: they must only
601 : /// be allowed to run if Service has finished its initial reconciliation.
602 0 : async fn tenant_service_handler<R, H>(
603 0 : request: Request<Body>,
604 0 : handler: H,
605 0 : request_name: RequestName,
606 0 : ) -> R::Output
607 0 : where
608 0 : R: std::future::Future<Output = Result<Response<Body>, ApiError>> + Send + 'static,
609 0 : H: FnOnce(Arc<Service>, Request<Body>) -> R + Send + Sync + 'static,
610 0 : {
611 0 : let state = get_state(&request);
612 0 : let service = state.service.clone();
613 0 :
614 0 : let startup_complete = service.startup_complete.clone();
615 0 : if tokio::time::timeout(STARTUP_RECONCILE_TIMEOUT, startup_complete.wait())
616 0 : .await
617 0 : .is_err()
618 : {
619 : // This shouldn't happen: it is the responsibilty of [`Service::startup_reconcile`] to use appropriate
620 : // timeouts around its remote calls, to bound its runtime.
621 0 : return Err(ApiError::Timeout(
622 0 : "Timed out waiting for service readiness".into(),
623 0 : ));
624 0 : }
625 0 :
626 0 : named_request_span(
627 0 : request,
628 0 : |request| async move { handler(service, request).await },
629 0 : request_name,
630 0 : )
631 0 : .await
632 0 : }
633 :
634 : /// Check if the required scope is held in the request's token, or if the request has
635 : /// a token with 'admin' scope then always permit it.
636 0 : fn check_permissions(request: &Request<Body>, required_scope: Scope) -> Result<(), ApiError> {
637 0 : check_permission_with(request, |claims| {
638 0 : match crate::auth::check_permission(claims, required_scope) {
639 0 : Err(e) => match crate::auth::check_permission(claims, Scope::Admin) {
640 0 : Ok(()) => Ok(()),
641 0 : Err(_) => Err(e),
642 : },
643 0 : Ok(()) => Ok(()),
644 : }
645 0 : })
646 0 : }
647 :
648 : #[derive(Clone, Debug)]
649 : struct RequestMeta {
650 : method: hyper::http::Method,
651 : at: Instant,
652 : }
653 :
654 0 : fn prologue_metrics_middleware<B: hyper::body::HttpBody + Send + Sync + 'static>(
655 0 : ) -> Middleware<B, ApiError> {
656 0 : Middleware::pre(move |req| async move {
657 0 : let meta = RequestMeta {
658 0 : method: req.method().clone(),
659 0 : at: Instant::now(),
660 0 : };
661 0 :
662 0 : req.set_context(meta);
663 0 :
664 0 : Ok(req)
665 0 : })
666 0 : }
667 :
668 0 : fn epilogue_metrics_middleware<B: hyper::body::HttpBody + Send + Sync + 'static>(
669 0 : ) -> Middleware<B, ApiError> {
670 0 : Middleware::post_with_info(move |resp, req_info| async move {
671 0 : let request_name = match req_info.context::<RequestName>() {
672 0 : Some(name) => name,
673 0 : None => {
674 0 : return Ok(resp);
675 0 : }
676 0 : };
677 0 :
678 0 : if let Some(meta) = req_info.context::<RequestMeta>() {
679 0 : let status = &crate::metrics::METRICS_REGISTRY
680 0 : .metrics_group
681 0 : .storage_controller_http_request_status;
682 0 : let latency = &crate::metrics::METRICS_REGISTRY
683 0 : .metrics_group
684 0 : .storage_controller_http_request_latency;
685 0 :
686 0 : status.inc(HttpRequestStatusLabelGroup {
687 0 : path: request_name.0,
688 0 : method: meta.method.clone().into(),
689 0 : status: crate::metrics::StatusCode(resp.status()),
690 0 : });
691 0 :
692 0 : latency.observe(
693 0 : HttpRequestLatencyLabelGroup {
694 0 : path: request_name.0,
695 0 : method: meta.method.into(),
696 0 : },
697 0 : meta.at.elapsed().as_secs_f64(),
698 0 : );
699 0 : }
700 0 : Ok(resp)
701 0 : })
702 0 : }
703 :
704 0 : pub async fn measured_metrics_handler(req: Request<Body>) -> Result<Response<Body>, ApiError> {
705 0 : pub const TEXT_FORMAT: &str = "text/plain; version=0.0.4";
706 0 :
707 0 : let state = get_state(&req);
708 0 : let payload = crate::metrics::METRICS_REGISTRY.encode(&state.neon_metrics);
709 0 : let response = Response::builder()
710 0 : .status(200)
711 0 : .header(CONTENT_TYPE, TEXT_FORMAT)
712 0 : .body(payload.into())
713 0 : .unwrap();
714 0 :
715 0 : Ok(response)
716 0 : }
717 :
718 : #[derive(Clone)]
719 : struct RequestName(&'static str);
720 :
721 0 : async fn named_request_span<R, H>(
722 0 : request: Request<Body>,
723 0 : handler: H,
724 0 : name: RequestName,
725 0 : ) -> R::Output
726 0 : where
727 0 : R: Future<Output = Result<Response<Body>, ApiError>> + Send + 'static,
728 0 : H: FnOnce(Request<Body>) -> R + Send + Sync + 'static,
729 0 : {
730 0 : request.set_context(name);
731 0 : request_span(request, handler).await
732 0 : }
733 :
734 0 : pub fn make_router(
735 0 : service: Arc<Service>,
736 0 : auth: Option<Arc<SwappableJwtAuth>>,
737 0 : build_info: BuildInfo,
738 0 : ) -> RouterBuilder<hyper::Body, ApiError> {
739 0 : let mut router = endpoint::make_router()
740 0 : .middleware(prologue_metrics_middleware())
741 0 : .middleware(epilogue_metrics_middleware());
742 0 : if auth.is_some() {
743 0 : router = router.middleware(auth_middleware(|request| {
744 0 : let state = get_state(request);
745 0 : if state.allowlist_routes.contains(request.uri()) {
746 0 : None
747 : } else {
748 0 : state.auth.as_deref()
749 : }
750 0 : }));
751 0 : }
752 :
753 0 : router
754 0 : .data(Arc::new(HttpState::new(service, auth, build_info)))
755 0 : .get("/metrics", |r| {
756 0 : named_request_span(r, measured_metrics_handler, RequestName("metrics"))
757 0 : })
758 0 : // Non-prefixed generic endpoints (status, metrics)
759 0 : .get("/status", |r| {
760 0 : named_request_span(r, handle_status, RequestName("status"))
761 0 : })
762 0 : .get("/ready", |r| {
763 0 : named_request_span(r, handle_ready, RequestName("ready"))
764 0 : })
765 0 : // Upcalls for the pageserver: point the pageserver's `control_plane_api` config to this prefix
766 0 : .post("/upcall/v1/re-attach", |r| {
767 0 : named_request_span(r, handle_re_attach, RequestName("upcall_v1_reattach"))
768 0 : })
769 0 : .post("/upcall/v1/validate", |r| {
770 0 : named_request_span(r, handle_validate, RequestName("upcall_v1_validate"))
771 0 : })
772 0 : // Test/dev/debug endpoints
773 0 : .post("/debug/v1/attach-hook", |r| {
774 0 : named_request_span(r, handle_attach_hook, RequestName("debug_v1_attach_hook"))
775 0 : })
776 0 : .post("/debug/v1/inspect", |r| {
777 0 : named_request_span(r, handle_inspect, RequestName("debug_v1_inspect"))
778 0 : })
779 0 : .post("/debug/v1/tenant/:tenant_id/drop", |r| {
780 0 : named_request_span(r, handle_tenant_drop, RequestName("debug_v1_tenant_drop"))
781 0 : })
782 0 : .post("/debug/v1/node/:node_id/drop", |r| {
783 0 : named_request_span(r, handle_node_drop, RequestName("debug_v1_node_drop"))
784 0 : })
785 0 : .post("/debug/v1/tenant/:tenant_id/import", |r| {
786 0 : named_request_span(
787 0 : r,
788 0 : handle_tenant_import,
789 0 : RequestName("debug_v1_tenant_import"),
790 0 : )
791 0 : })
792 0 : .get("/debug/v1/tenant", |r| {
793 0 : named_request_span(r, handle_tenants_dump, RequestName("debug_v1_tenant"))
794 0 : })
795 0 : .get("/debug/v1/tenant/:tenant_id/locate", |r| {
796 0 : tenant_service_handler(
797 0 : r,
798 0 : handle_tenant_locate,
799 0 : RequestName("debug_v1_tenant_locate"),
800 0 : )
801 0 : })
802 0 : .get("/debug/v1/scheduler", |r| {
803 0 : named_request_span(r, handle_scheduler_dump, RequestName("debug_v1_scheduler"))
804 0 : })
805 0 : .post("/debug/v1/consistency_check", |r| {
806 0 : named_request_span(
807 0 : r,
808 0 : handle_consistency_check,
809 0 : RequestName("debug_v1_consistency_check"),
810 0 : )
811 0 : })
812 0 : .post("/debug/v1/reconcile_all", |r| {
813 0 : request_span(r, handle_reconcile_all)
814 0 : })
815 0 : .put("/debug/v1/failpoints", |r| {
816 0 : request_span(r, |r| failpoints_handler(r, CancellationToken::new()))
817 0 : })
818 0 : // Node operations
819 0 : .post("/control/v1/node", |r| {
820 0 : named_request_span(r, handle_node_register, RequestName("control_v1_node"))
821 0 : })
822 0 : .get("/control/v1/node", |r| {
823 0 : named_request_span(r, handle_node_list, RequestName("control_v1_node"))
824 0 : })
825 0 : .put("/control/v1/node/:node_id/config", |r| {
826 0 : named_request_span(
827 0 : r,
828 0 : handle_node_configure,
829 0 : RequestName("control_v1_node_config"),
830 0 : )
831 0 : })
832 0 : // Tenant Shard operations
833 0 : .put("/control/v1/tenant/:tenant_shard_id/migrate", |r| {
834 0 : tenant_service_handler(
835 0 : r,
836 0 : handle_tenant_shard_migrate,
837 0 : RequestName("control_v1_tenant_migrate"),
838 0 : )
839 0 : })
840 0 : .put("/control/v1/tenant/:tenant_id/shard_split", |r| {
841 0 : tenant_service_handler(
842 0 : r,
843 0 : handle_tenant_shard_split,
844 0 : RequestName("control_v1_tenant_shard_split"),
845 0 : )
846 0 : })
847 0 : .get("/control/v1/tenant/:tenant_id", |r| {
848 0 : tenant_service_handler(
849 0 : r,
850 0 : handle_tenant_describe,
851 0 : RequestName("control_v1_tenant_describe"),
852 0 : )
853 0 : })
854 0 : .get("/control/v1/tenant", |r| {
855 0 : tenant_service_handler(r, handle_tenant_list, RequestName("control_v1_tenant_list"))
856 0 : })
857 0 : .put("/control/v1/tenant/:tenant_id/policy", |r| {
858 0 : named_request_span(
859 0 : r,
860 0 : handle_tenant_update_policy,
861 0 : RequestName("control_v1_tenant_policy"),
862 0 : )
863 0 : })
864 0 : // Tenant operations
865 0 : // The ^/v1/ endpoints act as a "Virtual Pageserver", enabling shard-naive clients to call into
866 0 : // this service to manage tenants that actually consist of many tenant shards, as if they are a single entity.
867 0 : .post("/v1/tenant", |r| {
868 0 : tenant_service_handler(r, handle_tenant_create, RequestName("v1_tenant"))
869 0 : })
870 0 : .delete("/v1/tenant/:tenant_id", |r| {
871 0 : tenant_service_handler(r, handle_tenant_delete, RequestName("v1_tenant"))
872 0 : })
873 0 : .put("/v1/tenant/config", |r| {
874 0 : tenant_service_handler(r, handle_tenant_config_set, RequestName("v1_tenant_config"))
875 0 : })
876 0 : .get("/v1/tenant/:tenant_id/config", |r| {
877 0 : tenant_service_handler(r, handle_tenant_config_get, RequestName("v1_tenant_config"))
878 0 : })
879 0 : .put("/v1/tenant/:tenant_shard_id/location_config", |r| {
880 0 : tenant_service_handler(
881 0 : r,
882 0 : handle_tenant_location_config,
883 0 : RequestName("v1_tenant_location_config"),
884 0 : )
885 0 : })
886 0 : .put("/v1/tenant/:tenant_id/time_travel_remote_storage", |r| {
887 0 : tenant_service_handler(
888 0 : r,
889 0 : handle_tenant_time_travel_remote_storage,
890 0 : RequestName("v1_tenant_time_travel_remote_storage"),
891 0 : )
892 0 : })
893 0 : .post("/v1/tenant/:tenant_id/secondary/download", |r| {
894 0 : tenant_service_handler(
895 0 : r,
896 0 : handle_tenant_secondary_download,
897 0 : RequestName("v1_tenant_secondary_download"),
898 0 : )
899 0 : })
900 0 : // Timeline operations
901 0 : .delete("/v1/tenant/:tenant_id/timeline/:timeline_id", |r| {
902 0 : tenant_service_handler(
903 0 : r,
904 0 : handle_tenant_timeline_delete,
905 0 : RequestName("v1_tenant_timeline"),
906 0 : )
907 0 : })
908 0 : .post("/v1/tenant/:tenant_id/timeline", |r| {
909 0 : tenant_service_handler(
910 0 : r,
911 0 : handle_tenant_timeline_create,
912 0 : RequestName("v1_tenant_timeline"),
913 0 : )
914 0 : })
915 0 : // Tenant detail GET passthrough to shard zero:
916 0 : .get("/v1/tenant/:tenant_id", |r| {
917 0 : tenant_service_handler(
918 0 : r,
919 0 : handle_tenant_timeline_passthrough,
920 0 : RequestName("v1_tenant_passthrough"),
921 0 : )
922 0 : })
923 0 : // The `*` in the URL is a wildcard: any tenant/timeline GET APIs on the pageserver
924 0 : // are implicitly exposed here. This must be last in the list to avoid
925 0 : // taking precedence over other GET methods we might implement by hand.
926 0 : .get("/v1/tenant/:tenant_id/*", |r| {
927 0 : tenant_service_handler(
928 0 : r,
929 0 : handle_tenant_timeline_passthrough,
930 0 : RequestName("v1_tenant_passthrough"),
931 0 : )
932 0 : })
933 0 : }
|