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