LCOV - code coverage report
Current view: top level - safekeeper/src/http - routes.rs (source / functions) Coverage Total Hit
Test: 1e20c4f2b28aa592527961bb32170ebbd2c9172f.info Lines: 2.1 % 565 12
Test Date: 2025-07-16 12:29:03 Functions: 1.1 % 87 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              : 
     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              :     };
     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 = pull_timeline::handle_request(
     245            0 :         data,
     246            0 :         conf.sk_auth_token.clone(),
     247            0 :         ca_certs,
     248            0 :         global_timelines,
     249            0 :         false,
     250            0 :     )
     251            0 :     .await?;
     252            0 :     json_response(StatusCode::OK, resp)
     253            0 : }
     254              : 
     255              : /// Stream tar archive with all timeline data.
     256            0 : async fn timeline_snapshot_handler(request: Request<Body>) -> Result<Response<Body>, ApiError> {
     257            0 :     let destination = parse_request_param(&request, "destination_id")?;
     258            0 :     let ttid = TenantTimelineId::new(
     259            0 :         parse_request_param(&request, "tenant_id")?,
     260            0 :         parse_request_param(&request, "timeline_id")?,
     261              :     );
     262            0 :     check_permission(&request, Some(ttid.tenant_id))?;
     263              : 
     264            0 :     let global_timelines = get_global_timelines(&request);
     265            0 :     let tli = global_timelines.get(ttid).map_err(ApiError::from)?;
     266            0 :     let storage = global_timelines.get_wal_backup().get_storage();
     267              : 
     268              :     // To stream the body use wrap_stream which wants Stream of Result<Bytes>,
     269              :     // so create the chan and write to it in another task.
     270            0 :     let (tx, rx) = mpsc::channel(1);
     271              : 
     272            0 :     let conf = get_conf(&request);
     273            0 :     task::spawn(pull_timeline::stream_snapshot(
     274            0 :         tli,
     275            0 :         conf.my_id,
     276            0 :         destination,
     277            0 :         tx,
     278            0 :         storage,
     279              :     ));
     280              : 
     281            0 :     let rx_stream = ReceiverStream::new(rx);
     282            0 :     let body = Body::wrap_stream(rx_stream);
     283              : 
     284            0 :     let response = Response::builder()
     285            0 :         .status(200)
     286            0 :         .header(hyper::header::CONTENT_TYPE, "application/octet-stream")
     287            0 :         .body(body)
     288            0 :         .unwrap();
     289              : 
     290            0 :     Ok(response)
     291            0 : }
     292              : 
     293              : /// Error type for delete_or_exclude: either generation conflict or something
     294              : /// internal.
     295              : #[derive(thiserror::Error, Debug)]
     296              : pub enum DeleteOrExcludeError {
     297              :     #[error("refused to switch into excluding mconf {requested}, current: {current}")]
     298              :     Conflict {
     299              :         requested: membership::Configuration,
     300              :         current: membership::Configuration,
     301              :     },
     302              :     #[error(transparent)]
     303              :     Other(#[from] anyhow::Error),
     304              : }
     305              : 
     306              : /// Convert DeleteOrExcludeError to ApiError.
     307              : impl From<DeleteOrExcludeError> for ApiError {
     308            0 :     fn from(de: DeleteOrExcludeError) -> ApiError {
     309            0 :         match de {
     310              :             DeleteOrExcludeError::Conflict {
     311              :                 requested: _,
     312              :                 current: _,
     313            0 :             } => ApiError::Conflict(de.to_string()),
     314            0 :             DeleteOrExcludeError::Other(e) => ApiError::InternalServerError(e),
     315              :         }
     316            0 :     }
     317              : }
     318              : 
     319              : /// Remove timeline locally after this node has been excluded from the
     320              : /// membership configuration. The body is the same as in the membership endpoint
     321              : /// -- conf where node is excluded -- and in principle single ep could be used
     322              : /// for both actions, but since this is a data deletion op let's keep them
     323              : /// separate.
     324            0 : async fn timeline_exclude_handler(mut request: Request<Body>) -> Result<Response<Body>, ApiError> {
     325            0 :     let ttid = TenantTimelineId::new(
     326            0 :         parse_request_param(&request, "tenant_id")?,
     327            0 :         parse_request_param(&request, "timeline_id")?,
     328              :     );
     329            0 :     check_permission(&request, Some(ttid.tenant_id))?;
     330              : 
     331            0 :     let global_timelines = get_global_timelines(&request);
     332            0 :     let data: models::TimelineMembershipSwitchRequest = json_request(&mut request).await?;
     333            0 :     let my_id = get_conf(&request).my_id;
     334              :     // If request doesn't exclude us, membership switch endpoint should be used
     335              :     // instead.
     336            0 :     if data.mconf.contains(my_id) {
     337            0 :         return Err(ApiError::Forbidden(format!(
     338            0 :             "refused to switch into {}, node {} is member of it",
     339            0 :             data.mconf, my_id
     340            0 :         )));
     341            0 :     }
     342            0 :     let action = DeleteOrExclude::Exclude(data.mconf);
     343              : 
     344            0 :     let resp = global_timelines
     345            0 :         .delete_or_exclude(&ttid, action)
     346            0 :         .await
     347            0 :         .map_err(ApiError::from)?;
     348            0 :     json_response(StatusCode::OK, resp)
     349            0 : }
     350              : 
     351              : /// Consider switching timeline membership configuration to the provided one.
     352            0 : async fn timeline_membership_handler(
     353            0 :     mut request: Request<Body>,
     354            0 : ) -> Result<Response<Body>, ApiError> {
     355            0 :     let ttid = TenantTimelineId::new(
     356            0 :         parse_request_param(&request, "tenant_id")?,
     357            0 :         parse_request_param(&request, "timeline_id")?,
     358              :     );
     359            0 :     check_permission(&request, Some(ttid.tenant_id))?;
     360              : 
     361            0 :     let global_timelines = get_global_timelines(&request);
     362            0 :     let tli = global_timelines.get(ttid).map_err(ApiError::from)?;
     363              : 
     364            0 :     let data: models::TimelineMembershipSwitchRequest = json_request(&mut request).await?;
     365            0 :     let my_id = get_conf(&request).my_id;
     366              :     // If request excludes us, exclude endpoint should be used instead.
     367            0 :     if !data.mconf.contains(my_id) {
     368            0 :         return Err(ApiError::Forbidden(format!(
     369            0 :             "refused to switch into {}, node {} is not a member of it",
     370            0 :             data.mconf, my_id
     371            0 :         )));
     372            0 :     }
     373            0 :     let req_gen = data.mconf.generation;
     374            0 :     let response = tli
     375            0 :         .membership_switch(data.mconf)
     376            0 :         .await
     377            0 :         .map_err(ApiError::InternalServerError)?;
     378              : 
     379              :     // Return 409 if request was ignored.
     380            0 :     if req_gen == response.current_conf.generation {
     381            0 :         json_response(StatusCode::OK, response)
     382              :     } else {
     383            0 :         Err(ApiError::Conflict(format!(
     384            0 :             "request to switch into {} ignored, current generation {}",
     385            0 :             req_gen, response.current_conf.generation
     386            0 :         )))
     387              :     }
     388            0 : }
     389              : 
     390            0 : async fn timeline_copy_handler(mut request: Request<Body>) -> Result<Response<Body>, ApiError> {
     391            0 :     check_permission(&request, None)?;
     392              : 
     393            0 :     let request_data: TimelineCopyRequest = json_request(&mut request).await?;
     394            0 :     let source_ttid = TenantTimelineId::new(
     395            0 :         parse_request_param(&request, "tenant_id")?,
     396            0 :         parse_request_param(&request, "source_timeline_id")?,
     397              :     );
     398              : 
     399            0 :     let global_timelines = get_global_timelines(&request);
     400            0 :     let wal_backup = global_timelines.get_wal_backup();
     401            0 :     let storage = wal_backup
     402            0 :         .get_storage()
     403            0 :         .ok_or(ApiError::BadRequest(anyhow::anyhow!(
     404            0 :             "Remote Storage is not configured"
     405            0 :         )))?;
     406              : 
     407            0 :     copy_timeline::handle_request(copy_timeline::Request{
     408            0 :         source_ttid,
     409            0 :         until_lsn: request_data.until_lsn,
     410            0 :         destination_ttid: TenantTimelineId::new(source_ttid.tenant_id, request_data.target_timeline_id),
     411            0 :     }, global_timelines, storage)
     412            0 :         .instrument(info_span!("copy_timeline", from=%source_ttid, to=%request_data.target_timeline_id, until_lsn=%request_data.until_lsn))
     413            0 :         .await
     414            0 :         .map_err(ApiError::InternalServerError)?;
     415              : 
     416            0 :     json_response(StatusCode::OK, ())
     417            0 : }
     418              : 
     419            0 : async fn patch_control_file_handler(
     420            0 :     mut request: Request<Body>,
     421            0 : ) -> Result<Response<Body>, ApiError> {
     422            0 :     check_permission(&request, None)?;
     423              : 
     424            0 :     let ttid = TenantTimelineId::new(
     425            0 :         parse_request_param(&request, "tenant_id")?,
     426            0 :         parse_request_param(&request, "timeline_id")?,
     427              :     );
     428              : 
     429            0 :     let global_timelines = get_global_timelines(&request);
     430            0 :     let tli = global_timelines.get(ttid).map_err(ApiError::from)?;
     431              : 
     432            0 :     let patch_request: patch_control_file::Request = json_request(&mut request).await?;
     433            0 :     let response = patch_control_file::handle_request(tli, patch_request)
     434            0 :         .await
     435            0 :         .map_err(ApiError::InternalServerError)?;
     436              : 
     437            0 :     json_response(StatusCode::OK, response)
     438            0 : }
     439              : 
     440              : /// Force persist control file.
     441            0 : async fn timeline_checkpoint_handler(request: Request<Body>) -> Result<Response<Body>, ApiError> {
     442            0 :     check_permission(&request, None)?;
     443              : 
     444            0 :     let ttid = TenantTimelineId::new(
     445            0 :         parse_request_param(&request, "tenant_id")?,
     446            0 :         parse_request_param(&request, "timeline_id")?,
     447              :     );
     448              : 
     449            0 :     let global_timelines = get_global_timelines(&request);
     450            0 :     let tli = global_timelines.get(ttid)?;
     451            0 :     tli.write_shared_state()
     452            0 :         .await
     453              :         .sk
     454            0 :         .state_mut()
     455            0 :         .flush()
     456            0 :         .await
     457            0 :         .map_err(ApiError::InternalServerError)?;
     458            0 :     json_response(StatusCode::OK, ())
     459            0 : }
     460              : 
     461            0 : async fn timeline_digest_handler(request: Request<Body>) -> Result<Response<Body>, ApiError> {
     462            0 :     let ttid = TenantTimelineId::new(
     463            0 :         parse_request_param(&request, "tenant_id")?,
     464            0 :         parse_request_param(&request, "timeline_id")?,
     465              :     );
     466            0 :     check_permission(&request, Some(ttid.tenant_id))?;
     467              : 
     468            0 :     let global_timelines = get_global_timelines(&request);
     469            0 :     let from_lsn: Option<Lsn> = parse_query_param(&request, "from_lsn")?;
     470            0 :     let until_lsn: Option<Lsn> = parse_query_param(&request, "until_lsn")?;
     471              : 
     472            0 :     let request = TimelineDigestRequest {
     473            0 :         from_lsn: from_lsn.ok_or(ApiError::BadRequest(anyhow::anyhow!(
     474            0 :             "from_lsn is required"
     475            0 :         )))?,
     476            0 :         until_lsn: until_lsn.ok_or(ApiError::BadRequest(anyhow::anyhow!(
     477            0 :             "until_lsn is required"
     478            0 :         )))?,
     479              :     };
     480              : 
     481            0 :     let tli = global_timelines.get(ttid).map_err(ApiError::from)?;
     482            0 :     let tli = tli
     483            0 :         .wal_residence_guard()
     484            0 :         .await
     485            0 :         .map_err(ApiError::InternalServerError)?;
     486              : 
     487            0 :     let response = debug_dump::calculate_digest(&tli, request)
     488            0 :         .await
     489            0 :         .map_err(ApiError::InternalServerError)?;
     490            0 :     json_response(StatusCode::OK, response)
     491            0 : }
     492              : 
     493              : /// Unevict timeline and remove uploaded partial segment(s) from the remote storage.
     494              : /// Successfull response returns list of segments existed before the deletion.
     495              : /// Aimed for one-off usage not normally needed.
     496            0 : async fn timeline_backup_partial_reset(request: Request<Body>) -> Result<Response<Body>, ApiError> {
     497            0 :     let ttid = TenantTimelineId::new(
     498            0 :         parse_request_param(&request, "tenant_id")?,
     499            0 :         parse_request_param(&request, "timeline_id")?,
     500              :     );
     501            0 :     check_permission(&request, Some(ttid.tenant_id))?;
     502              : 
     503            0 :     let global_timelines = get_global_timelines(&request);
     504            0 :     let tli = global_timelines.get(ttid).map_err(ApiError::from)?;
     505              : 
     506            0 :     let response = tli
     507            0 :         .backup_partial_reset()
     508            0 :         .await
     509            0 :         .map_err(ApiError::InternalServerError)?;
     510            0 :     json_response(StatusCode::OK, response)
     511            0 : }
     512              : 
     513              : /// Make term at least as high as one in request. If one in request is None,
     514              : /// increment current one.
     515            0 : async fn timeline_term_bump_handler(
     516            0 :     mut request: Request<Body>,
     517            0 : ) -> Result<Response<Body>, ApiError> {
     518            0 :     let ttid = TenantTimelineId::new(
     519            0 :         parse_request_param(&request, "tenant_id")?,
     520            0 :         parse_request_param(&request, "timeline_id")?,
     521              :     );
     522            0 :     check_permission(&request, Some(ttid.tenant_id))?;
     523              : 
     524            0 :     let request_data: TimelineTermBumpRequest = json_request(&mut request).await?;
     525              : 
     526            0 :     let global_timelines = get_global_timelines(&request);
     527            0 :     let tli = global_timelines.get(ttid).map_err(ApiError::from)?;
     528            0 :     let response = tli
     529            0 :         .term_bump(request_data.term)
     530            0 :         .await
     531            0 :         .map_err(ApiError::InternalServerError)?;
     532              : 
     533            0 :     json_response(StatusCode::OK, response)
     534            0 : }
     535              : 
     536              : /// Used only in tests to hand craft required data.
     537            0 : async fn record_safekeeper_info(mut request: Request<Body>) -> Result<Response<Body>, ApiError> {
     538            0 :     let ttid = TenantTimelineId::new(
     539            0 :         parse_request_param(&request, "tenant_id")?,
     540            0 :         parse_request_param(&request, "timeline_id")?,
     541              :     );
     542            0 :     check_permission(&request, Some(ttid.tenant_id))?;
     543            0 :     let sk_info: SkTimelineInfo = json_request(&mut request).await?;
     544            0 :     let proto_sk_info = SafekeeperTimelineInfo {
     545              :         safekeeper_id: 0,
     546            0 :         tenant_timeline_id: Some(ProtoTenantTimelineId {
     547            0 :             tenant_id: ttid.tenant_id.as_ref().to_owned(),
     548            0 :             timeline_id: ttid.timeline_id.as_ref().to_owned(),
     549            0 :         }),
     550            0 :         term: sk_info.term.unwrap_or(0),
     551            0 :         last_log_term: sk_info.last_log_term.unwrap_or(0),
     552            0 :         flush_lsn: sk_info.flush_lsn.0,
     553            0 :         commit_lsn: sk_info.commit_lsn.0,
     554            0 :         remote_consistent_lsn: sk_info.remote_consistent_lsn.0,
     555            0 :         peer_horizon_lsn: sk_info.peer_horizon_lsn.0,
     556            0 :         safekeeper_connstr: sk_info.safekeeper_connstr.unwrap_or_else(|| "".to_owned()),
     557            0 :         http_connstr: sk_info.http_connstr.unwrap_or_else(|| "".to_owned()),
     558            0 :         https_connstr: sk_info.https_connstr,
     559            0 :         backup_lsn: sk_info.backup_lsn.0,
     560            0 :         local_start_lsn: sk_info.local_start_lsn.0,
     561            0 :         availability_zone: None,
     562            0 :         standby_horizon: sk_info.standby_horizon.0,
     563              :     };
     564              : 
     565            0 :     let global_timelines = get_global_timelines(&request);
     566            0 :     let tli = global_timelines.get(ttid).map_err(ApiError::from)?;
     567            0 :     tli.record_safekeeper_info(proto_sk_info)
     568            0 :         .await
     569            0 :         .map_err(ApiError::InternalServerError)?;
     570              : 
     571            0 :     json_response(StatusCode::OK, ())
     572            0 : }
     573              : 
     574            0 : fn parse_kv_str<E: fmt::Display, T: FromStr<Err = E>>(k: &str, v: &str) -> Result<T, ApiError> {
     575            0 :     v.parse()
     576            0 :         .map_err(|e| ApiError::BadRequest(anyhow::anyhow!("cannot parse {k}: {e}")))
     577            0 : }
     578              : 
     579              : /// Dump debug info about all available safekeeper state.
     580            0 : async fn dump_debug_handler(mut request: Request<Body>) -> Result<Response<Body>, ApiError> {
     581            0 :     check_permission(&request, None)?;
     582            0 :     ensure_no_body(&mut request).await?;
     583              : 
     584            0 :     let mut dump_all: Option<bool> = None;
     585            0 :     let mut dump_control_file: Option<bool> = None;
     586            0 :     let mut dump_memory: Option<bool> = None;
     587            0 :     let mut dump_disk_content: Option<bool> = None;
     588            0 :     let mut dump_term_history: Option<bool> = None;
     589            0 :     let mut dump_wal_last_modified: Option<bool> = None;
     590            0 :     let mut tenant_id: Option<TenantId> = None;
     591            0 :     let mut timeline_id: Option<TimelineId> = None;
     592              : 
     593            0 :     let query = request.uri().query().unwrap_or("");
     594            0 :     let mut values = url::form_urlencoded::parse(query.as_bytes());
     595              : 
     596            0 :     for (k, v) in &mut values {
     597            0 :         match k.as_ref() {
     598            0 :             "dump_all" => dump_all = Some(parse_kv_str(&k, &v)?),
     599            0 :             "dump_control_file" => dump_control_file = Some(parse_kv_str(&k, &v)?),
     600            0 :             "dump_memory" => dump_memory = Some(parse_kv_str(&k, &v)?),
     601            0 :             "dump_disk_content" => dump_disk_content = Some(parse_kv_str(&k, &v)?),
     602            0 :             "dump_term_history" => dump_term_history = Some(parse_kv_str(&k, &v)?),
     603            0 :             "dump_wal_last_modified" => dump_wal_last_modified = Some(parse_kv_str(&k, &v)?),
     604            0 :             "tenant_id" => tenant_id = Some(parse_kv_str(&k, &v)?),
     605            0 :             "timeline_id" => timeline_id = Some(parse_kv_str(&k, &v)?),
     606            0 :             _ => Err(ApiError::BadRequest(anyhow::anyhow!(
     607            0 :                 "Unknown query parameter: {}",
     608            0 :                 k
     609            0 :             )))?,
     610              :         }
     611              :     }
     612              : 
     613            0 :     let dump_all = dump_all.unwrap_or(false);
     614            0 :     let dump_control_file = dump_control_file.unwrap_or(dump_all);
     615            0 :     let dump_memory = dump_memory.unwrap_or(dump_all);
     616            0 :     let dump_disk_content = dump_disk_content.unwrap_or(dump_all);
     617            0 :     let dump_term_history = dump_term_history.unwrap_or(true);
     618            0 :     let dump_wal_last_modified = dump_wal_last_modified.unwrap_or(dump_all);
     619              : 
     620            0 :     let global_timelines = get_global_timelines(&request);
     621              : 
     622            0 :     let args = debug_dump::Args {
     623            0 :         dump_all,
     624            0 :         dump_control_file,
     625            0 :         dump_memory,
     626            0 :         dump_disk_content,
     627            0 :         dump_term_history,
     628            0 :         dump_wal_last_modified,
     629            0 :         tenant_id,
     630            0 :         timeline_id,
     631            0 :     };
     632              : 
     633            0 :     let resp = debug_dump::build(args, global_timelines)
     634            0 :         .await
     635            0 :         .map_err(ApiError::InternalServerError)?;
     636              : 
     637            0 :     let started_at = std::time::Instant::now();
     638              : 
     639            0 :     let (tx, rx) = mpsc::channel(1);
     640              : 
     641            0 :     let body = Body::wrap_stream(ReceiverStream::new(rx));
     642              : 
     643            0 :     let mut writer = ChannelWriter::new(128 * 1024, tx);
     644              : 
     645            0 :     let response = Response::builder()
     646            0 :         .status(200)
     647            0 :         .header(hyper::header::CONTENT_TYPE, "application/octet-stream")
     648            0 :         .body(body)
     649            0 :         .unwrap();
     650              : 
     651            0 :     let span = info_span!("blocking");
     652            0 :     tokio::task::spawn_blocking(move || {
     653            0 :         let _span = span.entered();
     654              : 
     655            0 :         let res = serde_json::to_writer(&mut writer, &resp)
     656            0 :             .map_err(std::io::Error::from)
     657            0 :             .and_then(|_| writer.flush());
     658              : 
     659            0 :         match res {
     660              :             Ok(()) => {
     661            0 :                 tracing::info!(
     662            0 :                     bytes = writer.flushed_bytes(),
     663            0 :                     elapsed_ms = started_at.elapsed().as_millis(),
     664            0 :                     "responded /v1/debug_dump"
     665              :                 );
     666              :             }
     667            0 :             Err(e) => {
     668            0 :                 tracing::warn!("failed to write out /v1/debug_dump response: {e:#}");
     669              :                 // semantics of this error are quite... unclear. we want to error the stream out to
     670              :                 // abort the response to somehow notify the client that we failed.
     671              :                 //
     672              :                 // though, most likely the reason for failure is that the receiver is already gone.
     673            0 :                 drop(
     674            0 :                     writer
     675            0 :                         .tx
     676            0 :                         .blocking_send(Err(std::io::ErrorKind::BrokenPipe.into())),
     677              :                 );
     678              :             }
     679              :         }
     680            0 :     });
     681              : 
     682            0 :     Ok(response)
     683            0 : }
     684              : 
     685              : /// Safekeeper http router.
     686            0 : pub fn make_router(
     687            0 :     conf: Arc<SafeKeeperConf>,
     688            0 :     global_timelines: Arc<GlobalTimelines>,
     689            0 : ) -> RouterBuilder<hyper::Body, ApiError> {
     690            0 :     let mut router = endpoint::make_router();
     691            0 :     if conf.http_auth.is_some() {
     692            0 :         router = router.middleware(auth_middleware(|request| {
     693              :             const ALLOWLIST_ROUTES: &[&str] =
     694              :                 &["/v1/status", "/metrics", "/profile/cpu", "/profile/heap"];
     695            0 :             if ALLOWLIST_ROUTES.contains(&request.uri().path()) {
     696            0 :                 None
     697              :             } else {
     698              :                 // Option<Arc<SwappableJwtAuth>> is always provided as data below, hence unwrap().
     699            0 :                 request
     700            0 :                     .data::<Option<Arc<SwappableJwtAuth>>>()
     701            0 :                     .unwrap()
     702            0 :                     .as_deref()
     703              :             }
     704            0 :         }))
     705            0 :     }
     706              : 
     707            0 :     let force_metric_collection_on_scrape = conf.force_metric_collection_on_scrape;
     708              : 
     709            0 :     let prometheus_metrics_handler_wrapper =
     710            0 :         move |req| prometheus_metrics_handler(req, force_metric_collection_on_scrape);
     711              : 
     712              :     // NB: on any changes do not forget to update the OpenAPI spec
     713              :     // located nearby (/safekeeper/src/http/openapi_spec.yaml).
     714            0 :     let auth = conf.http_auth.clone();
     715            0 :     router
     716            0 :         .data(conf)
     717            0 :         .data(global_timelines)
     718            0 :         .data(auth)
     719            0 :         .get("/metrics", move |r| {
     720            0 :             request_span(r, prometheus_metrics_handler_wrapper)
     721            0 :         })
     722            0 :         .get("/profile/cpu", |r| request_span(r, profile_cpu_handler))
     723            0 :         .get("/profile/heap", |r| request_span(r, profile_heap_handler))
     724            0 :         .get("/v1/status", |r| request_span(r, status_handler))
     725            0 :         .put("/v1/failpoints", |r| {
     726            0 :             request_span(r, move |r| async {
     727            0 :                 check_permission(&r, None)?;
     728            0 :                 let cancel = CancellationToken::new();
     729            0 :                 failpoints_handler(r, cancel).await
     730            0 :             })
     731            0 :         })
     732            0 :         .get("/v1/utilization", |r| request_span(r, utilization_handler))
     733            0 :         .delete("/v1/tenant/:tenant_id", |r| {
     734            0 :             request_span(r, tenant_delete_handler)
     735            0 :         })
     736              :         // Will be used in the future instead of implicit timeline creation
     737            0 :         .post("/v1/tenant/timeline", |r| {
     738            0 :             request_span(r, timeline_create_handler)
     739            0 :         })
     740            0 :         .get("/v1/tenant/timeline", |r| {
     741            0 :             request_span(r, timeline_list_handler)
     742            0 :         })
     743            0 :         .get("/v1/tenant/:tenant_id/timeline/:timeline_id", |r| {
     744            0 :             request_span(r, timeline_status_handler)
     745            0 :         })
     746            0 :         .delete("/v1/tenant/:tenant_id/timeline/:timeline_id", |r| {
     747            0 :             request_span(r, timeline_delete_handler)
     748            0 :         })
     749            0 :         .post("/v1/pull_timeline", |r| {
     750            0 :             request_span(r, timeline_pull_handler)
     751            0 :         })
     752            0 :         .put("/v1/tenant/:tenant_id/timeline/:timeline_id/exclude", |r| {
     753            0 :             request_span(r, timeline_exclude_handler)
     754            0 :         })
     755            0 :         .get(
     756              :             "/v1/tenant/:tenant_id/timeline/:timeline_id/snapshot/:destination_id",
     757            0 :             |r| request_span(r, timeline_snapshot_handler),
     758              :         )
     759            0 :         .put(
     760              :             "/v1/tenant/:tenant_id/timeline/:timeline_id/membership",
     761            0 :             |r| request_span(r, timeline_membership_handler),
     762              :         )
     763            0 :         .post(
     764              :             "/v1/tenant/:tenant_id/timeline/:source_timeline_id/copy",
     765            0 :             |r| request_span(r, timeline_copy_handler),
     766              :         )
     767            0 :         .patch(
     768              :             "/v1/tenant/:tenant_id/timeline/:timeline_id/control_file",
     769            0 :             |r| request_span(r, patch_control_file_handler),
     770              :         )
     771            0 :         .post(
     772              :             "/v1/tenant/:tenant_id/timeline/:timeline_id/checkpoint",
     773            0 :             |r| request_span(r, timeline_checkpoint_handler),
     774              :         )
     775            0 :         .get("/v1/tenant/:tenant_id/timeline/:timeline_id/digest", |r| {
     776            0 :             request_span(r, timeline_digest_handler)
     777            0 :         })
     778            0 :         .post(
     779              :             "/v1/tenant/:tenant_id/timeline/:timeline_id/backup_partial_reset",
     780            0 :             |r| request_span(r, timeline_backup_partial_reset),
     781              :         )
     782            0 :         .post(
     783              :             "/v1/tenant/:tenant_id/timeline/:timeline_id/term_bump",
     784            0 :             |r| request_span(r, timeline_term_bump_handler),
     785              :         )
     786            0 :         .post("/v1/record_safekeeper_info/:tenant_id/:timeline_id", |r| {
     787            0 :             request_span(r, record_safekeeper_info)
     788            0 :         })
     789            0 :         .get("/v1/debug_dump", |r| request_span(r, dump_debug_handler))
     790            0 : }
     791              : 
     792              : #[cfg(test)]
     793              : mod tests {
     794              :     use super::*;
     795              : 
     796              :     #[test]
     797            1 :     fn test_term_switch_entry_api_serialize() {
     798            1 :         let state = AcceptorStateStatus {
     799            1 :             term: 1,
     800            1 :             epoch: 1,
     801            1 :             term_history: vec![TermSwitchApiEntry {
     802            1 :                 term: 1,
     803            1 :                 lsn: Lsn(0x16FFDDDD),
     804            1 :             }],
     805            1 :         };
     806            1 :         let json = serde_json::to_string(&state).unwrap();
     807            1 :         assert_eq!(
     808              :             json,
     809              :             "{\"term\":1,\"epoch\":1,\"term_history\":[{\"term\":1,\"lsn\":\"0/16FFDDDD\"}]}"
     810              :         );
     811            1 :     }
     812              : }
        

Generated by: LCOV version 2.1-beta