[control] Phase 2 control plane: routes repo via git, journaled apply with trial/watch/revert, undo and restore, push with retry, share links, API tokens, REST API with OpenAPI, --dev
This commit is contained in:
@@ -0,0 +1,197 @@
|
||||
// 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 --dev`: everything temporary, on 127.0.0.1. A fresh routes repository, a
|
||||
//! state directory, a share-link key and one API token printed once. If an `ianitor-edge`
|
||||
//! binary is found (`--edge-bin`, `$IANITOR_EDGE_BIN`, or next to this binary), it runs as
|
||||
//! the dev proxy on 127.0.0.1:18080/18443 with an admin socket, so applies are loaded and
|
||||
//! watched for real; otherwise applies are only written. Everything is removed on Ctrl-C.
|
||||
|
||||
use std::net::SocketAddr;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Child, Command, Stdio};
|
||||
use std::time::Duration;
|
||||
|
||||
use ianitor_control::config::{Caddy, Compile, Config, Edge, Routes};
|
||||
use ianitor_control::repo::Repo;
|
||||
use ianitor_control::tokens::Tokens;
|
||||
use ianitor_control::util::{hex, random, write_atomic};
|
||||
|
||||
const SITE: &str = "# Dev site settings. Sign-in goes to an Authelia that may not run here.\n\
|
||||
[forward_auth]\nurl = \"http://127.0.0.1:9091/api/authz/forward-auth\"\n";
|
||||
|
||||
struct Cleanup {
|
||||
dir: PathBuf,
|
||||
edge: Option<Child>,
|
||||
}
|
||||
|
||||
impl Drop for Cleanup {
|
||||
fn drop(&mut self) {
|
||||
if let Some(c) = &mut self.edge {
|
||||
let _ = c.kill();
|
||||
let _ = c.wait();
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&self.dir);
|
||||
}
|
||||
}
|
||||
|
||||
fn find_edge(args: &[String]) -> Option<PathBuf> {
|
||||
let mut it = args.iter();
|
||||
while let Some(a) = it.next() {
|
||||
if a == "--edge-bin" {
|
||||
return it.next().map(PathBuf::from);
|
||||
}
|
||||
}
|
||||
if let Some(p) = std::env::var_os("IANITOR_EDGE_BIN") {
|
||||
return Some(PathBuf::from(p));
|
||||
}
|
||||
let me = std::env::current_exe().ok()?;
|
||||
let sibling = me.with_file_name(if cfg!(windows) {
|
||||
"ianitor-edge.exe"
|
||||
} else {
|
||||
"ianitor-edge"
|
||||
});
|
||||
sibling.is_file().then_some(sibling)
|
||||
}
|
||||
|
||||
fn arg(args: &[String], name: &str) -> Option<String> {
|
||||
let mut it = args.iter();
|
||||
while let Some(a) = it.next() {
|
||||
if a == name {
|
||||
return it.next().cloned();
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub async fn run(args: &[String]) -> Result<(), String> {
|
||||
let listen: SocketAddr = arg(args, "--listen")
|
||||
.unwrap_or_else(|| "127.0.0.1:7878".into())
|
||||
.parse()
|
||||
.map_err(|_| "--listen must be an address like 127.0.0.1:7878")?;
|
||||
if !listen.ip().is_loopback() {
|
||||
return Err("--dev listens on loopback only".into());
|
||||
}
|
||||
let dir = std::env::temp_dir().join(format!("ianitor-dev-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let mut cleanup = Cleanup {
|
||||
dir: dir.clone(),
|
||||
edge: None,
|
||||
};
|
||||
for d in [
|
||||
"state",
|
||||
"edge",
|
||||
"caddy",
|
||||
"certs",
|
||||
"creds",
|
||||
"logs",
|
||||
"edge-state",
|
||||
] {
|
||||
std::fs::create_dir_all(dir.join(d)).map_err(|e| e.to_string())?;
|
||||
}
|
||||
let key = hex(&random::<32>().map_err(|e| e.to_string())?);
|
||||
write_atomic(&dir.join("creds/share-link-key"), key.as_bytes(), 0o600)
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
let edge_bin = if cfg!(unix) { find_edge(args) } else { None };
|
||||
let s = |p: &str| dir.join(p).to_string_lossy().into_owned();
|
||||
let cfg = Config {
|
||||
listen,
|
||||
allowed_hosts: Vec::new(),
|
||||
state_dir: dir.join("state"),
|
||||
credentials_dir: Some(dir.join("creds")),
|
||||
git: PathBuf::from("git"),
|
||||
watch_secs: arg(args, "--watch-secs")
|
||||
.and_then(|v| v.parse().ok())
|
||||
.unwrap_or(10),
|
||||
watch_every_secs: 2,
|
||||
trial_margin_secs: 20,
|
||||
health_poll_secs: 2,
|
||||
routes: Routes {
|
||||
repo: dir.join("routes.git"),
|
||||
branch: "main".into(),
|
||||
remote: None,
|
||||
remote_name: "Gitea".into(),
|
||||
push_username: "ianitor".into(),
|
||||
push_credential: None,
|
||||
},
|
||||
edge: Edge {
|
||||
config: dir.join("edge/edge.json"),
|
||||
trial: None,
|
||||
admin_socket: edge_bin.as_ref().map(|_| dir.join("edge/admin.sock")),
|
||||
share_revocations: dir.join("edge/share-revocations.json"),
|
||||
},
|
||||
caddy: Caddy {
|
||||
config: dir.join("caddy/caddy.json"),
|
||||
},
|
||||
compile: Compile {
|
||||
http_listen: "127.0.0.1:18080".parse().map_err(|_| "bad address")?,
|
||||
https_listen: "127.0.0.1:18443".parse().map_err(|_| "bad address")?,
|
||||
cert_dir: s("certs"),
|
||||
state_dir: s("edge-state"),
|
||||
access_log: s("logs/access.log"),
|
||||
caddy_credentials_dir: s("creds"),
|
||||
caddy_admin: None,
|
||||
},
|
||||
compile_caddy: None,
|
||||
};
|
||||
cfg.check().map_err(|e| e.to_string())?;
|
||||
Repo::open_seeded(&cfg.git, &cfg.routes.repo, &cfg.state_dir, "main", SITE)
|
||||
.map_err(|e| e.to_string())?;
|
||||
let (_, token) = Tokens::new(&cfg.state_dir).create("dev", None)?;
|
||||
|
||||
// Control writes edge.json first; then edge can start from it.
|
||||
let ctl_cfg = cfg.clone();
|
||||
let opened = ianitor_control::Control::open(ctl_cfg).await?;
|
||||
drop(opened);
|
||||
if let Some(bin) = &edge_bin {
|
||||
cleanup.edge = Some(start_edge(bin, &dir, &cfg)?);
|
||||
}
|
||||
|
||||
println!("Ianitor control (dev) on http://{listen}/api/v1");
|
||||
println!("Routes repository: {}", cfg.routes.repo.display());
|
||||
match &edge_bin {
|
||||
Some(b) => println!(
|
||||
"Dev proxy: {} on https://127.0.0.1:18443 (HTTP 18080); Domi hosts need certificates in {}",
|
||||
b.display(),
|
||||
dir.join("certs").display()
|
||||
),
|
||||
None => println!(
|
||||
"No ianitor-edge found: applies are written but not loaded or watched (use --edge-bin)."
|
||||
),
|
||||
}
|
||||
println!("API token (shown once): {token}");
|
||||
println!("Press Ctrl-C to stop and remove {}", dir.display());
|
||||
let r = ianitor_control::serve(cfg, ianitor_control::stop_signal()).await;
|
||||
drop(cleanup);
|
||||
r
|
||||
}
|
||||
|
||||
fn start_edge(bin: &Path, dir: &Path, cfg: &Config) -> Result<Child, String> {
|
||||
let log = std::fs::File::create(dir.join("logs/edge.log")).map_err(|e| e.to_string())?;
|
||||
let log2 = log.try_clone().map_err(|e| e.to_string())?;
|
||||
let child = Command::new(bin)
|
||||
.arg("--config")
|
||||
.arg(&cfg.edge.config)
|
||||
.arg("--admin-socket")
|
||||
.arg(dir.join("edge/admin.sock"))
|
||||
.arg("--share-revocations")
|
||||
.arg(&cfg.edge.share_revocations)
|
||||
.env("CREDENTIALS_DIRECTORY", dir.join("creds"))
|
||||
.stdout(Stdio::from(log))
|
||||
.stderr(Stdio::from(log2))
|
||||
.spawn()
|
||||
.map_err(|e| format!("cannot start {}: {e}", bin.display()))?;
|
||||
let sock = dir.join("edge/admin.sock");
|
||||
for _ in 0..100 {
|
||||
if sock.exists() {
|
||||
return Ok(child);
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
}
|
||||
Err(format!(
|
||||
"the dev proxy did not start; see {}",
|
||||
dir.join("logs/edge.log").display()
|
||||
))
|
||||
}
|
||||
Reference in New Issue
Block a user