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