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