[core] Unix upstreams: unix:/path parses strictly into a socket upstream; edge proxies and health-checks it in plain HTTP over the socket, Caddy dials unix/<path>
This commit is contained in:
@@ -39,6 +39,36 @@ pub fn peer(addr: SocketAddr, u: &UpstreamRt) -> HttpPeer {
|
||||
p
|
||||
}
|
||||
|
||||
/// The peer of a `unix:` upstream (plain HTTP over the socket).
|
||||
#[cfg(unix)]
|
||||
pub fn unix_peer(path: &str) -> Result<HttpPeer> {
|
||||
let mut p = HttpPeer::new_uds(path, false, String::new())?;
|
||||
p.options.connection_timeout = Some(DIAL_TIMEOUT);
|
||||
Ok(p)
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
pub fn unix_peer(path: &str) -> Result<HttpPeer> {
|
||||
Error::e_explain(
|
||||
ErrorType::SocketError,
|
||||
format!("{path}: Unix sockets need a Unix system"),
|
||||
)
|
||||
}
|
||||
|
||||
/// Every peer to try for `u`, in order: its socket, or each address its name resolves to.
|
||||
pub async fn peers(u: &UpstreamRt) -> Result<Vec<HttpPeer>> {
|
||||
if let Some(path) = &u.unix {
|
||||
return Ok(vec![unix_peer(path)?]);
|
||||
}
|
||||
let addrs = u.resolve().await.map_err(|e| {
|
||||
Error::explain(
|
||||
ErrorType::ConnectNoRoute,
|
||||
format!("cannot resolve {}: {e}", u.authority),
|
||||
)
|
||||
})?;
|
||||
Ok(addrs.into_iter().map(|a| peer(a, u)).collect())
|
||||
}
|
||||
|
||||
/// Send `req` without a body; read the whole response, at most `max_body` bytes of body,
|
||||
/// all within `timeout`.
|
||||
pub async fn fetch(
|
||||
@@ -64,16 +94,9 @@ async fn exchange(
|
||||
max_body: usize,
|
||||
timeout: Duration,
|
||||
) -> Result<Fetched> {
|
||||
let addrs = u.resolve().await.map_err(|e| {
|
||||
Error::explain(
|
||||
ErrorType::ConnectNoRoute,
|
||||
format!("cannot resolve {}: {e}", u.authority),
|
||||
)
|
||||
})?;
|
||||
let mut last = None;
|
||||
let mut session = None;
|
||||
for addr in addrs {
|
||||
let mut p = peer(addr, u);
|
||||
for mut p in peers(u).await? {
|
||||
p.options.total_connection_timeout = Some(timeout);
|
||||
match connector.get_http_session(&p).await {
|
||||
Ok((s, _reused)) => {
|
||||
|
||||
@@ -122,6 +122,9 @@ async fn round(host: &Arc<HostRt>, path: &str, connector: &Arc<Connector>, watch
|
||||
let (h, p, c) = (host.clone(), path.to_owned(), connector.clone());
|
||||
let probe_host = if watch {
|
||||
host.cfg.hostname.clone()
|
||||
} else if host.upstreams[i].unix.is_some() {
|
||||
// A socket has no authority to name; the probe asks as a local client would.
|
||||
"localhost".to_owned()
|
||||
} else {
|
||||
host.upstreams[i].authority.clone()
|
||||
};
|
||||
|
||||
@@ -306,6 +306,11 @@ impl ProxyHttp for EdgeProxy {
|
||||
Error::explain(ErrorType::HTTPStatus(503), "no healthy upstream")
|
||||
})?;
|
||||
let up = &host.upstreams[i];
|
||||
if let Some(path) = &up.unix {
|
||||
// A socket: one peer, nothing to resolve and no other address to try.
|
||||
log::debug!(target: "ianitor::proxy", "{}: upstream {}", host.cfg.hostname, up.authority);
|
||||
return Ok(Box::new(fetch::unix_peer(path)?));
|
||||
}
|
||||
ctx.addrs = match up.resolve().await {
|
||||
Ok(a) => a,
|
||||
Err(e) => {
|
||||
|
||||
@@ -85,6 +85,8 @@ pub struct UpstreamRt {
|
||||
pub authority: String,
|
||||
pub tls: bool,
|
||||
pub sni: String,
|
||||
/// A `unix:` upstream's socket path (plain HTTP); `host` and `port` are then unused.
|
||||
pub unix: Option<String>,
|
||||
pub healthy: AtomicBool,
|
||||
pub health: HealthRecord,
|
||||
}
|
||||
@@ -205,6 +207,21 @@ fn upstream(u: &EdgeUpstream) -> Result<UpstreamRt, EdgeError> {
|
||||
address: u.address.clone(),
|
||||
reason: reason.to_owned(),
|
||||
};
|
||||
if let Some(path) = u.address.strip_prefix("unix:") {
|
||||
if !path.starts_with('/') || u.tls {
|
||||
return Err(err("expected unix:/absolute/path, plain HTTP"));
|
||||
}
|
||||
return Ok(UpstreamRt {
|
||||
host: String::new(),
|
||||
port: 0,
|
||||
authority: u.address.clone(),
|
||||
tls: false,
|
||||
sni: String::new(),
|
||||
unix: Some(path.to_owned()),
|
||||
healthy: AtomicBool::new(true),
|
||||
health: HealthRecord::default(),
|
||||
});
|
||||
}
|
||||
let (host, port) = u
|
||||
.address
|
||||
.rsplit_once(':')
|
||||
@@ -223,6 +240,7 @@ fn upstream(u: &EdgeUpstream) -> Result<UpstreamRt, EdgeError> {
|
||||
authority: u.address.clone(),
|
||||
tls: u.tls,
|
||||
sni: u.sni.clone(),
|
||||
unix: None,
|
||||
healthy: AtomicBool::new(true),
|
||||
health: HealthRecord::default(),
|
||||
})
|
||||
|
||||
@@ -240,4 +240,93 @@ mod unix {
|
||||
assert_eq!(r.status, 403, "{}", edge.stderr());
|
||||
assert!(echo.proxied().is_empty());
|
||||
}
|
||||
|
||||
/// A `unix:` upstream (G14 option b: the admin host reaches control on its socket):
|
||||
/// requests and health checks go over the socket, in plain HTTP.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_unix_socket_upstream_is_proxied_and_health_checked() {
|
||||
use http_body_util::Full;
|
||||
use hyper::server::conn::http1;
|
||||
use hyper::service::service_fn;
|
||||
use hyper_util::rt::TokioIo;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
let dir = ianitor_testkit::proc::TempDir::new("unix-upstream");
|
||||
let sock = dir.join("app.sock");
|
||||
let listener = tokio::net::UnixListener::bind(&sock).unwrap();
|
||||
let seen: Arc<Mutex<Vec<(String, String)>>> = Arc::default();
|
||||
let s = seen.clone();
|
||||
tokio::spawn(async move {
|
||||
loop {
|
||||
let Ok((stream, _)) = listener.accept().await else {
|
||||
continue;
|
||||
};
|
||||
let s = s.clone();
|
||||
tokio::spawn(async move {
|
||||
let svc = service_fn(move |req: hyper::Request<hyper::body::Incoming>| {
|
||||
let host = req
|
||||
.headers()
|
||||
.get("host")
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.unwrap_or("")
|
||||
.to_owned();
|
||||
s.lock().unwrap().push((req.uri().path().to_owned(), host));
|
||||
async move {
|
||||
Ok::<_, std::convert::Infallible>(hyper::Response::new(Full::new(
|
||||
bytes::Bytes::from_static(b"via the socket"),
|
||||
)))
|
||||
}
|
||||
});
|
||||
let _ = http1::Builder::new()
|
||||
.serve_connection(TokioIo::new(stream), svc)
|
||||
.await;
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
let edge = start(EdgeSpec {
|
||||
hosts: vec![host_file(
|
||||
"ui.test",
|
||||
&format!(
|
||||
"upstreams = [\"unix:{}\"]
|
||||
[health_check]
|
||||
path = \"/healthz\"
|
||||
interval_secs = 1
|
||||
",
|
||||
sock.display()
|
||||
),
|
||||
)],
|
||||
..Default::default()
|
||||
});
|
||||
let r = client::https(
|
||||
edge.https,
|
||||
"ui.test",
|
||||
edge.roots(),
|
||||
&Req::get("ui.test", "/x"),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
(r.status, r.text().as_str()),
|
||||
(200, "via the socket"),
|
||||
"{}",
|
||||
edge.stderr()
|
||||
);
|
||||
for _ in 0..50 {
|
||||
if seen.lock().unwrap().iter().any(|(p, _)| p == "/healthz") {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
}
|
||||
let seen = seen.lock().unwrap().clone();
|
||||
assert!(
|
||||
seen.contains(&("/x".to_owned(), "ui.test".to_owned())),
|
||||
"{seen:?}"
|
||||
);
|
||||
assert!(
|
||||
seen.iter()
|
||||
.any(|(p, h)| p == "/healthz" && h == "localhost"),
|
||||
"{seen:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user