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