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