Make all HTTP services optionnal

This commit is contained in:
Alex 2022-09-07 17:54:16 +02:00
parent 28d86e7602
commit 2559f63e9b
Signed by untrusted user: lx
GPG key ID: 0E496D15096376BE
7 changed files with 299 additions and 273 deletions

View file

@ -1,3 +1,4 @@
use std::net::SocketAddr;
use std::sync::Arc; use std::sync::Arc;
use async_trait::async_trait; use async_trait::async_trait;
@ -52,15 +53,15 @@ impl AdminApiServer {
} }
} }
pub async fn run(self, shutdown_signal: impl Future<Output = ()>) -> Result<(), GarageError> { pub async fn run(
if let Some(bind_addr) = self.garage.config.admin.api_bind_addr { self,
bind_addr: SocketAddr,
shutdown_signal: impl Future<Output = ()>,
) -> Result<(), GarageError> {
let region = self.garage.config.s3_api.s3_region.clone(); let region = self.garage.config.s3_api.s3_region.clone();
ApiServer::new(region, self) ApiServer::new(region, self)
.run_server(bind_addr, shutdown_signal) .run_server(bind_addr, shutdown_signal)
.await .await
} else {
Ok(())
}
} }
fn handle_options(&self, _req: &Request<Body>) -> Result<Response<Body>, Error> { fn handle_options(&self, _req: &Request<Body>) -> Result<Response<Body>, Error> {

View file

@ -1,3 +1,4 @@
use std::net::SocketAddr;
use std::sync::Arc; use std::sync::Arc;
use async_trait::async_trait; use async_trait::async_trait;
@ -36,20 +37,13 @@ pub(crate) struct K2VApiEndpoint {
impl K2VApiServer { impl K2VApiServer {
pub async fn run( pub async fn run(
garage: Arc<Garage>, garage: Arc<Garage>,
bind_addr: SocketAddr,
s3_region: String,
shutdown_signal: impl Future<Output = ()>, shutdown_signal: impl Future<Output = ()>,
) -> Result<(), GarageError> { ) -> Result<(), GarageError> {
if let Some(cfg) = &garage.config.k2v_api { ApiServer::new(s3_region, K2VApiServer { garage })
let bind_addr = cfg.api_bind_addr;
ApiServer::new(
garage.config.s3_api.s3_region.clone(),
K2VApiServer { garage },
)
.run_server(bind_addr, shutdown_signal) .run_server(bind_addr, shutdown_signal)
.await .await
} else {
Ok(())
}
} }
} }

View file

@ -1,3 +1,4 @@
use std::net::SocketAddr;
use std::sync::Arc; use std::sync::Arc;
use async_trait::async_trait; use async_trait::async_trait;
@ -43,14 +44,11 @@ pub(crate) struct S3ApiEndpoint {
impl S3ApiServer { impl S3ApiServer {
pub async fn run( pub async fn run(
garage: Arc<Garage>, garage: Arc<Garage>,
addr: SocketAddr,
s3_region: String,
shutdown_signal: impl Future<Output = ()>, shutdown_signal: impl Future<Output = ()>,
) -> Result<(), GarageError> { ) -> Result<(), GarageError> {
let addr = garage.config.s3_api.api_bind_addr; ApiServer::new(s3_region, S3ApiServer { garage })
ApiServer::new(
garage.config.s3_api.s3_region.clone(),
S3ApiServer { garage },
)
.run_server(addr, shutdown_signal) .run_server(addr, shutdown_signal)
.await .await
} }

View file

@ -9,7 +9,7 @@ use garage_util::error::Error;
use garage_api::admin::api_server::AdminApiServer; use garage_api::admin::api_server::AdminApiServer;
use garage_api::s3::api_server::S3ApiServer; use garage_api::s3::api_server::S3ApiServer;
use garage_model::garage::Garage; use garage_model::garage::Garage;
use garage_web::run_web_server; use garage_web::WebServer;
#[cfg(feature = "k2v")] #[cfg(feature = "k2v")]
use garage_api::k2v::api_server::K2VApiServer; use garage_api::k2v::api_server::K2VApiServer;
@ -30,6 +30,8 @@ pub async fn run_server(config_file: PathBuf) -> Result<(), Error> {
info!("Loading configuration..."); info!("Loading configuration...");
let config = read_config(config_file)?; let config = read_config(config_file)?;
// ---- Initialize Garage internals ----
info!("Initializing background runner..."); info!("Initializing background runner...");
let watch_cancel = netapp::util::watch_ctrl_c(); let watch_cancel = netapp::util::watch_ctrl_c();
let (background, await_background_done) = BackgroundRunner::new(16, watch_cancel.clone()); let (background, await_background_done) = BackgroundRunner::new(16, watch_cancel.clone());
@ -44,7 +46,7 @@ pub async fn run_server(config_file: PathBuf) -> Result<(), Error> {
init_tracing(config.admin.trace_sink.as_ref().unwrap(), garage.system.id)?; init_tracing(config.admin.trace_sink.as_ref().unwrap(), garage.system.id)?;
#[cfg(not(feature = "telemetry-otlp"))] #[cfg(not(feature = "telemetry-otlp"))]
warn!("Garage was built without OTLP exporter, admin.trace_sink is ignored."); error!("Garage was built without OTLP exporter, admin.trace_sink is ignored.");
} }
info!("Initialize Admin API server and metrics collector..."); info!("Initialize Admin API server and metrics collector...");
@ -56,53 +58,73 @@ pub async fn run_server(config_file: PathBuf) -> Result<(), Error> {
info!("Create admin RPC handler..."); info!("Create admin RPC handler...");
AdminRpcHandler::new(garage.clone()); AdminRpcHandler::new(garage.clone());
info!("Initializing S3 API server..."); // ---- Launch public-facing API servers ----
let s3_api_server = tokio::spawn(S3ApiServer::run(
garage.clone(),
wait_from(watch_cancel.clone()),
));
let mut servers = vec![];
if let Some(s3_bind_addr) = &config.s3_api.api_bind_addr {
info!("Initializing S3 API server...");
servers.push((
"S3 API",
tokio::spawn(S3ApiServer::run(
garage.clone(),
*s3_bind_addr,
config.s3_api.s3_region.clone(),
wait_from(watch_cancel.clone()),
)),
));
}
if config.k2v_api.is_some() {
#[cfg(feature = "k2v")] #[cfg(feature = "k2v")]
let k2v_api_server = { {
info!("Initializing K2V API server..."); info!("Initializing K2V API server...");
servers.push((
"K2V API",
tokio::spawn(K2VApiServer::run( tokio::spawn(K2VApiServer::run(
garage.clone(), garage.clone(),
config.k2v_api.as_ref().unwrap().api_bind_addr,
config.s3_api.s3_region.clone(),
wait_from(watch_cancel.clone()), wait_from(watch_cancel.clone()),
)) )),
};
info!("Initializing web server...");
let web_server = tokio::spawn(run_web_server(
garage.clone(),
wait_from(watch_cancel.clone()),
)); ));
}
#[cfg(not(feature = "k2v"))]
error!("K2V is not enabled in this build, cannot start K2V API server");
}
if let Some(web_config) = &config.s3_web {
info!("Initializing web server...");
servers.push((
"Web",
tokio::spawn(WebServer::run(
garage.clone(),
web_config.bind_addr,
web_config.root_domain.clone(),
wait_from(watch_cancel.clone()),
)),
));
}
if let Some(admin_bind_addr) = &config.admin.api_bind_addr {
info!("Launching Admin API server..."); info!("Launching Admin API server...");
let admin_server = tokio::spawn(admin_server.run(wait_from(watch_cancel.clone()))); servers.push((
"Admin",
tokio::spawn(admin_server.run(*admin_bind_addr, wait_from(watch_cancel.clone()))),
));
}
// Stuff runs // Stuff runs
// When a cancel signal is sent, stuff stops // When a cancel signal is sent, stuff stops
if let Err(e) = s3_api_server.await? {
warn!("S3 API server exited with error: {}", e); // Collect stuff
for (desc, join_handle) in servers {
if let Err(e) = join_handle.await? {
error!("{} server exited with error: {}", desc, e);
} else { } else {
info!("S3 API server exited without error."); info!("{} server exited without error.", desc);
} }
#[cfg(feature = "k2v")]
if let Err(e) = k2v_api_server.await? {
warn!("K2V API server exited with error: {}", e);
} else {
info!("K2V API server exited without error.");
}
if let Err(e) = web_server.await? {
warn!("Web server exited with error: {}", e);
} else {
info!("Web server exited without error.");
}
if let Err(e) = admin_server.await? {
warn!("Admin web server exited with error: {}", e);
} else {
info!("Admin API server exited without error.");
} }
// Remove RPC handlers for system to break reference cycles // Remove RPC handlers for system to break reference cycles

View file

@ -81,11 +81,10 @@ pub struct Config {
pub s3_api: S3ApiConfig, pub s3_api: S3ApiConfig,
/// Configuration for K2V api /// Configuration for K2V api
#[cfg(feature = "k2v")]
pub k2v_api: Option<K2VApiConfig>, pub k2v_api: Option<K2VApiConfig>,
/// Configuration for serving files as normal web server /// Configuration for serving files as normal web server
pub s3_web: WebConfig, pub s3_web: Option<WebConfig>,
/// Configuration for the admin API endpoint /// Configuration for the admin API endpoint
#[serde(default = "Default::default")] #[serde(default = "Default::default")]
@ -96,7 +95,7 @@ pub struct Config {
#[derive(Deserialize, Debug, Clone)] #[derive(Deserialize, Debug, Clone)]
pub struct S3ApiConfig { pub struct S3ApiConfig {
/// Address and port to bind for api serving /// Address and port to bind for api serving
pub api_bind_addr: SocketAddr, pub api_bind_addr: Option<SocketAddr>,
/// S3 region to use /// S3 region to use
pub s3_region: String, pub s3_region: String,
/// Suffix to remove from domain name to find bucket. If None, /// Suffix to remove from domain name to find bucket. If None,
@ -105,7 +104,6 @@ pub struct S3ApiConfig {
} }
/// Configuration for K2V api /// Configuration for K2V api
#[cfg(feature = "k2v")]
#[derive(Deserialize, Debug, Clone)] #[derive(Deserialize, Debug, Clone)]
pub struct K2VApiConfig { pub struct K2VApiConfig {
/// Address and port to bind for api serving /// Address and port to bind for api serving

View file

@ -6,4 +6,4 @@ mod error;
pub use error::Error; pub use error::Error;
mod web_server; mod web_server;
pub use web_server::run_web_server; pub use web_server::WebServer;

View file

@ -57,44 +57,53 @@ impl WebMetrics {
} }
} }
/// Run a web server pub struct WebServer {
pub async fn run_web_server(
garage: Arc<Garage>, garage: Arc<Garage>,
shutdown_signal: impl Future<Output = ()>, metrics: Arc<WebMetrics>,
) -> Result<(), GarageError> { root_domain: String,
let addr = &garage.config.s3_web.bind_addr; }
impl WebServer {
/// Run a web server
pub async fn run(
garage: Arc<Garage>,
addr: SocketAddr,
root_domain: String,
shutdown_signal: impl Future<Output = ()>,
) -> Result<(), GarageError> {
let metrics = Arc::new(WebMetrics::new()); let metrics = Arc::new(WebMetrics::new());
let web_server = Arc::new(WebServer {
garage,
metrics,
root_domain,
});
let service = make_service_fn(|conn: &AddrStream| { let service = make_service_fn(|conn: &AddrStream| {
let garage = garage.clone(); let web_server = web_server.clone();
let metrics = metrics.clone();
let client_addr = conn.remote_addr(); let client_addr = conn.remote_addr();
async move { async move {
Ok::<_, Error>(service_fn(move |req: Request<Body>| { Ok::<_, Error>(service_fn(move |req: Request<Body>| {
let garage = garage.clone(); let web_server = web_server.clone();
let metrics = metrics.clone();
handle_request(garage, metrics, req, client_addr) web_server.handle_request(req, client_addr)
})) }))
} }
}); });
let server = Server::bind(addr).serve(service); let server = Server::bind(&addr).serve(service);
let graceful = server.with_graceful_shutdown(shutdown_signal); let graceful = server.with_graceful_shutdown(shutdown_signal);
info!("Web server listening on http://{}", addr); info!("Web server listening on http://{}", addr);
graceful.await?; graceful.await?;
Ok(()) Ok(())
} }
async fn handle_request( async fn handle_request(
garage: Arc<Garage>, self: Arc<Self>,
metrics: Arc<WebMetrics>,
req: Request<Body>, req: Request<Body>,
addr: SocketAddr, addr: SocketAddr,
) -> Result<Response<Body>, Infallible> { ) -> Result<Response<Body>, Infallible> {
info!("{} {} {}", addr, req.method(), req.uri()); info!("{} {} {}", addr, req.method(), req.uri());
// Lots of instrumentation // Lots of instrumentation
@ -111,13 +120,14 @@ async fn handle_request(
let metrics_tags = &[KeyValue::new("method", req.method().to_string())]; let metrics_tags = &[KeyValue::new("method", req.method().to_string())];
// The actual handler // The actual handler
let res = serve_file(garage, &req) let res = self
.serve_file(&req)
.with_context(Context::current_with_span(span)) .with_context(Context::current_with_span(span))
.record_duration(&metrics.request_duration, &metrics_tags[..]) .record_duration(&self.metrics.request_duration, &metrics_tags[..])
.await; .await;
// More instrumentation // More instrumentation
metrics.request_counter.add(1, &metrics_tags[..]); self.metrics.request_counter.add(1, &metrics_tags[..]);
// Returning the result // Returning the result
match res { match res {
@ -133,7 +143,7 @@ async fn handle_request(
req.uri(), req.uri(),
error error
); );
metrics.error_counter.add( self.metrics.error_counter.add(
1, 1,
&[ &[
metrics_tags[0].clone(), metrics_tags[0].clone(),
@ -143,24 +153,9 @@ async fn handle_request(
Ok(error_to_res(error)) Ok(error_to_res(error))
} }
} }
} }
fn error_to_res(e: Error) -> Response<Body> { async fn serve_file(self: &Arc<Self>, req: &Request<Body>) -> Result<Response<Body>, Error> {
// If we are here, it is either that:
// - there was an error before trying to get the requested URL
// from the bucket (e.g. bucket not found)
// - there was an error processing the request and (the request
// was a HEAD request or we couldn't get the error document)
// We do NOT enter this code path when returning the bucket's
// error document (this is handled in serve_file)
let body = Body::from(format!("{}\n", e));
let mut http_error = Response::new(body);
*http_error.status_mut() = e.http_status_code();
e.add_headers(http_error.headers_mut());
http_error
}
async fn serve_file(garage: Arc<Garage>, req: &Request<Body>) -> Result<Response<Body>, Error> {
// Get http authority string (eg. [::1]:3902 or garage.tld:80) // Get http authority string (eg. [::1]:3902 or garage.tld:80)
let authority = req let authority = req
.headers() .headers()
@ -170,10 +165,10 @@ async fn serve_file(garage: Arc<Garage>, req: &Request<Body>) -> Result<Response
// Get bucket // Get bucket
let host = authority_to_host(authority)?; let host = authority_to_host(authority)?;
let root = &garage.config.s3_web.root_domain;
let bucket_name = host_to_bucket(&host, root).unwrap_or(&host); let bucket_name = host_to_bucket(&host, &self.root_domain).unwrap_or(&host);
let bucket_id = garage let bucket_id = self
.garage
.bucket_alias_table .bucket_alias_table
.get(&EmptyKey, &bucket_name.to_string()) .get(&EmptyKey, &bucket_name.to_string())
.await? .await?
@ -181,7 +176,8 @@ async fn serve_file(garage: Arc<Garage>, req: &Request<Body>) -> Result<Response
.ok_or(Error::NotFound)?; .ok_or(Error::NotFound)?;
// Check bucket isn't deleted and has website access enabled // Check bucket isn't deleted and has website access enabled
let bucket = garage let bucket = self
.garage
.bucket_table .bucket_table
.get(&EmptyKey, &bucket_id) .get(&EmptyKey, &bucket_id)
.await? .await?
@ -207,8 +203,8 @@ async fn serve_file(garage: Arc<Garage>, req: &Request<Body>) -> Result<Response
let ret_doc = match *req.method() { let ret_doc = match *req.method() {
Method::OPTIONS => handle_options_for_bucket(req, &bucket), Method::OPTIONS => handle_options_for_bucket(req, &bucket),
Method::HEAD => handle_head(garage.clone(), req, bucket_id, &key, None).await, Method::HEAD => handle_head(self.garage.clone(), req, bucket_id, &key, None).await,
Method::GET => handle_get(garage.clone(), req, bucket_id, &key, None).await, Method::GET => handle_get(self.garage.clone(), req, bucket_id, &key, None).await,
_ => Err(ApiError::bad_request("HTTP method not supported")), _ => Err(ApiError::bad_request("HTTP method not supported")),
} }
.map_err(Error::from); .map_err(Error::from);
@ -239,7 +235,8 @@ async fn serve_file(garage: Arc<Garage>, req: &Request<Body>) -> Result<Response
.body(Body::empty()) .body(Body::empty())
.unwrap(); .unwrap();
match handle_get(garage, &req2, bucket_id, &error_document, None).await { match handle_get(self.garage.clone(), &req2, bucket_id, &error_document, None).await
{
Ok(mut error_doc) => { Ok(mut error_doc) => {
// The error won't be logged back in handle_request, // The error won't be logged back in handle_request,
// so log it here // so log it here
@ -281,6 +278,22 @@ async fn serve_file(garage: Arc<Garage>, req: &Request<Body>) -> Result<Response
Ok(resp) Ok(resp)
} }
} }
}
}
fn error_to_res(e: Error) -> Response<Body> {
// If we are here, it is either that:
// - there was an error before trying to get the requested URL
// from the bucket (e.g. bucket not found)
// - there was an error processing the request and (the request
// was a HEAD request or we couldn't get the error document)
// We do NOT enter this code path when returning the bucket's
// error document (this is handled in serve_file)
let body = Body::from(format!("{}\n", e));
let mut http_error = Response::new(body);
*http_error.status_mut() = e.http_status_code();
e.add_headers(http_error.headers_mut());
http_error
} }
/// Path to key /// Path to key