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