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