LCOV - code coverage report
Current view: top level - safekeeper/src/http - routes.rs (source / functions) Coverage Total Hit
Test: aca806cab4756d7eb6a304846130f4a73a5d5393.info Lines: 2.5 % 591 15
Test Date: 2025-04-24 20:31:15 Functions: 1.2 % 86 1

            Line data    Source code
       1              : use std::collections::HashMap;
       2              : use std::fmt;
       3              : use std::io::Write as _;
       4              : use std::str::FromStr;
       5              : use std::sync::Arc;
       6              : 
       7              : use http_utils::endpoint::{
       8              :     self, ChannelWriter, auth_middleware, check_permission_with, profile_cpu_handler,
       9              :     profile_heap_handler, prometheus_metrics_handler, request_span,
      10              : };
      11              : use http_utils::error::ApiError;
      12              : use http_utils::failpoints::failpoints_handler;
      13              : use http_utils::json::{json_request, json_response};
      14              : use http_utils::request::{ensure_no_body, parse_query_param, parse_request_param};
      15              : use http_utils::{RequestExt, RouterBuilder};
      16              : use hyper::{Body, Request, Response, StatusCode};
      17              : use pem::Pem;
      18              : use postgres_ffi::WAL_SEGMENT_SIZE;
      19              : use safekeeper_api::models::{
      20              :     AcceptorStateStatus, PullTimelineRequest, SafekeeperStatus, SkTimelineInfo, TenantDeleteResult,
      21              :     TermSwitchApiEntry, TimelineCopyRequest, TimelineCreateRequest, TimelineDeleteResult,
      22              :     TimelineStatus, TimelineTermBumpRequest,
      23              : };
      24              : use safekeeper_api::{ServerInfo, membership, models};
      25              : use storage_broker::proto::{SafekeeperTimelineInfo, TenantTimelineId as ProtoTenantTimelineId};
      26              : use tokio::sync::mpsc;
      27              : use tokio::task;
      28              : use tokio_stream::wrappers::ReceiverStream;
      29              : use tokio_util::sync::CancellationToken;
      30              : use tracing::{Instrument, info_span};
      31              : use utils::auth::SwappableJwtAuth;
      32              : use utils::id::{TenantId, TenantTimelineId, TimelineId};
      33              : use utils::lsn::Lsn;
      34              : 
      35              : use crate::debug_dump::TimelineDigestRequest;
      36              : use crate::safekeeper::TermLsn;
      37              : use crate::timelines_global_map::DeleteOrExclude;
      38              : use crate::{
      39              :     GlobalTimelines, SafeKeeperConf, copy_timeline, debug_dump, patch_control_file, pull_timeline,
      40              : };
      41              : 
      42              : /// Healthcheck handler.
      43            0 : async fn status_handler(request: Request<Body>) -> Result<Response<Body>, ApiError> {
      44            0 :     check_permission(&request, None)?;
      45            0 :     let conf = get_conf(&request);
      46            0 :     let status = SafekeeperStatus { id: conf.my_id };
      47            0 :     json_response(StatusCode::OK, status)
      48            0 : }
      49              : 
      50            0 : fn get_conf(request: &Request<Body>) -> &SafeKeeperConf {
      51            0 :     request
      52            0 :         .data::<Arc<SafeKeeperConf>>()
      53            0 :         .expect("unknown state type")
      54            0 :         .as_ref()
      55            0 : }
      56              : 
      57            0 : fn get_global_timelines(request: &Request<Body>) -> Arc<GlobalTimelines> {
      58            0 :     request
      59            0 :         .data::<Arc<GlobalTimelines>>()
      60            0 :         .expect("unknown state type")
      61            0 :         .clone()
      62            0 : }
      63              : 
      64            0 : fn check_permission(request: &Request<Body>, tenant_id: Option<TenantId>) -> Result<(), ApiError> {
      65            0 :     check_permission_with(request, |claims| {
      66            0 :         crate::auth::check_permission(claims, tenant_id)
      67            0 :     })
      68            0 : }
      69              : 
      70              : /// Deactivates all timelines for the tenant and removes its data directory.
      71              : /// See `timeline_delete_handler`.
      72            0 : async fn tenant_delete_handler(mut request: Request<Body>) -> Result<Response<Body>, ApiError> {
      73            0 :     let tenant_id = parse_request_param(&request, "tenant_id")?;
      74            0 :     let only_local = parse_query_param(&request, "only_local")?.unwrap_or(false);
      75            0 :     check_permission(&request, Some(tenant_id))?;
      76            0 :     ensure_no_body(&mut request).await?;
      77            0 :     let global_timelines = get_global_timelines(&request);
      78            0 :     let action = if only_local {
      79            0 :         DeleteOrExclude::DeleteLocal
      80              :     } else {
      81            0 :         DeleteOrExclude::Delete
      82              :     };
      83            0 :     let delete_info = global_timelines
      84            0 :         .delete_all_for_tenant(&tenant_id, action)
      85            0 :         .await
      86            0 :         .map_err(ApiError::InternalServerError)?;
      87            0 :     let response_body: TenantDeleteResult = delete_info
      88            0 :         .iter()
      89            0 :         .map(|(ttid, resp)| (format!("{}", ttid.timeline_id), *resp))
      90            0 :         .collect::<HashMap<String, TimelineDeleteResult>>();
      91            0 :     json_response(StatusCode::OK, response_body)
      92            0 : }
      93              : 
      94            0 : async fn timeline_create_handler(mut request: Request<Body>) -> Result<Response<Body>, ApiError> {
      95            0 :     let request_data: TimelineCreateRequest = json_request(&mut request).await?;
      96              : 
      97            0 :     let ttid = TenantTimelineId {
      98            0 :         tenant_id: request_data.tenant_id,
      99            0 :         timeline_id: request_data.timeline_id,
     100            0 :     };
     101            0 :     check_permission(&request, Some(ttid.tenant_id))?;
     102              : 
     103            0 :     let server_info = ServerInfo {
     104            0 :         pg_version: request_data.pg_version,
     105            0 :         system_id: request_data.system_id.unwrap_or(0),
     106            0 :         wal_seg_size: request_data.wal_seg_size.unwrap_or(WAL_SEGMENT_SIZE as u32),
     107            0 :     };
     108            0 :     let global_timelines = get_global_timelines(&request);
     109            0 :     global_timelines
     110            0 :         .create(
     111            0 :             ttid,
     112            0 :             request_data.mconf,
     113            0 :             server_info,
     114            0 :             request_data.start_lsn,
     115            0 :             request_data.commit_lsn.unwrap_or(request_data.start_lsn),
     116            0 :         )
     117            0 :         .await
     118            0 :         .map_err(ApiError::InternalServerError)?;
     119              : 
     120            0 :     json_response(StatusCode::OK, ())
     121            0 : }
     122              : 
     123            0 : async fn utilization_handler(request: Request<Body>) -> Result<Response<Body>, ApiError> {
     124            0 :     check_permission(&request, None)?;
     125            0 :     let global_timelines = get_global_timelines(&request);
     126            0 :     let utilization = global_timelines.get_timeline_counts();
     127            0 :     json_response(StatusCode::OK, utilization)
     128            0 : }
     129              : 
     130              : /// List all (not deleted) timelines.
     131              : /// Note: it is possible to do the same with debug_dump.
     132            0 : async fn timeline_list_handler(request: Request<Body>) -> Result<Response<Body>, ApiError> {
     133            0 :     check_permission(&request, None)?;
     134            0 :     let global_timelines = get_global_timelines(&request);
     135            0 :     let res: Vec<TenantTimelineId> = global_timelines
     136            0 :         .get_all()
     137            0 :         .iter()
     138            0 :         .map(|tli| tli.ttid)
     139            0 :         .collect();
     140            0 :     json_response(StatusCode::OK, res)
     141            0 : }
     142              : 
     143              : impl From<TermSwitchApiEntry> for TermLsn {
     144            0 :     fn from(api_val: TermSwitchApiEntry) -> Self {
     145            0 :         TermLsn {
     146            0 :             term: api_val.term,
     147            0 :             lsn: api_val.lsn,
     148            0 :         }
     149            0 :     }
     150              : }
     151              : 
     152              : /// Report info about timeline.
     153            0 : async fn timeline_status_handler(request: Request<Body>) -> Result<Response<Body>, ApiError> {
     154            0 :     let ttid = TenantTimelineId::new(
     155            0 :         parse_request_param(&request, "tenant_id")?,
     156            0 :         parse_request_param(&request, "timeline_id")?,
     157              :     );
     158            0 :     check_permission(&request, Some(ttid.tenant_id))?;
     159              : 
     160            0 :     let global_timelines = get_global_timelines(&request);
     161            0 :     let tli = global_timelines.get(ttid).map_err(ApiError::from)?;
     162            0 :     let (inmem, state) = tli.get_state().await;
     163            0 :     let flush_lsn = tli.get_flush_lsn().await;
     164              : 
     165            0 :     let last_log_term = state.acceptor_state.get_last_log_term(flush_lsn);
     166            0 :     let term_history = state
     167            0 :         .acceptor_state
     168            0 :         .term_history
     169            0 :         .0
     170            0 :         .into_iter()
     171            0 :         .map(|ts| TermSwitchApiEntry {
     172            0 :             term: ts.term,
     173            0 :             lsn: ts.lsn,
     174            0 :         })
     175            0 :         .collect();
     176            0 :     let acc_state = AcceptorStateStatus {
     177            0 :         term: state.acceptor_state.term,
     178            0 :         epoch: last_log_term,
     179            0 :         term_history,
     180            0 :     };
     181            0 : 
     182            0 :     let conf = get_conf(&request);
     183              :     // Note: we report in memory values which can be lost.
     184            0 :     let status = TimelineStatus {
     185            0 :         tenant_id: ttid.tenant_id,
     186            0 :         timeline_id: ttid.timeline_id,
     187            0 :         mconf: state.mconf,
     188            0 :         acceptor_state: acc_state,
     189            0 :         pg_info: state.server,
     190            0 :         flush_lsn,
     191            0 :         timeline_start_lsn: state.timeline_start_lsn,
     192            0 :         local_start_lsn: state.local_start_lsn,
     193            0 :         commit_lsn: inmem.commit_lsn,
     194            0 :         backup_lsn: inmem.backup_lsn,
     195            0 :         peer_horizon_lsn: inmem.peer_horizon_lsn,
     196            0 :         remote_consistent_lsn: inmem.remote_consistent_lsn,
     197            0 :         peers: tli.get_peers(conf).await,
     198            0 :         walsenders: tli.get_walsenders().get_all_public(),
     199            0 :         walreceivers: tli.get_walreceivers().get_all(),
     200            0 :     };
     201            0 :     json_response(StatusCode::OK, status)
     202            0 : }
     203              : 
     204              : /// Deactivates the timeline and removes its data directory.
     205            0 : async fn timeline_delete_handler(mut request: Request<Body>) -> Result<Response<Body>, ApiError> {
     206            0 :     let ttid = TenantTimelineId::new(
     207            0 :         parse_request_param(&request, "tenant_id")?,
     208            0 :         parse_request_param(&request, "timeline_id")?,
     209              :     );
     210            0 :     let only_local = parse_query_param(&request, "only_local")?.unwrap_or(false);
     211            0 :     check_permission(&request, Some(ttid.tenant_id))?;
     212            0 :     ensure_no_body(&mut request).await?;
     213            0 :     let global_timelines = get_global_timelines(&request);
     214            0 :     let action = if only_local {
     215            0 :         DeleteOrExclude::DeleteLocal
     216              :     } else {
     217            0 :         DeleteOrExclude::Delete
     218              :     };
     219            0 :     let resp = global_timelines
     220            0 :         .delete_or_exclude(&ttid, action)
     221            0 :         .await
     222            0 :         .map_err(ApiError::from)?;
     223            0 :     json_response(StatusCode::OK, resp)
     224            0 : }
     225              : 
     226              : /// Pull timeline from peer safekeeper instances.
     227            0 : async fn timeline_pull_handler(mut request: Request<Body>) -> Result<Response<Body>, ApiError> {
     228            0 :     check_permission(&request, None)?;
     229              : 
     230            0 :     let data: PullTimelineRequest = json_request(&mut request).await?;
     231            0 :     let conf = get_conf(&request);
     232            0 :     let global_timelines = get_global_timelines(&request);
     233              : 
     234            0 :     let ca_certs = conf
     235            0 :         .ssl_ca_certs
     236            0 :         .iter()
     237            0 :         .map(Pem::contents)
     238            0 :         .map(reqwest::Certificate::from_der)
     239            0 :         .collect::<Result<Vec<_>, _>>()
     240            0 :         .map_err(|e| {
     241            0 :             ApiError::InternalServerError(anyhow::anyhow!("failed to parse CA certs: {e}"))
     242            0 :         })?;
     243              : 
     244            0 :     let resp =
     245            0 :         pull_timeline::handle_request(data, conf.sk_auth_token.clone(), ca_certs, global_timelines)
     246            0 :             .await
     247            0 :             .map_err(ApiError::InternalServerError)?;
     248            0 :     json_response(StatusCode::OK, resp)
     249            0 : }
     250              : 
     251              : /// Stream tar archive with all timeline data.
     252            0 : async fn timeline_snapshot_handler(request: Request<Body>) -> Result<Response<Body>, ApiError> {
     253            0 :     let destination = parse_request_param(&request, "destination_id")?;
     254            0 :     let ttid = TenantTimelineId::new(
     255            0 :         parse_request_param(&request, "tenant_id")?,
     256            0 :         parse_request_param(&request, "timeline_id")?,
     257              :     );
     258            0 :     check_permission(&request, Some(ttid.tenant_id))?;
     259              : 
     260            0 :     let global_timelines = get_global_timelines(&request);
     261            0 :     let tli = global_timelines.get(ttid).map_err(ApiError::from)?;
     262              : 
     263              :     // To stream the body use wrap_stream which wants Stream of Result<Bytes>,
     264              :     // so create the chan and write to it in another task.
     265            0 :     let (tx, rx) = mpsc::channel(1);
     266            0 : 
     267            0 :     let conf = get_conf(&request);
     268            0 :     task::spawn(pull_timeline::stream_snapshot(
     269            0 :         tli,
     270            0 :         conf.my_id,
     271            0 :         destination,
     272            0 :         tx,
     273            0 :     ));
     274            0 : 
     275            0 :     let rx_stream = ReceiverStream::new(rx);
     276            0 :     let body = Body::wrap_stream(rx_stream);
     277            0 : 
     278            0 :     let response = Response::builder()
     279            0 :         .status(200)
     280            0 :         .header(hyper::header::CONTENT_TYPE, "application/octet-stream")
     281            0 :         .body(body)
     282            0 :         .unwrap();
     283            0 : 
     284            0 :     Ok(response)
     285            0 : }
     286              : 
     287              : /// Error type for delete_or_exclude: either generation conflict or something
     288              : /// internal.
     289              : #[derive(thiserror::Error, Debug)]
     290              : pub enum DeleteOrExcludeError {
     291              :     #[error("refused to switch into excluding mconf {requested}, current: {current}")]
     292              :     Conflict {
     293              :         requested: membership::Configuration,
     294              :         current: membership::Configuration,
     295              :     },
     296              :     #[error(transparent)]
     297              :     Other(#[from] anyhow::Error),
     298              : }
     299              : 
     300              : /// Convert DeleteOrExcludeError to ApiError.
     301              : impl From<DeleteOrExcludeError> for ApiError {
     302            0 :     fn from(de: DeleteOrExcludeError) -> ApiError {
     303            0 :         match de {
     304              :             DeleteOrExcludeError::Conflict {
     305              :                 requested: _,
     306              :                 current: _,
     307            0 :             } => ApiError::Conflict(de.to_string()),
     308            0 :             DeleteOrExcludeError::Other(e) => ApiError::InternalServerError(e),
     309              :         }
     310            0 :     }
     311              : }
     312              : 
     313              : /// Remove timeline locally after this node has been excluded from the
     314              : /// membership configuration. The body is the same as in the membership endpoint
     315              : /// -- conf where node is excluded -- and in principle single ep could be used
     316              : /// for both actions, but since this is a data deletion op let's keep them
     317              : /// separate.
     318            0 : async fn timeline_exclude_handler(mut request: Request<Body>) -> Result<Response<Body>, ApiError> {
     319            0 :     let ttid = TenantTimelineId::new(
     320            0 :         parse_request_param(&request, "tenant_id")?,
     321            0 :         parse_request_param(&request, "timeline_id")?,
     322              :     );
     323            0 :     check_permission(&request, Some(ttid.tenant_id))?;
     324              : 
     325            0 :     let global_timelines = get_global_timelines(&request);
     326            0 :     let data: models::TimelineMembershipSwitchRequest = json_request(&mut request).await?;
     327            0 :     let my_id = get_conf(&request).my_id;
     328            0 :     // If request doesn't exclude us, membership switch endpoint should be used
     329            0 :     // instead.
     330            0 :     if data.mconf.contains(my_id) {
     331            0 :         return Err(ApiError::Forbidden(format!(
     332            0 :             "refused to switch into {}, node {} is member of it",
     333            0 :             data.mconf, my_id
     334            0 :         )));
     335            0 :     }
     336            0 :     let action = DeleteOrExclude::Exclude(data.mconf);
     337              : 
     338            0 :     let resp = global_timelines
     339            0 :         .delete_or_exclude(&ttid, action)
     340            0 :         .await
     341            0 :         .map_err(ApiError::from)?;
     342            0 :     json_response(StatusCode::OK, resp)
     343            0 : }
     344              : 
     345              : /// Consider switching timeline membership configuration to the provided one.
     346            0 : async fn timeline_membership_handler(
     347            0 :     mut request: Request<Body>,
     348            0 : ) -> Result<Response<Body>, ApiError> {
     349            0 :     let ttid = TenantTimelineId::new(
     350            0 :         parse_request_param(&request, "tenant_id")?,
     351            0 :         parse_request_param(&request, "timeline_id")?,
     352              :     );
     353            0 :     check_permission(&request, Some(ttid.tenant_id))?;
     354              : 
     355            0 :     let global_timelines = get_global_timelines(&request);
     356            0 :     let tli = global_timelines.get(ttid).map_err(ApiError::from)?;
     357              : 
     358            0 :     let data: models::TimelineMembershipSwitchRequest = json_request(&mut request).await?;
     359            0 :     let my_id = get_conf(&request).my_id;
     360            0 :     // If request excludes us, exclude endpoint should be used instead.
     361            0 :     if !data.mconf.contains(my_id) {
     362            0 :         return Err(ApiError::Forbidden(format!(
     363            0 :             "refused to switch into {}, node {} is not a member of it",
     364            0 :             data.mconf, my_id
     365            0 :         )));
     366            0 :     }
     367            0 :     let req_gen = data.mconf.generation;
     368            0 :     let response = tli
     369            0 :         .membership_switch(data.mconf)
     370            0 :         .await
     371            0 :         .map_err(ApiError::InternalServerError)?;
     372              : 
     373              :     // Return 409 if request was ignored.
     374            0 :     if req_gen == response.current_conf.generation {
     375            0 :         json_response(StatusCode::OK, response)
     376              :     } else {
     377            0 :         Err(ApiError::Conflict(format!(
     378            0 :             "request to switch into {} ignored, current generation {}",
     379            0 :             req_gen, response.current_conf.generation
     380            0 :         )))
     381              :     }
     382            0 : }
     383              : 
     384            0 : async fn timeline_copy_handler(mut request: Request<Body>) -> Result<Response<Body>, ApiError> {
     385            0 :     check_permission(&request, None)?;
     386              : 
     387            0 :     let request_data: TimelineCopyRequest = json_request(&mut request).await?;
     388            0 :     let source_ttid = TenantTimelineId::new(
     389            0 :         parse_request_param(&request, "tenant_id")?,
     390            0 :         parse_request_param(&request, "source_timeline_id")?,
     391              :     );
     392              : 
     393            0 :     let global_timelines = get_global_timelines(&request);
     394            0 : 
     395            0 :     copy_timeline::handle_request(copy_timeline::Request{
     396            0 :         source_ttid,
     397            0 :         until_lsn: request_data.until_lsn,
     398            0 :         destination_ttid: TenantTimelineId::new(source_ttid.tenant_id, request_data.target_timeline_id),
     399            0 :     }, global_timelines)
     400            0 :         .instrument(info_span!("copy_timeline", from=%source_ttid, to=%request_data.target_timeline_id, until_lsn=%request_data.until_lsn))
     401            0 :         .await
     402            0 :         .map_err(ApiError::InternalServerError)?;
     403              : 
     404            0 :     json_response(StatusCode::OK, ())
     405            0 : }
     406              : 
     407            0 : async fn patch_control_file_handler(
     408            0 :     mut request: Request<Body>,
     409            0 : ) -> Result<Response<Body>, ApiError> {
     410            0 :     check_permission(&request, None)?;
     411              : 
     412            0 :     let ttid = TenantTimelineId::new(
     413            0 :         parse_request_param(&request, "tenant_id")?,
     414            0 :         parse_request_param(&request, "timeline_id")?,
     415              :     );
     416              : 
     417            0 :     let global_timelines = get_global_timelines(&request);
     418            0 :     let tli = global_timelines.get(ttid).map_err(ApiError::from)?;
     419              : 
     420            0 :     let patch_request: patch_control_file::Request = json_request(&mut request).await?;
     421            0 :     let response = patch_control_file::handle_request(tli, patch_request)
     422            0 :         .await
     423            0 :         .map_err(ApiError::InternalServerError)?;
     424              : 
     425            0 :     json_response(StatusCode::OK, response)
     426            0 : }
     427              : 
     428              : /// Force persist control file.
     429            0 : async fn timeline_checkpoint_handler(request: Request<Body>) -> Result<Response<Body>, ApiError> {
     430            0 :     check_permission(&request, None)?;
     431              : 
     432            0 :     let ttid = TenantTimelineId::new(
     433            0 :         parse_request_param(&request, "tenant_id")?,
     434            0 :         parse_request_param(&request, "timeline_id")?,
     435              :     );
     436              : 
     437            0 :     let global_timelines = get_global_timelines(&request);
     438            0 :     let tli = global_timelines.get(ttid)?;
     439            0 :     tli.write_shared_state()
     440            0 :         .await
     441              :         .sk
     442            0 :         .state_mut()
     443            0 :         .flush()
     444            0 :         .await
     445            0 :         .map_err(ApiError::InternalServerError)?;
     446            0 :     json_response(StatusCode::OK, ())
     447            0 : }
     448              : 
     449            0 : async fn timeline_digest_handler(request: Request<Body>) -> Result<Response<Body>, ApiError> {
     450            0 :     let ttid = TenantTimelineId::new(
     451            0 :         parse_request_param(&request, "tenant_id")?,
     452            0 :         parse_request_param(&request, "timeline_id")?,
     453              :     );
     454            0 :     check_permission(&request, Some(ttid.tenant_id))?;
     455              : 
     456            0 :     let global_timelines = get_global_timelines(&request);
     457            0 :     let from_lsn: Option<Lsn> = parse_query_param(&request, "from_lsn")?;
     458            0 :     let until_lsn: Option<Lsn> = parse_query_param(&request, "until_lsn")?;
     459              : 
     460            0 :     let request = TimelineDigestRequest {
     461            0 :         from_lsn: from_lsn.ok_or(ApiError::BadRequest(anyhow::anyhow!(
     462            0 :             "from_lsn is required"
     463            0 :         )))?,
     464            0 :         until_lsn: until_lsn.ok_or(ApiError::BadRequest(anyhow::anyhow!(
     465            0 :             "until_lsn is required"
     466            0 :         )))?,
     467              :     };
     468              : 
     469            0 :     let tli = global_timelines.get(ttid).map_err(ApiError::from)?;
     470            0 :     let tli = tli
     471            0 :         .wal_residence_guard()
     472            0 :         .await
     473            0 :         .map_err(ApiError::InternalServerError)?;
     474              : 
     475            0 :     let response = debug_dump::calculate_digest(&tli, request)
     476            0 :         .await
     477            0 :         .map_err(ApiError::InternalServerError)?;
     478            0 :     json_response(StatusCode::OK, response)
     479            0 : }
     480              : 
     481              : /// Unevict timeline and remove uploaded partial segment(s) from the remote storage.
     482              : /// Successfull response returns list of segments existed before the deletion.
     483              : /// Aimed for one-off usage not normally needed.
     484            0 : async fn timeline_backup_partial_reset(request: Request<Body>) -> Result<Response<Body>, ApiError> {
     485            0 :     let ttid = TenantTimelineId::new(
     486            0 :         parse_request_param(&request, "tenant_id")?,
     487            0 :         parse_request_param(&request, "timeline_id")?,
     488              :     );
     489            0 :     check_permission(&request, Some(ttid.tenant_id))?;
     490              : 
     491            0 :     let global_timelines = get_global_timelines(&request);
     492            0 :     let tli = global_timelines.get(ttid).map_err(ApiError::from)?;
     493              : 
     494            0 :     let response = tli
     495            0 :         .backup_partial_reset()
     496            0 :         .await
     497            0 :         .map_err(ApiError::InternalServerError)?;
     498            0 :     json_response(StatusCode::OK, response)
     499            0 : }
     500              : 
     501              : /// Make term at least as high as one in request. If one in request is None,
     502              : /// increment current one.
     503            0 : async fn timeline_term_bump_handler(
     504            0 :     mut request: Request<Body>,
     505            0 : ) -> Result<Response<Body>, ApiError> {
     506            0 :     let ttid = TenantTimelineId::new(
     507            0 :         parse_request_param(&request, "tenant_id")?,
     508            0 :         parse_request_param(&request, "timeline_id")?,
     509              :     );
     510            0 :     check_permission(&request, Some(ttid.tenant_id))?;
     511              : 
     512            0 :     let request_data: TimelineTermBumpRequest = json_request(&mut request).await?;
     513              : 
     514            0 :     let global_timelines = get_global_timelines(&request);
     515            0 :     let tli = global_timelines.get(ttid).map_err(ApiError::from)?;
     516            0 :     let response = tli
     517            0 :         .term_bump(request_data.term)
     518            0 :         .await
     519            0 :         .map_err(ApiError::InternalServerError)?;
     520              : 
     521            0 :     json_response(StatusCode::OK, response)
     522            0 : }
     523              : 
     524              : /// Used only in tests to hand craft required data.
     525            0 : async fn record_safekeeper_info(mut request: Request<Body>) -> Result<Response<Body>, ApiError> {
     526            0 :     let ttid = TenantTimelineId::new(
     527            0 :         parse_request_param(&request, "tenant_id")?,
     528            0 :         parse_request_param(&request, "timeline_id")?,
     529              :     );
     530            0 :     check_permission(&request, Some(ttid.tenant_id))?;
     531            0 :     let sk_info: SkTimelineInfo = json_request(&mut request).await?;
     532            0 :     let proto_sk_info = SafekeeperTimelineInfo {
     533            0 :         safekeeper_id: 0,
     534            0 :         tenant_timeline_id: Some(ProtoTenantTimelineId {
     535            0 :             tenant_id: ttid.tenant_id.as_ref().to_owned(),
     536            0 :             timeline_id: ttid.timeline_id.as_ref().to_owned(),
     537            0 :         }),
     538            0 :         term: sk_info.term.unwrap_or(0),
     539            0 :         last_log_term: sk_info.last_log_term.unwrap_or(0),
     540            0 :         flush_lsn: sk_info.flush_lsn.0,
     541            0 :         commit_lsn: sk_info.commit_lsn.0,
     542            0 :         remote_consistent_lsn: sk_info.remote_consistent_lsn.0,
     543            0 :         peer_horizon_lsn: sk_info.peer_horizon_lsn.0,
     544            0 :         safekeeper_connstr: sk_info.safekeeper_connstr.unwrap_or_else(|| "".to_owned()),
     545            0 :         http_connstr: sk_info.http_connstr.unwrap_or_else(|| "".to_owned()),
     546            0 :         https_connstr: sk_info.https_connstr,
     547            0 :         backup_lsn: sk_info.backup_lsn.0,
     548            0 :         local_start_lsn: sk_info.local_start_lsn.0,
     549            0 :         availability_zone: None,
     550            0 :         standby_horizon: sk_info.standby_horizon.0,
     551            0 :     };
     552            0 : 
     553            0 :     let global_timelines = get_global_timelines(&request);
     554            0 :     let tli = global_timelines.get(ttid).map_err(ApiError::from)?;
     555            0 :     tli.record_safekeeper_info(proto_sk_info)
     556            0 :         .await
     557            0 :         .map_err(ApiError::InternalServerError)?;
     558              : 
     559            0 :     json_response(StatusCode::OK, ())
     560            0 : }
     561              : 
     562            0 : fn parse_kv_str<E: fmt::Display, T: FromStr<Err = E>>(k: &str, v: &str) -> Result<T, ApiError> {
     563            0 :     v.parse()
     564            0 :         .map_err(|e| ApiError::BadRequest(anyhow::anyhow!("cannot parse {k}: {e}")))
     565            0 : }
     566              : 
     567              : /// Dump debug info about all available safekeeper state.
     568            0 : async fn dump_debug_handler(mut request: Request<Body>) -> Result<Response<Body>, ApiError> {
     569            0 :     check_permission(&request, None)?;
     570            0 :     ensure_no_body(&mut request).await?;
     571              : 
     572            0 :     let mut dump_all: Option<bool> = None;
     573            0 :     let mut dump_control_file: Option<bool> = None;
     574            0 :     let mut dump_memory: Option<bool> = None;
     575            0 :     let mut dump_disk_content: Option<bool> = None;
     576            0 :     let mut dump_term_history: Option<bool> = None;
     577            0 :     let mut dump_wal_last_modified: Option<bool> = None;
     578            0 :     let mut tenant_id: Option<TenantId> = None;
     579            0 :     let mut timeline_id: Option<TimelineId> = None;
     580            0 : 
     581            0 :     let query = request.uri().query().unwrap_or("");
     582            0 :     let mut values = url::form_urlencoded::parse(query.as_bytes());
     583              : 
     584            0 :     for (k, v) in &mut values {
     585            0 :         match k.as_ref() {
     586            0 :             "dump_all" => dump_all = Some(parse_kv_str(&k, &v)?),
     587            0 :             "dump_control_file" => dump_control_file = Some(parse_kv_str(&k, &v)?),
     588            0 :             "dump_memory" => dump_memory = Some(parse_kv_str(&k, &v)?),
     589            0 :             "dump_disk_content" => dump_disk_content = Some(parse_kv_str(&k, &v)?),
     590            0 :             "dump_term_history" => dump_term_history = Some(parse_kv_str(&k, &v)?),
     591            0 :             "dump_wal_last_modified" => dump_wal_last_modified = Some(parse_kv_str(&k, &v)?),
     592            0 :             "tenant_id" => tenant_id = Some(parse_kv_str(&k, &v)?),
     593            0 :             "timeline_id" => timeline_id = Some(parse_kv_str(&k, &v)?),
     594            0 :             _ => Err(ApiError::BadRequest(anyhow::anyhow!(
     595            0 :                 "Unknown query parameter: {}",
     596            0 :                 k
     597            0 :             )))?,
     598              :         }
     599              :     }
     600              : 
     601            0 :     let dump_all = dump_all.unwrap_or(false);
     602            0 :     let dump_control_file = dump_control_file.unwrap_or(dump_all);
     603            0 :     let dump_memory = dump_memory.unwrap_or(dump_all);
     604            0 :     let dump_disk_content = dump_disk_content.unwrap_or(dump_all);
     605            0 :     let dump_term_history = dump_term_history.unwrap_or(true);
     606            0 :     let dump_wal_last_modified = dump_wal_last_modified.unwrap_or(dump_all);
     607            0 : 
     608            0 :     let global_timelines = get_global_timelines(&request);
     609            0 : 
     610            0 :     let args = debug_dump::Args {
     611            0 :         dump_all,
     612            0 :         dump_control_file,
     613            0 :         dump_memory,
     614            0 :         dump_disk_content,
     615            0 :         dump_term_history,
     616            0 :         dump_wal_last_modified,
     617            0 :         tenant_id,
     618            0 :         timeline_id,
     619            0 :     };
     620              : 
     621            0 :     let resp = debug_dump::build(args, global_timelines)
     622            0 :         .await
     623            0 :         .map_err(ApiError::InternalServerError)?;
     624              : 
     625            0 :     let started_at = std::time::Instant::now();
     626            0 : 
     627            0 :     let (tx, rx) = mpsc::channel(1);
     628            0 : 
     629            0 :     let body = Body::wrap_stream(ReceiverStream::new(rx));
     630            0 : 
     631            0 :     let mut writer = ChannelWriter::new(128 * 1024, tx);
     632            0 : 
     633            0 :     let response = Response::builder()
     634            0 :         .status(200)
     635            0 :         .header(hyper::header::CONTENT_TYPE, "application/octet-stream")
     636            0 :         .body(body)
     637            0 :         .unwrap();
     638              : 
     639            0 :     let span = info_span!("blocking");
     640            0 :     tokio::task::spawn_blocking(move || {
     641            0 :         let _span = span.entered();
     642            0 : 
     643            0 :         let res = serde_json::to_writer(&mut writer, &resp)
     644            0 :             .map_err(std::io::Error::from)
     645            0 :             .and_then(|_| writer.flush());
     646            0 : 
     647            0 :         match res {
     648              :             Ok(()) => {
     649            0 :                 tracing::info!(
     650            0 :                     bytes = writer.flushed_bytes(),
     651            0 :                     elapsed_ms = started_at.elapsed().as_millis(),
     652            0 :                     "responded /v1/debug_dump"
     653              :                 );
     654              :             }
     655            0 :             Err(e) => {
     656            0 :                 tracing::warn!("failed to write out /v1/debug_dump response: {e:#}");
     657              :                 // semantics of this error are quite... unclear. we want to error the stream out to
     658              :                 // abort the response to somehow notify the client that we failed.
     659              :                 //
     660              :                 // though, most likely the reason for failure is that the receiver is already gone.
     661            0 :                 drop(
     662            0 :                     writer
     663            0 :                         .tx
     664            0 :                         .blocking_send(Err(std::io::ErrorKind::BrokenPipe.into())),
     665            0 :                 );
     666              :             }
     667              :         }
     668            0 :     });
     669            0 : 
     670            0 :     Ok(response)
     671            0 : }
     672              : 
     673              : /// Safekeeper http router.
     674            0 : pub fn make_router(
     675            0 :     conf: Arc<SafeKeeperConf>,
     676            0 :     global_timelines: Arc<GlobalTimelines>,
     677            0 : ) -> RouterBuilder<hyper::Body, ApiError> {
     678            0 :     let mut router = endpoint::make_router();
     679            0 :     if conf.http_auth.is_some() {
     680            0 :         router = router.middleware(auth_middleware(|request| {
     681              :             const ALLOWLIST_ROUTES: &[&str] =
     682              :                 &["/v1/status", "/metrics", "/profile/cpu", "/profile/heap"];
     683            0 :             if ALLOWLIST_ROUTES.contains(&request.uri().path()) {
     684            0 :                 None
     685              :             } else {
     686              :                 // Option<Arc<SwappableJwtAuth>> is always provided as data below, hence unwrap().
     687            0 :                 request
     688            0 :                     .data::<Option<Arc<SwappableJwtAuth>>>()
     689            0 :                     .unwrap()
     690            0 :                     .as_deref()
     691              :             }
     692            0 :         }))
     693            0 :     }
     694              : 
     695              :     // NB: on any changes do not forget to update the OpenAPI spec
     696              :     // located nearby (/safekeeper/src/http/openapi_spec.yaml).
     697            0 :     let auth = conf.http_auth.clone();
     698            0 :     router
     699            0 :         .data(conf)
     700            0 :         .data(global_timelines)
     701            0 :         .data(auth)
     702            0 :         .get("/metrics", |r| request_span(r, prometheus_metrics_handler))
     703            0 :         .get("/profile/cpu", |r| request_span(r, profile_cpu_handler))
     704            0 :         .get("/profile/heap", |r| request_span(r, profile_heap_handler))
     705            0 :         .get("/v1/status", |r| request_span(r, status_handler))
     706            0 :         .put("/v1/failpoints", |r| {
     707            0 :             request_span(r, move |r| async {
     708            0 :                 check_permission(&r, None)?;
     709            0 :                 let cancel = CancellationToken::new();
     710            0 :                 failpoints_handler(r, cancel).await
     711            0 :             })
     712            0 :         })
     713            0 :         .get("/v1/utilization", |r| request_span(r, utilization_handler))
     714            0 :         .delete("/v1/tenant/:tenant_id", |r| {
     715            0 :             request_span(r, tenant_delete_handler)
     716            0 :         })
     717            0 :         // Will be used in the future instead of implicit timeline creation
     718            0 :         .post("/v1/tenant/timeline", |r| {
     719            0 :             request_span(r, timeline_create_handler)
     720            0 :         })
     721            0 :         .get("/v1/tenant/timeline", |r| {
     722            0 :             request_span(r, timeline_list_handler)
     723            0 :         })
     724            0 :         .get("/v1/tenant/:tenant_id/timeline/:timeline_id", |r| {
     725            0 :             request_span(r, timeline_status_handler)
     726            0 :         })
     727            0 :         .delete("/v1/tenant/:tenant_id/timeline/:timeline_id", |r| {
     728            0 :             request_span(r, timeline_delete_handler)
     729            0 :         })
     730            0 :         .post("/v1/pull_timeline", |r| {
     731            0 :             request_span(r, timeline_pull_handler)
     732            0 :         })
     733            0 :         .put("/v1/tenant/:tenant_id/timeline/:timeline_id/exclude", |r| {
     734            0 :             request_span(r, timeline_exclude_handler)
     735            0 :         })
     736            0 :         .get(
     737            0 :             "/v1/tenant/:tenant_id/timeline/:timeline_id/snapshot/:destination_id",
     738            0 :             |r| request_span(r, timeline_snapshot_handler),
     739            0 :         )
     740            0 :         .put(
     741            0 :             "/v1/tenant/:tenant_id/timeline/:timeline_id/membership",
     742            0 :             |r| request_span(r, timeline_membership_handler),
     743            0 :         )
     744            0 :         .post(
     745            0 :             "/v1/tenant/:tenant_id/timeline/:source_timeline_id/copy",
     746            0 :             |r| request_span(r, timeline_copy_handler),
     747            0 :         )
     748            0 :         .patch(
     749            0 :             "/v1/tenant/:tenant_id/timeline/:timeline_id/control_file",
     750            0 :             |r| request_span(r, patch_control_file_handler),
     751            0 :         )
     752            0 :         .post(
     753            0 :             "/v1/tenant/:tenant_id/timeline/:timeline_id/checkpoint",
     754            0 :             |r| request_span(r, timeline_checkpoint_handler),
     755            0 :         )
     756            0 :         .get("/v1/tenant/:tenant_id/timeline/:timeline_id/digest", |r| {
     757            0 :             request_span(r, timeline_digest_handler)
     758            0 :         })
     759            0 :         .post(
     760            0 :             "/v1/tenant/:tenant_id/timeline/:timeline_id/backup_partial_reset",
     761            0 :             |r| request_span(r, timeline_backup_partial_reset),
     762            0 :         )
     763            0 :         .post(
     764            0 :             "/v1/tenant/:tenant_id/timeline/:timeline_id/term_bump",
     765            0 :             |r| request_span(r, timeline_term_bump_handler),
     766            0 :         )
     767            0 :         .post("/v1/record_safekeeper_info/:tenant_id/:timeline_id", |r| {
     768            0 :             request_span(r, record_safekeeper_info)
     769            0 :         })
     770            0 :         .get("/v1/debug_dump", |r| request_span(r, dump_debug_handler))
     771            0 : }
     772              : 
     773              : #[cfg(test)]
     774              : mod tests {
     775              :     use super::*;
     776              : 
     777              :     #[test]
     778            1 :     fn test_term_switch_entry_api_serialize() {
     779            1 :         let state = AcceptorStateStatus {
     780            1 :             term: 1,
     781            1 :             epoch: 1,
     782            1 :             term_history: vec![TermSwitchApiEntry {
     783            1 :                 term: 1,
     784            1 :                 lsn: Lsn(0x16FFDDDD),
     785            1 :             }],
     786            1 :         };
     787            1 :         let json = serde_json::to_string(&state).unwrap();
     788            1 :         assert_eq!(
     789            1 :             json,
     790            1 :             "{\"term\":1,\"epoch\":1,\"term_history\":[{\"term\":1,\"lsn\":\"0/16FFDDDD\"}]}"
     791            1 :         );
     792            1 :     }
     793              : }
        

Generated by: LCOV version 2.1-beta