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