LCOV - code coverage report
Current view: top level - safekeeper/src/http - routes.rs (source / functions) Coverage Total Hit
Test: 47d527da5e8405637e322911c55c08727c2fd272.info Lines: 2.9 % 524 15
Test Date: 2025-01-16 17:37:50 Functions: 1.3 % 78 1

            Line data    Source code
       1              : use hyper::{Body, Request, Response, StatusCode};
       2              : use safekeeper_api::models;
       3              : use safekeeper_api::models::AcceptorStateStatus;
       4              : use safekeeper_api::models::SafekeeperStatus;
       5              : use safekeeper_api::models::TermSwitchApiEntry;
       6              : use safekeeper_api::models::TimelineStatus;
       7              : use safekeeper_api::ServerInfo;
       8              : use std::collections::HashMap;
       9              : use std::fmt;
      10              : use std::io::Write as _;
      11              : use std::str::FromStr;
      12              : use std::sync::Arc;
      13              : use storage_broker::proto::SafekeeperTimelineInfo;
      14              : use storage_broker::proto::TenantTimelineId as ProtoTenantTimelineId;
      15              : use tokio::sync::mpsc;
      16              : use tokio::task;
      17              : use tokio_stream::wrappers::ReceiverStream;
      18              : use tokio_util::sync::CancellationToken;
      19              : use tracing::{info_span, Instrument};
      20              : use utils::failpoint_support::failpoints_handler;
      21              : use utils::http::endpoint::{
      22              :     profile_cpu_handler, profile_heap_handler, prometheus_metrics_handler, request_span,
      23              :     ChannelWriter,
      24              : };
      25              : use utils::http::request::parse_query_param;
      26              : 
      27              : use postgres_ffi::WAL_SEGMENT_SIZE;
      28              : use safekeeper_api::models::{SkTimelineInfo, TimelineCopyRequest};
      29              : use safekeeper_api::models::{TimelineCreateRequest, TimelineTermBumpRequest};
      30              : use utils::{
      31              :     auth::SwappableJwtAuth,
      32              :     http::{
      33              :         endpoint::{self, auth_middleware, check_permission_with},
      34              :         error::ApiError,
      35              :         json::{json_request, json_response},
      36              :         request::{ensure_no_body, parse_request_param},
      37              :         RequestExt, RouterBuilder,
      38              :     },
      39              :     id::{TenantId, TenantTimelineId, TimelineId},
      40              :     lsn::Lsn,
      41              : };
      42              : 
      43              : use crate::debug_dump::TimelineDigestRequest;
      44              : use crate::safekeeper::TermLsn;
      45              : use crate::timelines_global_map::TimelineDeleteForceResult;
      46              : use crate::GlobalTimelines;
      47              : use crate::SafeKeeperConf;
      48              : use crate::{copy_timeline, debug_dump, patch_control_file, pull_timeline};
      49              : 
      50              : /// Healthcheck handler.
      51            0 : async fn status_handler(request: Request<Body>) -> Result<Response<Body>, ApiError> {
      52            0 :     check_permission(&request, None)?;
      53            0 :     let conf = get_conf(&request);
      54            0 :     let status = SafekeeperStatus { id: conf.my_id };
      55            0 :     json_response(StatusCode::OK, status)
      56            0 : }
      57              : 
      58            0 : fn get_conf(request: &Request<Body>) -> &SafeKeeperConf {
      59            0 :     request
      60            0 :         .data::<Arc<SafeKeeperConf>>()
      61            0 :         .expect("unknown state type")
      62            0 :         .as_ref()
      63            0 : }
      64              : 
      65            0 : fn get_global_timelines(request: &Request<Body>) -> Arc<GlobalTimelines> {
      66            0 :     request
      67            0 :         .data::<Arc<GlobalTimelines>>()
      68            0 :         .expect("unknown state type")
      69            0 :         .clone()
      70            0 : }
      71              : 
      72            0 : fn check_permission(request: &Request<Body>, tenant_id: Option<TenantId>) -> Result<(), ApiError> {
      73            0 :     check_permission_with(request, |claims| {
      74            0 :         crate::auth::check_permission(claims, tenant_id)
      75            0 :     })
      76            0 : }
      77              : 
      78              : /// Deactivates all timelines for the tenant and removes its data directory.
      79              : /// See `timeline_delete_handler`.
      80            0 : async fn tenant_delete_handler(mut request: Request<Body>) -> Result<Response<Body>, ApiError> {
      81            0 :     let tenant_id = parse_request_param(&request, "tenant_id")?;
      82            0 :     let only_local = parse_query_param(&request, "only_local")?.unwrap_or(false);
      83            0 :     check_permission(&request, Some(tenant_id))?;
      84            0 :     ensure_no_body(&mut request).await?;
      85            0 :     let global_timelines = get_global_timelines(&request);
      86              :     // FIXME: `delete_force_all_for_tenant` can return an error for multiple different reasons;
      87              :     // Using an `InternalServerError` should be fixed when the types support it
      88            0 :     let delete_info = global_timelines
      89            0 :         .delete_force_all_for_tenant(&tenant_id, only_local)
      90            0 :         .await
      91            0 :         .map_err(ApiError::InternalServerError)?;
      92            0 :     json_response(
      93            0 :         StatusCode::OK,
      94            0 :         delete_info
      95            0 :             .iter()
      96            0 :             .map(|(ttid, resp)| (format!("{}", ttid.timeline_id), *resp))
      97            0 :             .collect::<HashMap<String, TimelineDeleteForceResult>>(),
      98            0 :     )
      99            0 : }
     100              : 
     101            0 : async fn timeline_create_handler(mut request: Request<Body>) -> Result<Response<Body>, ApiError> {
     102            0 :     let request_data: TimelineCreateRequest = json_request(&mut request).await?;
     103              : 
     104            0 :     let ttid = TenantTimelineId {
     105            0 :         tenant_id: request_data.tenant_id,
     106            0 :         timeline_id: request_data.timeline_id,
     107            0 :     };
     108            0 :     check_permission(&request, Some(ttid.tenant_id))?;
     109              : 
     110            0 :     let server_info = ServerInfo {
     111            0 :         pg_version: request_data.pg_version,
     112            0 :         system_id: request_data.system_id.unwrap_or(0),
     113            0 :         wal_seg_size: request_data.wal_seg_size.unwrap_or(WAL_SEGMENT_SIZE as u32),
     114            0 :     };
     115            0 :     let global_timelines = get_global_timelines(&request);
     116            0 :     global_timelines
     117            0 :         .create(
     118            0 :             ttid,
     119            0 :             request_data.mconf,
     120            0 :             server_info,
     121            0 :             request_data.start_lsn,
     122            0 :             request_data.commit_lsn.unwrap_or(request_data.start_lsn),
     123            0 :         )
     124            0 :         .await
     125            0 :         .map_err(ApiError::InternalServerError)?;
     126              : 
     127            0 :     json_response(StatusCode::OK, ())
     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              :     // FIXME: `delete_force` can fail from both internal errors and bad requests. Add better
     215              :     // error handling here when we're able to.
     216            0 :     let resp = global_timelines
     217            0 :         .delete(&ttid, only_local)
     218            0 :         .await
     219            0 :         .map_err(ApiError::InternalServerError)?;
     220            0 :     json_response(StatusCode::OK, resp)
     221            0 : }
     222              : 
     223              : /// Pull timeline from peer safekeeper instances.
     224            0 : async fn timeline_pull_handler(mut request: Request<Body>) -> Result<Response<Body>, ApiError> {
     225            0 :     check_permission(&request, None)?;
     226              : 
     227            0 :     let data: pull_timeline::Request = json_request(&mut request).await?;
     228            0 :     let conf = get_conf(&request);
     229            0 :     let global_timelines = get_global_timelines(&request);
     230              : 
     231            0 :     let resp = pull_timeline::handle_request(data, conf.sk_auth_token.clone(), global_timelines)
     232            0 :         .await
     233            0 :         .map_err(ApiError::InternalServerError)?;
     234            0 :     json_response(StatusCode::OK, resp)
     235            0 : }
     236              : 
     237              : /// Stream tar archive with all timeline data.
     238            0 : async fn timeline_snapshot_handler(request: Request<Body>) -> Result<Response<Body>, ApiError> {
     239            0 :     let destination = parse_request_param(&request, "destination_id")?;
     240            0 :     let ttid = TenantTimelineId::new(
     241            0 :         parse_request_param(&request, "tenant_id")?,
     242            0 :         parse_request_param(&request, "timeline_id")?,
     243              :     );
     244            0 :     check_permission(&request, Some(ttid.tenant_id))?;
     245              : 
     246            0 :     let global_timelines = get_global_timelines(&request);
     247            0 :     let tli = global_timelines.get(ttid).map_err(ApiError::from)?;
     248              : 
     249              :     // To stream the body use wrap_stream which wants Stream of Result<Bytes>,
     250              :     // so create the chan and write to it in another task.
     251            0 :     let (tx, rx) = mpsc::channel(1);
     252            0 : 
     253            0 :     let conf = get_conf(&request);
     254            0 :     task::spawn(pull_timeline::stream_snapshot(
     255            0 :         tli,
     256            0 :         conf.my_id,
     257            0 :         destination,
     258            0 :         tx,
     259            0 :     ));
     260            0 : 
     261            0 :     let rx_stream = ReceiverStream::new(rx);
     262            0 :     let body = Body::wrap_stream(rx_stream);
     263            0 : 
     264            0 :     let response = Response::builder()
     265            0 :         .status(200)
     266            0 :         .header(hyper::header::CONTENT_TYPE, "application/octet-stream")
     267            0 :         .body(body)
     268            0 :         .unwrap();
     269            0 : 
     270            0 :     Ok(response)
     271            0 : }
     272              : 
     273              : /// Consider switching timeline membership configuration to the provided one.
     274            0 : async fn timeline_membership_handler(
     275            0 :     mut request: Request<Body>,
     276            0 : ) -> Result<Response<Body>, ApiError> {
     277            0 :     let ttid = TenantTimelineId::new(
     278            0 :         parse_request_param(&request, "tenant_id")?,
     279            0 :         parse_request_param(&request, "timeline_id")?,
     280              :     );
     281            0 :     check_permission(&request, Some(ttid.tenant_id))?;
     282              : 
     283            0 :     let global_timelines = get_global_timelines(&request);
     284            0 :     let tli = global_timelines.get(ttid).map_err(ApiError::from)?;
     285              : 
     286            0 :     let data: models::TimelineMembershipSwitchRequest = json_request(&mut request).await?;
     287            0 :     let response = tli
     288            0 :         .membership_switch(data.mconf)
     289            0 :         .await
     290            0 :         .map_err(ApiError::InternalServerError)?;
     291              : 
     292            0 :     json_response(StatusCode::OK, response)
     293            0 : }
     294              : 
     295            0 : async fn timeline_copy_handler(mut request: Request<Body>) -> Result<Response<Body>, ApiError> {
     296            0 :     check_permission(&request, None)?;
     297              : 
     298            0 :     let request_data: TimelineCopyRequest = json_request(&mut request).await?;
     299            0 :     let source_ttid = TenantTimelineId::new(
     300            0 :         parse_request_param(&request, "tenant_id")?,
     301            0 :         parse_request_param(&request, "source_timeline_id")?,
     302              :     );
     303              : 
     304            0 :     let global_timelines = get_global_timelines(&request);
     305            0 : 
     306            0 :     copy_timeline::handle_request(copy_timeline::Request{
     307            0 :         source_ttid,
     308            0 :         until_lsn: request_data.until_lsn,
     309            0 :         destination_ttid: TenantTimelineId::new(source_ttid.tenant_id, request_data.target_timeline_id),
     310            0 :     }, global_timelines)
     311            0 :         .instrument(info_span!("copy_timeline", from=%source_ttid, to=%request_data.target_timeline_id, until_lsn=%request_data.until_lsn))
     312            0 :         .await
     313            0 :         .map_err(ApiError::InternalServerError)?;
     314              : 
     315            0 :     json_response(StatusCode::OK, ())
     316            0 : }
     317              : 
     318            0 : async fn patch_control_file_handler(
     319            0 :     mut request: Request<Body>,
     320            0 : ) -> Result<Response<Body>, ApiError> {
     321            0 :     check_permission(&request, None)?;
     322              : 
     323            0 :     let ttid = TenantTimelineId::new(
     324            0 :         parse_request_param(&request, "tenant_id")?,
     325            0 :         parse_request_param(&request, "timeline_id")?,
     326              :     );
     327              : 
     328            0 :     let global_timelines = get_global_timelines(&request);
     329            0 :     let tli = global_timelines.get(ttid).map_err(ApiError::from)?;
     330              : 
     331            0 :     let patch_request: patch_control_file::Request = json_request(&mut request).await?;
     332            0 :     let response = patch_control_file::handle_request(tli, patch_request)
     333            0 :         .await
     334            0 :         .map_err(ApiError::InternalServerError)?;
     335              : 
     336            0 :     json_response(StatusCode::OK, response)
     337            0 : }
     338              : 
     339              : /// Force persist control file.
     340            0 : async fn timeline_checkpoint_handler(request: Request<Body>) -> Result<Response<Body>, ApiError> {
     341            0 :     check_permission(&request, None)?;
     342              : 
     343            0 :     let ttid = TenantTimelineId::new(
     344            0 :         parse_request_param(&request, "tenant_id")?,
     345            0 :         parse_request_param(&request, "timeline_id")?,
     346              :     );
     347              : 
     348            0 :     let global_timelines = get_global_timelines(&request);
     349            0 :     let tli = global_timelines.get(ttid)?;
     350            0 :     tli.write_shared_state()
     351            0 :         .await
     352              :         .sk
     353            0 :         .state_mut()
     354            0 :         .flush()
     355            0 :         .await
     356            0 :         .map_err(ApiError::InternalServerError)?;
     357            0 :     json_response(StatusCode::OK, ())
     358            0 : }
     359              : 
     360            0 : async fn timeline_digest_handler(request: Request<Body>) -> Result<Response<Body>, ApiError> {
     361            0 :     let ttid = TenantTimelineId::new(
     362            0 :         parse_request_param(&request, "tenant_id")?,
     363            0 :         parse_request_param(&request, "timeline_id")?,
     364              :     );
     365            0 :     check_permission(&request, Some(ttid.tenant_id))?;
     366              : 
     367            0 :     let global_timelines = get_global_timelines(&request);
     368            0 :     let from_lsn: Option<Lsn> = parse_query_param(&request, "from_lsn")?;
     369            0 :     let until_lsn: Option<Lsn> = parse_query_param(&request, "until_lsn")?;
     370              : 
     371            0 :     let request = TimelineDigestRequest {
     372            0 :         from_lsn: from_lsn.ok_or(ApiError::BadRequest(anyhow::anyhow!(
     373            0 :             "from_lsn is required"
     374            0 :         )))?,
     375            0 :         until_lsn: until_lsn.ok_or(ApiError::BadRequest(anyhow::anyhow!(
     376            0 :             "until_lsn is required"
     377            0 :         )))?,
     378              :     };
     379              : 
     380            0 :     let tli = global_timelines.get(ttid).map_err(ApiError::from)?;
     381            0 :     let tli = tli
     382            0 :         .wal_residence_guard()
     383            0 :         .await
     384            0 :         .map_err(ApiError::InternalServerError)?;
     385              : 
     386            0 :     let response = debug_dump::calculate_digest(&tli, request)
     387            0 :         .await
     388            0 :         .map_err(ApiError::InternalServerError)?;
     389            0 :     json_response(StatusCode::OK, response)
     390            0 : }
     391              : 
     392              : /// Unevict timeline and remove uploaded partial segment(s) from the remote storage.
     393              : /// Successfull response returns list of segments existed before the deletion.
     394              : /// Aimed for one-off usage not normally needed.
     395            0 : async fn timeline_backup_partial_reset(request: Request<Body>) -> Result<Response<Body>, ApiError> {
     396            0 :     let ttid = TenantTimelineId::new(
     397            0 :         parse_request_param(&request, "tenant_id")?,
     398            0 :         parse_request_param(&request, "timeline_id")?,
     399              :     );
     400            0 :     check_permission(&request, Some(ttid.tenant_id))?;
     401              : 
     402            0 :     let global_timelines = get_global_timelines(&request);
     403            0 :     let tli = global_timelines.get(ttid).map_err(ApiError::from)?;
     404              : 
     405            0 :     let response = tli
     406            0 :         .backup_partial_reset()
     407            0 :         .await
     408            0 :         .map_err(ApiError::InternalServerError)?;
     409            0 :     json_response(StatusCode::OK, response)
     410            0 : }
     411              : 
     412              : /// Make term at least as high as one in request. If one in request is None,
     413              : /// increment current one.
     414            0 : async fn timeline_term_bump_handler(
     415            0 :     mut request: Request<Body>,
     416            0 : ) -> Result<Response<Body>, ApiError> {
     417            0 :     let ttid = TenantTimelineId::new(
     418            0 :         parse_request_param(&request, "tenant_id")?,
     419            0 :         parse_request_param(&request, "timeline_id")?,
     420              :     );
     421            0 :     check_permission(&request, Some(ttid.tenant_id))?;
     422              : 
     423            0 :     let request_data: TimelineTermBumpRequest = json_request(&mut request).await?;
     424              : 
     425            0 :     let global_timelines = get_global_timelines(&request);
     426            0 :     let tli = global_timelines.get(ttid).map_err(ApiError::from)?;
     427            0 :     let response = tli
     428            0 :         .term_bump(request_data.term)
     429            0 :         .await
     430            0 :         .map_err(ApiError::InternalServerError)?;
     431              : 
     432            0 :     json_response(StatusCode::OK, response)
     433            0 : }
     434              : 
     435              : /// Used only in tests to hand craft required data.
     436            0 : async fn record_safekeeper_info(mut request: Request<Body>) -> Result<Response<Body>, ApiError> {
     437            0 :     let ttid = TenantTimelineId::new(
     438            0 :         parse_request_param(&request, "tenant_id")?,
     439            0 :         parse_request_param(&request, "timeline_id")?,
     440              :     );
     441            0 :     check_permission(&request, Some(ttid.tenant_id))?;
     442            0 :     let sk_info: SkTimelineInfo = json_request(&mut request).await?;
     443            0 :     let proto_sk_info = SafekeeperTimelineInfo {
     444            0 :         safekeeper_id: 0,
     445            0 :         tenant_timeline_id: Some(ProtoTenantTimelineId {
     446            0 :             tenant_id: ttid.tenant_id.as_ref().to_owned(),
     447            0 :             timeline_id: ttid.timeline_id.as_ref().to_owned(),
     448            0 :         }),
     449            0 :         term: sk_info.term.unwrap_or(0),
     450            0 :         last_log_term: sk_info.last_log_term.unwrap_or(0),
     451            0 :         flush_lsn: sk_info.flush_lsn.0,
     452            0 :         commit_lsn: sk_info.commit_lsn.0,
     453            0 :         remote_consistent_lsn: sk_info.remote_consistent_lsn.0,
     454            0 :         peer_horizon_lsn: sk_info.peer_horizon_lsn.0,
     455            0 :         safekeeper_connstr: sk_info.safekeeper_connstr.unwrap_or_else(|| "".to_owned()),
     456            0 :         http_connstr: sk_info.http_connstr.unwrap_or_else(|| "".to_owned()),
     457            0 :         backup_lsn: sk_info.backup_lsn.0,
     458            0 :         local_start_lsn: sk_info.local_start_lsn.0,
     459            0 :         availability_zone: None,
     460            0 :         standby_horizon: sk_info.standby_horizon.0,
     461            0 :     };
     462            0 : 
     463            0 :     let global_timelines = get_global_timelines(&request);
     464            0 :     let tli = global_timelines.get(ttid).map_err(ApiError::from)?;
     465            0 :     tli.record_safekeeper_info(proto_sk_info)
     466            0 :         .await
     467            0 :         .map_err(ApiError::InternalServerError)?;
     468              : 
     469            0 :     json_response(StatusCode::OK, ())
     470            0 : }
     471              : 
     472            0 : fn parse_kv_str<E: fmt::Display, T: FromStr<Err = E>>(k: &str, v: &str) -> Result<T, ApiError> {
     473            0 :     v.parse()
     474            0 :         .map_err(|e| ApiError::BadRequest(anyhow::anyhow!("cannot parse {k}: {e}")))
     475            0 : }
     476              : 
     477              : /// Dump debug info about all available safekeeper state.
     478            0 : async fn dump_debug_handler(mut request: Request<Body>) -> Result<Response<Body>, ApiError> {
     479            0 :     check_permission(&request, None)?;
     480            0 :     ensure_no_body(&mut request).await?;
     481              : 
     482            0 :     let mut dump_all: Option<bool> = None;
     483            0 :     let mut dump_control_file: Option<bool> = None;
     484            0 :     let mut dump_memory: Option<bool> = None;
     485            0 :     let mut dump_disk_content: Option<bool> = None;
     486            0 :     let mut dump_term_history: Option<bool> = None;
     487            0 :     let mut dump_wal_last_modified: Option<bool> = None;
     488            0 :     let mut tenant_id: Option<TenantId> = None;
     489            0 :     let mut timeline_id: Option<TimelineId> = None;
     490            0 : 
     491            0 :     let query = request.uri().query().unwrap_or("");
     492            0 :     let mut values = url::form_urlencoded::parse(query.as_bytes());
     493              : 
     494            0 :     for (k, v) in &mut values {
     495            0 :         match k.as_ref() {
     496            0 :             "dump_all" => dump_all = Some(parse_kv_str(&k, &v)?),
     497            0 :             "dump_control_file" => dump_control_file = Some(parse_kv_str(&k, &v)?),
     498            0 :             "dump_memory" => dump_memory = Some(parse_kv_str(&k, &v)?),
     499            0 :             "dump_disk_content" => dump_disk_content = Some(parse_kv_str(&k, &v)?),
     500            0 :             "dump_term_history" => dump_term_history = Some(parse_kv_str(&k, &v)?),
     501            0 :             "dump_wal_last_modified" => dump_wal_last_modified = Some(parse_kv_str(&k, &v)?),
     502            0 :             "tenant_id" => tenant_id = Some(parse_kv_str(&k, &v)?),
     503            0 :             "timeline_id" => timeline_id = Some(parse_kv_str(&k, &v)?),
     504            0 :             _ => Err(ApiError::BadRequest(anyhow::anyhow!(
     505            0 :                 "Unknown query parameter: {}",
     506            0 :                 k
     507            0 :             )))?,
     508              :         }
     509              :     }
     510              : 
     511            0 :     let dump_all = dump_all.unwrap_or(false);
     512            0 :     let dump_control_file = dump_control_file.unwrap_or(dump_all);
     513            0 :     let dump_memory = dump_memory.unwrap_or(dump_all);
     514            0 :     let dump_disk_content = dump_disk_content.unwrap_or(dump_all);
     515            0 :     let dump_term_history = dump_term_history.unwrap_or(true);
     516            0 :     let dump_wal_last_modified = dump_wal_last_modified.unwrap_or(dump_all);
     517            0 : 
     518            0 :     let global_timelines = get_global_timelines(&request);
     519            0 : 
     520            0 :     let args = debug_dump::Args {
     521            0 :         dump_all,
     522            0 :         dump_control_file,
     523            0 :         dump_memory,
     524            0 :         dump_disk_content,
     525            0 :         dump_term_history,
     526            0 :         dump_wal_last_modified,
     527            0 :         tenant_id,
     528            0 :         timeline_id,
     529            0 :     };
     530              : 
     531            0 :     let resp = debug_dump::build(args, global_timelines)
     532            0 :         .await
     533            0 :         .map_err(ApiError::InternalServerError)?;
     534              : 
     535            0 :     let started_at = std::time::Instant::now();
     536            0 : 
     537            0 :     let (tx, rx) = mpsc::channel(1);
     538            0 : 
     539            0 :     let body = Body::wrap_stream(ReceiverStream::new(rx));
     540            0 : 
     541            0 :     let mut writer = ChannelWriter::new(128 * 1024, tx);
     542            0 : 
     543            0 :     let response = Response::builder()
     544            0 :         .status(200)
     545            0 :         .header(hyper::header::CONTENT_TYPE, "application/octet-stream")
     546            0 :         .body(body)
     547            0 :         .unwrap();
     548              : 
     549            0 :     let span = info_span!("blocking");
     550            0 :     tokio::task::spawn_blocking(move || {
     551            0 :         let _span = span.entered();
     552            0 : 
     553            0 :         let res = serde_json::to_writer(&mut writer, &resp)
     554            0 :             .map_err(std::io::Error::from)
     555            0 :             .and_then(|_| writer.flush());
     556            0 : 
     557            0 :         match res {
     558              :             Ok(()) => {
     559            0 :                 tracing::info!(
     560            0 :                     bytes = writer.flushed_bytes(),
     561            0 :                     elapsed_ms = started_at.elapsed().as_millis(),
     562            0 :                     "responded /v1/debug_dump"
     563              :                 );
     564              :             }
     565            0 :             Err(e) => {
     566            0 :                 tracing::warn!("failed to write out /v1/debug_dump response: {e:#}");
     567              :                 // semantics of this error are quite... unclear. we want to error the stream out to
     568              :                 // abort the response to somehow notify the client that we failed.
     569              :                 //
     570              :                 // though, most likely the reason for failure is that the receiver is already gone.
     571            0 :                 drop(
     572            0 :                     writer
     573            0 :                         .tx
     574            0 :                         .blocking_send(Err(std::io::ErrorKind::BrokenPipe.into())),
     575            0 :                 );
     576              :             }
     577              :         }
     578            0 :     });
     579            0 : 
     580            0 :     Ok(response)
     581            0 : }
     582              : 
     583              : /// Safekeeper http router.
     584            0 : pub fn make_router(
     585            0 :     conf: Arc<SafeKeeperConf>,
     586            0 :     global_timelines: Arc<GlobalTimelines>,
     587            0 : ) -> RouterBuilder<hyper::Body, ApiError> {
     588            0 :     let mut router = endpoint::make_router();
     589            0 :     if conf.http_auth.is_some() {
     590            0 :         router = router.middleware(auth_middleware(|request| {
     591              :             const ALLOWLIST_ROUTES: &[&str] =
     592              :                 &["/v1/status", "/metrics", "/profile/cpu", "/profile/heap"];
     593            0 :             if ALLOWLIST_ROUTES.contains(&request.uri().path()) {
     594            0 :                 None
     595              :             } else {
     596              :                 // Option<Arc<SwappableJwtAuth>> is always provided as data below, hence unwrap().
     597            0 :                 request
     598            0 :                     .data::<Option<Arc<SwappableJwtAuth>>>()
     599            0 :                     .unwrap()
     600            0 :                     .as_deref()
     601              :             }
     602            0 :         }))
     603            0 :     }
     604              : 
     605              :     // NB: on any changes do not forget to update the OpenAPI spec
     606              :     // located nearby (/safekeeper/src/http/openapi_spec.yaml).
     607            0 :     let auth = conf.http_auth.clone();
     608            0 :     router
     609            0 :         .data(conf)
     610            0 :         .data(global_timelines)
     611            0 :         .data(auth)
     612            0 :         .get("/metrics", |r| request_span(r, prometheus_metrics_handler))
     613            0 :         .get("/profile/cpu", |r| request_span(r, profile_cpu_handler))
     614            0 :         .get("/profile/heap", |r| request_span(r, profile_heap_handler))
     615            0 :         .get("/v1/status", |r| request_span(r, status_handler))
     616            0 :         .put("/v1/failpoints", |r| {
     617            0 :             request_span(r, move |r| async {
     618            0 :                 check_permission(&r, None)?;
     619            0 :                 let cancel = CancellationToken::new();
     620            0 :                 failpoints_handler(r, cancel).await
     621            0 :             })
     622            0 :         })
     623            0 :         .delete("/v1/tenant/:tenant_id", |r| {
     624            0 :             request_span(r, tenant_delete_handler)
     625            0 :         })
     626            0 :         // Will be used in the future instead of implicit timeline creation
     627            0 :         .post("/v1/tenant/timeline", |r| {
     628            0 :             request_span(r, timeline_create_handler)
     629            0 :         })
     630            0 :         .get("/v1/tenant/timeline", |r| {
     631            0 :             request_span(r, timeline_list_handler)
     632            0 :         })
     633            0 :         .get("/v1/tenant/:tenant_id/timeline/:timeline_id", |r| {
     634            0 :             request_span(r, timeline_status_handler)
     635            0 :         })
     636            0 :         .delete("/v1/tenant/:tenant_id/timeline/:timeline_id", |r| {
     637            0 :             request_span(r, timeline_delete_handler)
     638            0 :         })
     639            0 :         .post("/v1/pull_timeline", |r| {
     640            0 :             request_span(r, timeline_pull_handler)
     641            0 :         })
     642            0 :         .get(
     643            0 :             "/v1/tenant/:tenant_id/timeline/:timeline_id/snapshot/:destination_id",
     644            0 :             |r| request_span(r, timeline_snapshot_handler),
     645            0 :         )
     646            0 :         .post(
     647            0 :             "/v1/tenant/:tenant_id/timeline/:timeline_id/membership",
     648            0 :             |r| request_span(r, timeline_membership_handler),
     649            0 :         )
     650            0 :         .post(
     651            0 :             "/v1/tenant/:tenant_id/timeline/:source_timeline_id/copy",
     652            0 :             |r| request_span(r, timeline_copy_handler),
     653            0 :         )
     654            0 :         .patch(
     655            0 :             "/v1/tenant/:tenant_id/timeline/:timeline_id/control_file",
     656            0 :             |r| request_span(r, patch_control_file_handler),
     657            0 :         )
     658            0 :         .post(
     659            0 :             "/v1/tenant/:tenant_id/timeline/:timeline_id/checkpoint",
     660            0 :             |r| request_span(r, timeline_checkpoint_handler),
     661            0 :         )
     662            0 :         .get("/v1/tenant/:tenant_id/timeline/:timeline_id/digest", |r| {
     663            0 :             request_span(r, timeline_digest_handler)
     664            0 :         })
     665            0 :         .post(
     666            0 :             "/v1/tenant/:tenant_id/timeline/:timeline_id/backup_partial_reset",
     667            0 :             |r| request_span(r, timeline_backup_partial_reset),
     668            0 :         )
     669            0 :         .post(
     670            0 :             "/v1/tenant/:tenant_id/timeline/:timeline_id/term_bump",
     671            0 :             |r| request_span(r, timeline_term_bump_handler),
     672            0 :         )
     673            0 :         .post("/v1/record_safekeeper_info/:tenant_id/:timeline_id", |r| {
     674            0 :             request_span(r, record_safekeeper_info)
     675            0 :         })
     676            0 :         .get("/v1/debug_dump", |r| request_span(r, dump_debug_handler))
     677            0 : }
     678              : 
     679              : #[cfg(test)]
     680              : mod tests {
     681              :     use super::*;
     682              : 
     683              :     #[test]
     684            1 :     fn test_term_switch_entry_api_serialize() {
     685            1 :         let state = AcceptorStateStatus {
     686            1 :             term: 1,
     687            1 :             epoch: 1,
     688            1 :             term_history: vec![TermSwitchApiEntry {
     689            1 :                 term: 1,
     690            1 :                 lsn: Lsn(0x16FFDDDD),
     691            1 :             }],
     692            1 :         };
     693            1 :         let json = serde_json::to_string(&state).unwrap();
     694            1 :         assert_eq!(
     695            1 :             json,
     696            1 :             "{\"term\":1,\"epoch\":1,\"term_history\":[{\"term\":1,\"lsn\":\"0/16FFDDDD\"}]}"
     697            1 :         );
     698            1 :     }
     699              : }
        

Generated by: LCOV version 2.1-beta