Files
ianitor/crates/control/src/lib.rs
T

88 lines
2.5 KiB
Rust

// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! Ianitor control: the routes repository, apply with automatic rollback, share links, API
//! tokens and the REST API, on loopback only. It never serves public traffic; if it stops,
//! edge keeps serving the last good config.
pub mod api;
pub mod caddy_guard;
pub mod caddy_link;
pub mod config;
pub mod crash;
pub mod edgelink;
pub mod engine;
pub mod hostspec;
pub mod logger;
pub mod messages;
pub mod pki;
pub mod pki_ctl;
pub mod records;
pub mod repo;
pub mod shares;
pub mod switch;
pub mod tokens;
pub mod util;
use std::sync::Arc;
pub use config::Config;
pub use engine::Control;
/// Open control, start its background tasks and serve the API until `shutdown` resolves.
pub async fn serve(
cfg: Config,
shutdown: impl std::future::Future<Output = ()> + Send + 'static,
) -> Result<(), String> {
cfg.check().map_err(|e| e.to_string())?;
let listen = cfg.listen;
let ctl = Control::open(cfg).await?;
tokio::spawn(ctl.clone().worker());
tokio::spawn(ctl.clone().health_poller());
tokio::spawn(ctl.clone().pusher());
tokio::spawn(ctl.clone().pki_poller());
let app = api::router(api::AppState::new(ctl.clone()));
if !listen.ip().is_loopback() {
return Err("ianitor-control only listens on loopback".into());
}
let listener = tokio::net::TcpListener::bind(listen)
.await
.map_err(|e| format!("cannot listen on {listen}: {e}"))?;
log::info!(target: "ianitor::control", "API on http://{listen}/api/v1");
axum::serve(listener, app)
.with_graceful_shutdown(shutdown)
.await
.map_err(|e| e.to_string())?;
drop(ctl);
Ok(())
}
/// Wait for Ctrl-C or SIGTERM.
pub async fn stop_signal() {
#[cfg(unix)]
{
use tokio::signal::unix::{SignalKind, signal};
let mut term = match signal(SignalKind::terminate()) {
Ok(s) => s,
Err(_) => {
let _ = tokio::signal::ctrl_c().await;
return;
}
};
tokio::select! {
_ = tokio::signal::ctrl_c() => {}
_ = term.recv() => {}
}
}
#[cfg(not(unix))]
{
let _ = tokio::signal::ctrl_c().await;
}
}
/// For tests: the router over an opened control.
pub fn app(ctl: Arc<Control>) -> axum::Router {
api::router(api::AppState::new(ctl))
}