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