Line data Source code
1 : use std::convert::Infallible;
2 : use std::net::IpAddr;
3 : use std::net::Ipv6Addr;
4 : use std::net::SocketAddr;
5 : use std::sync::Arc;
6 : use std::thread;
7 :
8 : use crate::catalog::SchemaDumpError;
9 : use crate::catalog::{get_database_schema, get_dbs_and_roles};
10 : use crate::compute::forward_termination_signal;
11 : use crate::compute::{ComputeNode, ComputeState, ParsedSpec};
12 : use crate::installed_extensions;
13 : use compute_api::requests::{ConfigurationRequest, ExtensionInstallRequest, SetRoleGrantsRequest};
14 : use compute_api::responses::{
15 : ComputeStatus, ComputeStatusResponse, ExtensionInstallResult, GenericAPIError,
16 : SetRoleGrantsResponse,
17 : };
18 :
19 : use anyhow::Result;
20 : use hyper::header::CONTENT_TYPE;
21 : use hyper::service::{make_service_fn, service_fn};
22 : use hyper::{Body, Method, Request, Response, Server, StatusCode};
23 : use metrics::proto::MetricFamily;
24 : use metrics::Encoder;
25 : use metrics::TextEncoder;
26 : use tokio::task;
27 : use tracing::{debug, error, info, warn};
28 : use tracing_utils::http::OtelName;
29 : use utils::http::request::must_get_query_param;
30 :
31 0 : fn status_response_from_state(state: &ComputeState) -> ComputeStatusResponse {
32 0 : ComputeStatusResponse {
33 0 : start_time: state.start_time,
34 0 : tenant: state
35 0 : .pspec
36 0 : .as_ref()
37 0 : .map(|pspec| pspec.tenant_id.to_string()),
38 0 : timeline: state
39 0 : .pspec
40 0 : .as_ref()
41 0 : .map(|pspec| pspec.timeline_id.to_string()),
42 0 : status: state.status,
43 0 : last_active: state.last_active,
44 0 : error: state.error.clone(),
45 0 : }
46 0 : }
47 :
48 : // Service function to handle all available routes.
49 0 : async fn routes(req: Request<Body>, compute: &Arc<ComputeNode>) -> Response<Body> {
50 0 : //
51 0 : // NOTE: The URI path is currently included in traces. That's OK because
52 0 : // it doesn't contain any variable parts or sensitive information. But
53 0 : // please keep that in mind if you change the routing here.
54 0 : //
55 0 : match (req.method(), req.uri().path()) {
56 : // Serialized compute state.
57 0 : (&Method::GET, "/status") => {
58 0 : debug!("serving /status GET request");
59 0 : let state = compute.state.lock().unwrap();
60 0 : let status_response = status_response_from_state(&state);
61 0 : Response::new(Body::from(serde_json::to_string(&status_response).unwrap()))
62 : }
63 :
64 : // Startup metrics in JSON format. Keep /metrics reserved for a possible
65 : // future use for Prometheus metrics format.
66 0 : (&Method::GET, "/metrics.json") => {
67 0 : info!("serving /metrics.json GET request");
68 0 : let metrics = compute.state.lock().unwrap().metrics.clone();
69 0 : Response::new(Body::from(serde_json::to_string(&metrics).unwrap()))
70 : }
71 :
72 : // Prometheus metrics
73 0 : (&Method::GET, "/metrics") => {
74 0 : debug!("serving /metrics GET request");
75 :
76 : // When we call TextEncoder::encode() below, it will immediately
77 : // return an error if a metric family has no metrics, so we need to
78 : // preemptively filter out metric families with no metrics.
79 0 : let metrics = installed_extensions::collect()
80 0 : .into_iter()
81 0 : .filter(|m| !m.get_metric().is_empty())
82 0 : .collect::<Vec<MetricFamily>>();
83 0 :
84 0 : let encoder = TextEncoder::new();
85 0 : let mut buffer = vec![];
86 :
87 0 : if let Err(err) = encoder.encode(&metrics, &mut buffer) {
88 0 : let msg = format!("error handling /metrics request: {err}");
89 0 : error!(msg);
90 0 : return render_json_error(&msg, StatusCode::INTERNAL_SERVER_ERROR);
91 0 : }
92 0 :
93 0 : match Response::builder()
94 0 : .status(StatusCode::OK)
95 0 : .header(CONTENT_TYPE, encoder.format_type())
96 0 : .body(Body::from(buffer))
97 : {
98 0 : Ok(response) => response,
99 0 : Err(err) => {
100 0 : let msg = format!("error handling /metrics request: {err}");
101 0 : error!(msg);
102 0 : render_json_error(&msg, StatusCode::INTERNAL_SERVER_ERROR)
103 : }
104 : }
105 : }
106 : // Collect Postgres current usage insights
107 0 : (&Method::GET, "/insights") => {
108 0 : info!("serving /insights GET request");
109 0 : let status = compute.get_status();
110 0 : if status != ComputeStatus::Running {
111 0 : let msg = format!("compute is not running, current status: {:?}", status);
112 0 : error!(msg);
113 0 : return Response::new(Body::from(msg));
114 0 : }
115 :
116 0 : let insights = compute.collect_insights().await;
117 0 : Response::new(Body::from(insights))
118 : }
119 :
120 0 : (&Method::POST, "/check_writability") => {
121 0 : info!("serving /check_writability POST request");
122 0 : let status = compute.get_status();
123 0 : if status != ComputeStatus::Running {
124 0 : let msg = format!(
125 0 : "invalid compute status for check_writability request: {:?}",
126 0 : status
127 0 : );
128 0 : error!(msg);
129 0 : return Response::new(Body::from(msg));
130 0 : }
131 :
132 0 : let res = crate::checker::check_writability(compute).await;
133 0 : match res {
134 0 : Ok(_) => Response::new(Body::from("true")),
135 0 : Err(e) => {
136 0 : error!("check_writability failed: {}", e);
137 0 : Response::new(Body::from(e.to_string()))
138 : }
139 : }
140 : }
141 :
142 0 : (&Method::POST, "/extensions") => {
143 0 : info!("serving /extensions POST request");
144 0 : let status = compute.get_status();
145 0 : if status != ComputeStatus::Running {
146 0 : let msg = format!(
147 0 : "invalid compute status for extensions request: {:?}",
148 0 : status
149 0 : );
150 0 : error!(msg);
151 0 : return render_json_error(&msg, StatusCode::PRECONDITION_FAILED);
152 0 : }
153 :
154 0 : let request = hyper::body::to_bytes(req.into_body()).await.unwrap();
155 0 : let request = serde_json::from_slice::<ExtensionInstallRequest>(&request).unwrap();
156 0 : let res = compute
157 0 : .install_extension(&request.extension, &request.database, request.version)
158 0 : .await;
159 0 : match res {
160 0 : Ok(version) => render_json(Body::from(
161 0 : serde_json::to_string(&ExtensionInstallResult {
162 0 : extension: request.extension,
163 0 : version,
164 0 : })
165 0 : .unwrap(),
166 0 : )),
167 0 : Err(e) => {
168 0 : error!("install_extension failed: {}", e);
169 0 : render_json_error(&e.to_string(), StatusCode::INTERNAL_SERVER_ERROR)
170 : }
171 : }
172 : }
173 :
174 0 : (&Method::GET, "/info") => {
175 0 : let num_cpus = num_cpus::get_physical();
176 0 : info!("serving /info GET request. num_cpus: {}", num_cpus);
177 0 : Response::new(Body::from(
178 0 : serde_json::json!({
179 0 : "num_cpus": num_cpus,
180 0 : })
181 0 : .to_string(),
182 0 : ))
183 : }
184 :
185 : // Accept spec in JSON format and request compute configuration. If
186 : // anything goes wrong after we set the compute status to `ConfigurationPending`
187 : // and update compute state with new spec, we basically leave compute
188 : // in the potentially wrong state. That said, it's control-plane's
189 : // responsibility to watch compute state after reconfiguration request
190 : // and to clean restart in case of errors.
191 0 : (&Method::POST, "/configure") => {
192 0 : info!("serving /configure POST request");
193 0 : match handle_configure_request(req, compute).await {
194 0 : Ok(msg) => Response::new(Body::from(msg)),
195 0 : Err((msg, code)) => {
196 0 : error!("error handling /configure request: {msg}");
197 0 : render_json_error(&msg, code)
198 : }
199 : }
200 : }
201 :
202 0 : (&Method::POST, "/terminate") => {
203 0 : info!("serving /terminate POST request");
204 0 : match handle_terminate_request(compute).await {
205 0 : Ok(()) => Response::new(Body::empty()),
206 0 : Err((msg, code)) => {
207 0 : error!("error handling /terminate request: {msg}");
208 0 : render_json_error(&msg, code)
209 : }
210 : }
211 : }
212 :
213 0 : (&Method::GET, "/dbs_and_roles") => {
214 0 : info!("serving /dbs_and_roles GET request",);
215 0 : match get_dbs_and_roles(compute).await {
216 0 : Ok(res) => render_json(Body::from(serde_json::to_string(&res).unwrap())),
217 : Err(_) => {
218 0 : render_json_error("can't get dbs and roles", StatusCode::INTERNAL_SERVER_ERROR)
219 : }
220 : }
221 : }
222 :
223 0 : (&Method::GET, "/database_schema") => {
224 0 : let database = match must_get_query_param(&req, "database") {
225 0 : Err(e) => return e.into_response(),
226 0 : Ok(database) => database,
227 0 : };
228 0 : info!("serving /database_schema GET request with database: {database}",);
229 0 : match get_database_schema(compute, &database).await {
230 0 : Ok(res) => render_plain(Body::wrap_stream(res)),
231 : Err(SchemaDumpError::DatabaseDoesNotExist) => {
232 0 : render_json_error("database does not exist", StatusCode::NOT_FOUND)
233 : }
234 0 : Err(e) => {
235 0 : error!("can't get schema dump: {}", e);
236 0 : render_json_error("can't get schema dump", StatusCode::INTERNAL_SERVER_ERROR)
237 : }
238 : }
239 : }
240 :
241 0 : (&Method::POST, "/grants") => {
242 0 : info!("serving /grants POST request");
243 0 : let status = compute.get_status();
244 0 : if status != ComputeStatus::Running {
245 0 : let msg = format!(
246 0 : "invalid compute status for set_role_grants request: {:?}",
247 0 : status
248 0 : );
249 0 : error!(msg);
250 0 : return render_json_error(&msg, StatusCode::PRECONDITION_FAILED);
251 0 : }
252 :
253 0 : let request = hyper::body::to_bytes(req.into_body()).await.unwrap();
254 0 : let request = serde_json::from_slice::<SetRoleGrantsRequest>(&request).unwrap();
255 :
256 0 : let res = compute
257 0 : .set_role_grants(
258 0 : &request.database,
259 0 : &request.schema,
260 0 : &request.privileges,
261 0 : &request.role,
262 0 : )
263 0 : .await;
264 0 : match res {
265 0 : Ok(()) => render_json(Body::from(
266 0 : serde_json::to_string(&SetRoleGrantsResponse {
267 0 : database: request.database,
268 0 : schema: request.schema,
269 0 : role: request.role,
270 0 : privileges: request.privileges,
271 0 : })
272 0 : .unwrap(),
273 0 : )),
274 0 : Err(e) => render_json_error(
275 0 : &format!("could not grant role privileges to the schema: {e}"),
276 0 : // TODO: can we filter on role/schema not found errors
277 0 : // and return appropriate error code?
278 0 : StatusCode::INTERNAL_SERVER_ERROR,
279 0 : ),
280 : }
281 : }
282 :
283 : // get the list of installed extensions
284 : // currently only used in python tests
285 : // TODO: call it from cplane
286 0 : (&Method::GET, "/installed_extensions") => {
287 0 : info!("serving /installed_extensions GET request");
288 0 : let status = compute.get_status();
289 0 : if status != ComputeStatus::Running {
290 0 : let msg = format!(
291 0 : "invalid compute status for extensions request: {:?}",
292 0 : status
293 0 : );
294 0 : error!(msg);
295 0 : return Response::new(Body::from(msg));
296 0 : }
297 0 :
298 0 : let connstr = compute.connstr.clone();
299 0 : let res = crate::installed_extensions::get_installed_extensions(connstr).await;
300 0 : match res {
301 0 : Ok(res) => render_json(Body::from(serde_json::to_string(&res).unwrap())),
302 0 : Err(e) => render_json_error(
303 0 : &format!("could not get list of installed extensions: {}", e),
304 0 : StatusCode::INTERNAL_SERVER_ERROR,
305 0 : ),
306 : }
307 : }
308 :
309 : // download extension files from remote extension storage on demand
310 0 : (&Method::POST, route) if route.starts_with("/extension_server/") => {
311 0 : info!("serving {:?} POST request", route);
312 0 : info!("req.uri {:?}", req.uri());
313 :
314 : // don't even try to download extensions
315 : // if no remote storage is configured
316 0 : if compute.ext_remote_storage.is_none() {
317 0 : info!("no extensions remote storage configured");
318 0 : let mut resp = Response::new(Body::from("no remote storage configured"));
319 0 : *resp.status_mut() = StatusCode::INTERNAL_SERVER_ERROR;
320 0 : return resp;
321 0 : }
322 0 :
323 0 : let mut is_library = false;
324 0 : if let Some(params) = req.uri().query() {
325 0 : info!("serving {:?} POST request with params: {}", route, params);
326 0 : if params == "is_library=true" {
327 0 : is_library = true;
328 0 : } else {
329 0 : let mut resp = Response::new(Body::from("Wrong request parameters"));
330 0 : *resp.status_mut() = StatusCode::BAD_REQUEST;
331 0 : return resp;
332 : }
333 0 : }
334 0 : let filename = route.split('/').last().unwrap().to_string();
335 0 : info!("serving /extension_server POST request, filename: {filename:?} is_library: {is_library}");
336 :
337 : // get ext_name and path from spec
338 : // don't lock compute_state for too long
339 0 : let ext = {
340 0 : let compute_state = compute.state.lock().unwrap();
341 0 : let pspec = compute_state.pspec.as_ref().expect("spec must be set");
342 0 : let spec = &pspec.spec;
343 0 :
344 0 : // debug only
345 0 : info!("spec: {:?}", spec);
346 :
347 0 : let remote_extensions = match spec.remote_extensions.as_ref() {
348 0 : Some(r) => r,
349 : None => {
350 0 : info!("no remote extensions spec was provided");
351 0 : let mut resp = Response::new(Body::from("no remote storage configured"));
352 0 : *resp.status_mut() = StatusCode::INTERNAL_SERVER_ERROR;
353 0 : return resp;
354 : }
355 : };
356 :
357 0 : remote_extensions.get_ext(
358 0 : &filename,
359 0 : is_library,
360 0 : &compute.build_tag,
361 0 : &compute.pgversion,
362 0 : )
363 0 : };
364 0 :
365 0 : match ext {
366 0 : Ok((ext_name, ext_path)) => {
367 0 : match compute.download_extension(ext_name, ext_path).await {
368 0 : Ok(_) => Response::new(Body::from("OK")),
369 0 : Err(e) => {
370 0 : error!("extension download failed: {}", e);
371 0 : let mut resp = Response::new(Body::from(e.to_string()));
372 0 : *resp.status_mut() = StatusCode::INTERNAL_SERVER_ERROR;
373 0 : resp
374 : }
375 : }
376 : }
377 0 : Err(e) => {
378 0 : warn!("extension download failed to find extension: {}", e);
379 0 : let mut resp = Response::new(Body::from("failed to find file"));
380 0 : *resp.status_mut() = StatusCode::INTERNAL_SERVER_ERROR;
381 0 : resp
382 : }
383 : }
384 : }
385 :
386 : // Return the `404 Not Found` for any other routes.
387 : _ => {
388 0 : let mut not_found = Response::new(Body::from("404 Not Found"));
389 0 : *not_found.status_mut() = StatusCode::NOT_FOUND;
390 0 : not_found
391 : }
392 : }
393 0 : }
394 :
395 0 : async fn handle_configure_request(
396 0 : req: Request<Body>,
397 0 : compute: &Arc<ComputeNode>,
398 0 : ) -> Result<String, (String, StatusCode)> {
399 0 : if !compute.live_config_allowed {
400 0 : return Err((
401 0 : "live configuration is not allowed for this compute node".to_string(),
402 0 : StatusCode::PRECONDITION_FAILED,
403 0 : ));
404 0 : }
405 :
406 0 : let body_bytes = hyper::body::to_bytes(req.into_body()).await.unwrap();
407 0 : let spec_raw = String::from_utf8(body_bytes.to_vec()).unwrap();
408 0 : if let Ok(request) = serde_json::from_str::<ConfigurationRequest>(&spec_raw) {
409 0 : let spec = request.spec;
410 :
411 0 : let parsed_spec = match ParsedSpec::try_from(spec) {
412 0 : Ok(ps) => ps,
413 0 : Err(msg) => return Err((msg, StatusCode::BAD_REQUEST)),
414 : };
415 :
416 : // XXX: wrap state update under lock in code blocks. Otherwise,
417 : // we will try to `Send` `mut state` into the spawned thread
418 : // bellow, which will cause error:
419 : // ```
420 : // error: future cannot be sent between threads safely
421 : // ```
422 : {
423 0 : let mut state = compute.state.lock().unwrap();
424 0 : if state.status != ComputeStatus::Empty && state.status != ComputeStatus::Running {
425 0 : let msg = format!(
426 0 : "invalid compute status for configuration request: {:?}",
427 0 : state.status.clone()
428 0 : );
429 0 : return Err((msg, StatusCode::PRECONDITION_FAILED));
430 0 : }
431 0 : state.pspec = Some(parsed_spec);
432 0 : state.set_status(ComputeStatus::ConfigurationPending, &compute.state_changed);
433 0 : drop(state);
434 0 : info!("set new spec and notified waiters");
435 : }
436 :
437 : // Spawn a blocking thread to wait for compute to become Running.
438 : // This is needed to do not block the main pool of workers and
439 : // be able to serve other requests while some particular request
440 : // is waiting for compute to finish configuration.
441 0 : let c = compute.clone();
442 0 : task::spawn_blocking(move || {
443 0 : let mut state = c.state.lock().unwrap();
444 0 : while state.status != ComputeStatus::Running {
445 0 : state = c.state_changed.wait(state).unwrap();
446 0 : info!(
447 0 : "waiting for compute to become Running, current status: {:?}",
448 0 : state.status
449 : );
450 :
451 0 : if state.status == ComputeStatus::Failed {
452 0 : let err = state.error.as_ref().map_or("unknown error", |x| x);
453 0 : let msg = format!("compute configuration failed: {:?}", err);
454 0 : return Err((msg, StatusCode::INTERNAL_SERVER_ERROR));
455 0 : }
456 : }
457 :
458 0 : Ok(())
459 0 : })
460 0 : .await
461 0 : .unwrap()?;
462 :
463 : // Return current compute state if everything went well.
464 0 : let state = compute.state.lock().unwrap().clone();
465 0 : let status_response = status_response_from_state(&state);
466 0 : Ok(serde_json::to_string(&status_response).unwrap())
467 : } else {
468 0 : Err(("invalid spec".to_string(), StatusCode::BAD_REQUEST))
469 : }
470 0 : }
471 :
472 0 : fn render_json_error(e: &str, status: StatusCode) -> Response<Body> {
473 0 : let error = GenericAPIError {
474 0 : error: e.to_string(),
475 0 : };
476 0 : Response::builder()
477 0 : .status(status)
478 0 : .header(CONTENT_TYPE, "application/json")
479 0 : .body(Body::from(serde_json::to_string(&error).unwrap()))
480 0 : .unwrap()
481 0 : }
482 :
483 0 : fn render_json(body: Body) -> Response<Body> {
484 0 : Response::builder()
485 0 : .header(CONTENT_TYPE, "application/json")
486 0 : .body(body)
487 0 : .unwrap()
488 0 : }
489 :
490 0 : fn render_plain(body: Body) -> Response<Body> {
491 0 : Response::builder()
492 0 : .header(CONTENT_TYPE, "text/plain")
493 0 : .body(body)
494 0 : .unwrap()
495 0 : }
496 :
497 0 : async fn handle_terminate_request(compute: &Arc<ComputeNode>) -> Result<(), (String, StatusCode)> {
498 0 : {
499 0 : let mut state = compute.state.lock().unwrap();
500 0 : if state.status == ComputeStatus::Terminated {
501 0 : return Ok(());
502 0 : }
503 0 : if state.status != ComputeStatus::Empty && state.status != ComputeStatus::Running {
504 0 : let msg = format!(
505 0 : "invalid compute status for termination request: {}",
506 0 : state.status
507 0 : );
508 0 : return Err((msg, StatusCode::PRECONDITION_FAILED));
509 0 : }
510 0 : state.set_status(ComputeStatus::TerminationPending, &compute.state_changed);
511 0 : drop(state);
512 0 : }
513 0 :
514 0 : forward_termination_signal();
515 0 : info!("sent signal and notified waiters");
516 :
517 : // Spawn a blocking thread to wait for compute to become Terminated.
518 : // This is needed to do not block the main pool of workers and
519 : // be able to serve other requests while some particular request
520 : // is waiting for compute to finish configuration.
521 0 : let c = compute.clone();
522 0 : task::spawn_blocking(move || {
523 0 : let mut state = c.state.lock().unwrap();
524 0 : while state.status != ComputeStatus::Terminated {
525 0 : state = c.state_changed.wait(state).unwrap();
526 0 : info!(
527 0 : "waiting for compute to become {}, current status: {:?}",
528 0 : ComputeStatus::Terminated,
529 0 : state.status
530 : );
531 : }
532 :
533 0 : Ok(())
534 0 : })
535 0 : .await
536 0 : .unwrap()?;
537 0 : info!("terminated Postgres");
538 0 : Ok(())
539 0 : }
540 :
541 : // Main Hyper HTTP server function that runs it and blocks waiting on it forever.
542 : #[tokio::main]
543 0 : async fn serve(port: u16, state: Arc<ComputeNode>) {
544 0 : // this usually binds to both IPv4 and IPv6 on linux
545 0 : // see e.g. https://github.com/rust-lang/rust/pull/34440
546 0 : let addr = SocketAddr::new(IpAddr::from(Ipv6Addr::UNSPECIFIED), port);
547 0 :
548 0 : let make_service = make_service_fn(move |_conn| {
549 0 : let state = state.clone();
550 0 : async move {
551 0 : Ok::<_, Infallible>(service_fn(move |req: Request<Body>| {
552 0 : let state = state.clone();
553 0 : async move {
554 0 : Ok::<_, Infallible>(
555 0 : // NOTE: We include the URI path in the string. It
556 0 : // doesn't contain any variable parts or sensitive
557 0 : // information in this API.
558 0 : tracing_utils::http::tracing_handler(
559 0 : req,
560 0 : |req| routes(req, &state),
561 0 : OtelName::UriPath,
562 0 : )
563 0 : .await,
564 0 : )
565 0 : }
566 0 : }))
567 0 : }
568 0 : });
569 0 :
570 0 : info!("starting HTTP server on {}", addr);
571 0 :
572 0 : let server = Server::bind(&addr).serve(make_service);
573 0 :
574 0 : // Run this server forever
575 0 : if let Err(e) = server.await {
576 0 : error!("server error: {}", e);
577 0 : }
578 0 : }
579 :
580 : /// Launch a separate Hyper HTTP API server thread and return its `JoinHandle`.
581 0 : pub fn launch_http_server(port: u16, state: &Arc<ComputeNode>) -> Result<thread::JoinHandle<()>> {
582 0 : let state = Arc::clone(state);
583 0 :
584 0 : Ok(thread::Builder::new()
585 0 : .name("http-endpoint".into())
586 0 : .spawn(move || serve(port, state))?)
587 0 : }
|