[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,220 @@
|
||||
// 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/.
|
||||
|
||||
//! Control's side of edge's admin socket (see `ianitor_edge::admin`).
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::time::Duration;
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum EdgeLinkError {
|
||||
/// Edge did not answer (not running, socket missing, timeout).
|
||||
#[error("edge cannot be reached: {0}")]
|
||||
Unreachable(String),
|
||||
/// Edge answered with an error.
|
||||
#[error("{message}")]
|
||||
Refused { status: u16, message: String },
|
||||
}
|
||||
|
||||
/// One probe result as edge reports it.
|
||||
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
|
||||
pub struct Check {
|
||||
pub seq: u64,
|
||||
pub at: u64,
|
||||
pub ok: bool,
|
||||
pub source: String,
|
||||
pub kind: Option<String>,
|
||||
pub status: Option<u16>,
|
||||
pub latency_ms: Option<u64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct UpstreamStatus {
|
||||
pub address: String,
|
||||
pub healthy: bool,
|
||||
pub checks: Vec<Check>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct CertStatus {
|
||||
pub state: String,
|
||||
pub not_after: Option<i64>,
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct HostStatus {
|
||||
pub hostname: String,
|
||||
pub health_check: bool,
|
||||
pub upstreams: Vec<UpstreamStatus>,
|
||||
pub certificate: CertStatus,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct TrialStatus {
|
||||
pub config_sha256: String,
|
||||
pub seconds_left: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct EdgeStatus {
|
||||
pub generation: u64,
|
||||
pub config_sha256: String,
|
||||
pub started_at: u64,
|
||||
pub trial: Option<TrialStatus>,
|
||||
pub hosts: Vec<HostStatus>,
|
||||
}
|
||||
|
||||
/// How control reaches edge. `None` in dev mode without an edge: applies are written but
|
||||
/// not loaded or watched.
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum EdgeLink {
|
||||
Unix(PathBuf),
|
||||
None,
|
||||
}
|
||||
|
||||
const TIMEOUT: Duration = Duration::from_secs(10);
|
||||
|
||||
impl EdgeLink {
|
||||
pub fn attached(&self) -> bool {
|
||||
matches!(self, EdgeLink::Unix(_))
|
||||
}
|
||||
|
||||
async fn call(
|
||||
&self,
|
||||
method: &str,
|
||||
path: &str,
|
||||
body: Option<Value>,
|
||||
) -> Result<Value, EdgeLinkError> {
|
||||
let EdgeLink::Unix(socket) = self else {
|
||||
return Err(EdgeLinkError::Unreachable("no edge is attached".into()));
|
||||
};
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
let body = body.map(|b| b.to_string()).unwrap_or_default();
|
||||
let req = format!(
|
||||
"{method} {path} HTTP/1.1\r\nHost: edge\r\nConnection: close\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\r\n{body}",
|
||||
body.len()
|
||||
);
|
||||
let exchange = async {
|
||||
let mut s = tokio::net::UnixStream::connect(socket).await?;
|
||||
s.write_all(req.as_bytes()).await?;
|
||||
let mut buf = Vec::new();
|
||||
s.read_to_end(&mut buf).await?;
|
||||
Ok::<_, std::io::Error>(buf)
|
||||
};
|
||||
let buf = tokio::time::timeout(TIMEOUT, exchange)
|
||||
.await
|
||||
.map_err(|_| EdgeLinkError::Unreachable("no answer within 10 s".into()))?
|
||||
.map_err(|e| EdgeLinkError::Unreachable(e.to_string()))?;
|
||||
let (status, json) = parse(&buf).map_err(EdgeLinkError::Unreachable)?;
|
||||
if (200..300).contains(&status) {
|
||||
Ok(json)
|
||||
} else {
|
||||
Err(EdgeLinkError::Refused {
|
||||
status,
|
||||
message: json["error"].as_str().unwrap_or("edge refused").to_owned(),
|
||||
})
|
||||
}
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
{
|
||||
let _ = (socket, method, path, body);
|
||||
Err(EdgeLinkError::Unreachable(
|
||||
"the admin socket needs Unix".into(),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn status(&self) -> Result<EdgeStatus, EdgeLinkError> {
|
||||
let v = self.call("GET", "/v1/status", None).await?;
|
||||
serde_json::from_value(v)
|
||||
.map_err(|e| EdgeLinkError::Unreachable(format!("odd status: {e}")))
|
||||
}
|
||||
|
||||
/// Load the trial file; returns its SHA-256 as edge computed it.
|
||||
pub async fn trial(
|
||||
&self,
|
||||
confirm_within: u64,
|
||||
watch_hosts: &[String],
|
||||
every: u64,
|
||||
) -> Result<String, EdgeLinkError> {
|
||||
let v = self
|
||||
.call(
|
||||
"POST",
|
||||
"/v1/trial",
|
||||
Some(json!({
|
||||
"confirm_within_secs": confirm_within,
|
||||
"watch_hosts": watch_hosts,
|
||||
"watch_every_secs": every,
|
||||
})),
|
||||
)
|
||||
.await?;
|
||||
Ok(v["config_sha256"].as_str().unwrap_or_default().to_owned())
|
||||
}
|
||||
|
||||
pub async fn confirm(&self, sha: &str) -> Result<(), EdgeLinkError> {
|
||||
self.call("POST", "/v1/confirm", Some(json!({ "config_sha256": sha })))
|
||||
.await
|
||||
.map(|_| ())
|
||||
}
|
||||
|
||||
pub async fn abort(&self) -> Result<bool, EdgeLinkError> {
|
||||
let v = self.call("POST", "/v1/abort", None).await?;
|
||||
Ok(v["reverted"].as_bool().unwrap_or(false))
|
||||
}
|
||||
|
||||
pub async fn reload(&self) -> Result<String, EdgeLinkError> {
|
||||
let v = self.call("POST", "/v1/reload", None).await?;
|
||||
Ok(v["config_sha256"].as_str().unwrap_or_default().to_owned())
|
||||
}
|
||||
|
||||
pub async fn reload_revocations(&self) -> Result<(), EdgeLinkError> {
|
||||
self.call("POST", "/v1/share-revocations/reload", None)
|
||||
.await
|
||||
.map(|_| ())
|
||||
}
|
||||
|
||||
pub async fn acme_retry(&self) -> Result<(), EdgeLinkError> {
|
||||
self.call("POST", "/v1/acme/retry", None).await.map(|_| ())
|
||||
}
|
||||
}
|
||||
|
||||
fn parse(raw: &[u8]) -> Result<(u16, Value), String> {
|
||||
let end = raw
|
||||
.windows(4)
|
||||
.position(|w| w == b"\r\n\r\n")
|
||||
.ok_or("no complete answer from edge")?;
|
||||
let head = String::from_utf8_lossy(&raw[..end]);
|
||||
let status: u16 = head
|
||||
.split(' ')
|
||||
.nth(1)
|
||||
.and_then(|s| s.parse().ok())
|
||||
.ok_or("no status from edge")?;
|
||||
let chunked = head
|
||||
.to_ascii_lowercase()
|
||||
.contains("transfer-encoding: chunked");
|
||||
let mut body = raw[end + 4..].to_vec();
|
||||
if chunked {
|
||||
let mut out = Vec::new();
|
||||
let mut rest = &body[..];
|
||||
while let Some(p) = rest.windows(2).position(|w| w == b"\r\n") {
|
||||
let size = usize::from_str_radix(String::from_utf8_lossy(&rest[..p]).trim(), 16)
|
||||
.map_err(|_| "odd chunk from edge")?;
|
||||
rest = &rest[p + 2..];
|
||||
if size == 0 || rest.len() < size {
|
||||
break;
|
||||
}
|
||||
out.extend_from_slice(&rest[..size]);
|
||||
rest = &rest[(size + 2).min(rest.len())..];
|
||||
}
|
||||
body = out;
|
||||
}
|
||||
let json = serde_json::from_slice(&body).unwrap_or(Value::Null);
|
||||
Ok((status, json))
|
||||
}
|
||||
Reference in New Issue
Block a user