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