Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions control/crates/layerfs-platform/tests/localhost_reach.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
//! A Linux `native` or `docker` Sandbox dials the Store URL exactly as the
//! caller and `store doctor` dial it: `localhost`, IP literals, `hostaddr`,
//! `verify-full`, host lists and Unix sockets all pass through unchanged.
#![cfg(target_os = "linux")]
#[path = "support/standin.rs"]
mod standin;
use layerfs_platform::{self as machine, Platform};
use standin::Scratch;

const SECRET: &str = "s3cr3t-pw";

fn urls() -> Vec<String> {
[
"postgresql://lfs:S@localhost/layerfs",
"postgres://lfs:S@localhost:5432/layerfs?sslmode=disable",
"postgres://lfs:S@LocalHost:5432/layerfs",
"postgres://lfs:S@127.0.0.1:5432/layerfs?sslmode=disable",
"postgres://lfs:S@[::1]:5432/layerfs?sslmode=disable",
"postgres://lfs:S@localhost:5432/layerfs?hostaddr=::1",
"postgres://lfs:S@localhost:5432/layerfs?hostaddr=127.0.0.1",
"postgres://lfs:S@localhost:5432/layerfs?sslmode=verify-full",
"postgres://lfs:S@127.0.0.1:5432/layerfs?sslmode=verify-full",
"postgres://lfs:S@[::1]:5432/layerfs?sslmode=verify-full",
"postgres://lfs:S@localhost:5432,[::1]:5433/layerfs",
"postgres://lfs:S@/layerfs?host=/var/run/postgresql",
"postgres://lfs:S@db.example.com:5432/layerfs?sslmode=verify-full",
]
.iter()
.map(|u| u.replace(":S@", &format!(":{SECRET}@")))
.collect()
}

#[test]
fn native_and_docker_dial_every_url_as_given() {
let scratch = Scratch::new("reach-localhost");
let mut changed = Vec::new();
for kind in [Platform::Native, Platform::Docker] {
let spec = scratch.spec(kind);
for url in urls() {
let outcome = machine::reach(&spec, &url);
if outcome.as_deref() != Ok(url.as_str()) {
changed.push(format!("{kind:?} {url} -> {outcome:?}"));
}
}
}
assert!(changed.is_empty(), "{}", changed.join("\n"));
assert_eq!(scratch.log(), "", "no tool is asked for a shared loopback");
}
55 changes: 52 additions & 3 deletions control/crates/layerfs-sandbox/src/launch/local.rs
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,14 @@ fn start_named(
let labels = crate::lifecycle::labels(name, store.as_deref(), id);
let api = SandboxApi::with_runtime(Arc::new(runtime));
let options = launch_options(backend, identity, host)?;
let pg_host = match &setup.store {
DaemonStore::Postgres { url, .. } => Some(
layerfs_sandbox_backend::PostgresUrl::parse(url)
.map(|parsed| parsed.host().to_owned())
.unwrap_or_default(),
),
DaemonStore::Sqlite { .. } => None,
};
let request = ProviderCreate {
launch: LaunchRequest {
name: sandbox_name.clone(),
Expand All @@ -169,6 +177,16 @@ fn start_named(
};
let created = created.map_err(|mut failure| {
drop(failure.control.take());
let pg = pg_host
.as_deref()
.filter(|_| failure.phase == crate::SandboxPhase::Listener)
.map(|pg_host| {
(
pg_host,
host.store.as_str(),
backend == crate::runtime::Backend::Namespaces,
)
});
abandon(
id,
format!(
Expand All @@ -178,6 +196,7 @@ fn start_named(
),
failure.runtime.take(),
&executable,
pg,
)
})?;
let instance = created.startup.instance;
Expand All @@ -193,6 +212,7 @@ fn start_named(
),
Some(sandbox),
&executable,
None,
));
}
};
Expand Down Expand Up @@ -238,6 +258,7 @@ fn start_named(
),
runtime,
&executable,
None,
));
}
let state = Arc::new(state);
Expand Down Expand Up @@ -433,15 +454,18 @@ fn abandon(
mut cause: String,
sandbox: Option<Box<Sandbox>>,
daemon: &Path,
pg: Option<(&str, &str, bool)>,
) -> SdkRefusal {
let container = sandbox.as_ref().map(|s| s.identity().to_string());
let mut log = None;
let mut last_line = None;
let mut left = None;
if let Some(mut sandbox) = sandbox {
match sandbox.log_tail(crate::lifecycle::LOG_LINES, crate::lifecycle::LOG_BYTES) {
Ok(bytes) => {
let text = String::from_utf8_lossy(&bytes).trim_end().to_owned();
if let Some(last) = text.lines().rev().map(str::trim).find(|l| !l.is_empty()) {
last_line = Some(last.to_owned());
cause = format!("{cause}. Its daemon's last error: {last}");
}
log = Some(text);
Expand All @@ -456,9 +480,34 @@ fn abandon(
)
});
}
let (code, message, removed) = match left {
None => ("Failed", cause, container.is_some()),
Some(left) => (
let pg_unreachable = left.is_none()
&& pg.is_some()
&& last_line.as_deref().is_some_and(|line| {
line.contains("cannot reach PostgreSQL Store")
|| line.contains("Store open: physical Store I/O: pack persistence: Refused { status: \"Closed\" }")
});
let (code, message, removed) = match (left, pg_unreachable, pg) {
(None, true, Some((pg_host, store_name, namespaces))) => {
let message = if pg_host.is_empty() {
format!(
"Sandbox {id} did not start: its daemon cannot reach PostgreSQL Store {store_name}'s server"
)
} else if namespaces
&& !pg_host.eq_ignore_ascii_case("localhost")
&& pg_host.parse::<std::net::IpAddr>().is_err()
{
format!(
"Sandbox {id} did not start: its daemon cannot reach PostgreSQL Store {store_name}'s server at {pg_host} (the Sandbox root has no /etc/hosts or /etc/resolv.conf, so a hostname may not resolve there; use an IP address)"
)
} else {
format!(
"Sandbox {id} did not start: its daemon cannot reach PostgreSQL Store {store_name}'s server at {pg_host}"
)
};
("Unavailable", message, container.is_some())
}
(None, _, _) => ("Failed", cause, container.is_some()),
(Some(left), _, _) => (
"Unknown",
format!("creation of Sandbox {id} failed ({cause}); {left}"),
false,
Expand Down
9 changes: 7 additions & 2 deletions docs/architecture/api/sdk/sandbox.md
Original file line number Diff line number Diff line change
Expand Up @@ -112,8 +112,13 @@ A create whose outcome is not known is `Unknown`; its record keeps the

A start that fails is `Failed` in words: "Sandbox `<name>` did not start:
it stopped `<where>`: `<cause>`", then "Its daemon's last error: …" from
its log. Its `detail` holds `daemon` (the program that was started),
`log` (its last lines), `container` and `removed`
its log, except when a PostgreSQL Sandbox daemon could not reach its
Store's server at startup (`Unavailable`: "Sandbox `<name>` did not start:
its daemon cannot reach PostgreSQL Store `<store>`'s server at `<host>`",
noting on `namespaces` when `<host>` is a hostname that the Sandbox root
has no `/etc/hosts` or `/etc/resolv.conf`). Its `detail` holds `daemon`
(the program that was started), `log` (its last lines), `container` and
`removed`
([`launch/local.rs`](../../../../control/crates/layerfs-sandbox/src/launch/local.rs) `abandon`).
Its `fix` is `layerfs machine doctor <machine>` unless the refusal names a
closer one. On `native`, when `detail.daemon` is the native machine's
Expand Down
5 changes: 4 additions & 1 deletion docs/architecture/engine/store/postgresql.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,10 @@ including a server silent past the 5 s connect-and-login limit
connection is dialled on its own thread and waited for within that limit; a
dial left waiting ends when the server answers or the socket closes. The
diagnostic driver gives its connect and login the same limit under a longer
deadline. The
deadline. `Connector::new` pairs a single `localhost` host (with no
`hostaddr`) with `127.0.0.1` and `::1` via `hostaddr` while keeping
`localhost` for TLS verification, so roots without `/etc/hosts` reach
either IPv4 or IPv6 loopback without DNS. The
session keeps the frozen policy and server version the open check read, so
`PackPersistence::policy` costs no round trip afterwards.
`compaction_missing(session)` applies the same five Store-wide checks to the
Expand Down
11 changes: 11 additions & 0 deletions engine/crates/layerfs-daemon/src/application/failure.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,11 @@ pub enum ApplicationError {
},
/// Original direct existing-Store open failure.
Store(layerfs_storage::StorageError),
/// PostgreSQL Store server was unreachable at open.
PostgresUnreachable {
/// Server host without userinfo.
host: String,
},
/// Original authentication/kernel transport failure.
Channel(ChannelError),
/// Original malformed request, with bounded bytes retained separately.
Expand Down Expand Up @@ -53,6 +58,12 @@ impl fmt::Display for ApplicationError {
Self::Owner(e) => write!(f, "Overlay startup: {:?}", e.result.as_ref().err()),
Self::AfterOverlay { cause, .. } => write!(f, "after Overlay startup: {cause}"),
Self::Store(e) => write!(f, "Store open: {e}"),
Self::PostgresUnreachable { host } if host.is_empty() => {
f.write_str("cannot reach PostgreSQL Store")
}
Self::PostgresUnreachable { host } => {
write!(f, "cannot reach PostgreSQL Store at {host}")
}
Self::Channel(e) => write!(f, "kernel channel: {e}"),
Self::Protocol(e) => write!(f, "kernel request: {e}"),
Self::Install(e) => write!(f, "installation: {e}"),
Expand Down
40 changes: 38 additions & 2 deletions engine/crates/layerfs-daemon/src/application/owner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -566,10 +566,29 @@ impl Application {
Some(opened)
}
Err(cause) => {
let closed = matches!(
&cause,
layerfs_storage::StorageError::Io(io)
if matches!(
io.get_ref().and_then(|e| {
e.downcast_ref::<layerfs_storage::port::PersistenceError>()
}),
Some(layerfs_storage::port::PersistenceError::Refused { status })
if status == "Closed"
)
);
let cause = match (&setup.store, closed) {
(layerfs_bridge::DaemonStore::Postgres { url, .. }, true) => {
ApplicationError::PostgresUnreachable {
host: postgres_host(url),
}
}
_ => ApplicationError::Store(cause),
};
return Err(ApplicationError::AfterOverlay {
owner: Box::new(owner),
cause: Box::new(ApplicationError::Store(cause)),
})
cause: Box::new(cause),
});
}
},
None => None,
Expand Down Expand Up @@ -710,6 +729,23 @@ impl Application {
/// server. A Sandbox daemon opens it with the light check (#63): the schema
/// was fully checked when its Store was connected, and the caller's reach
/// check read its binding just before this daemon started.
fn postgres_host(url: &str) -> String {
let Some((_, rest)) = url.split_once("://") else {
return String::new();
};
let authority = rest.split(['/', '?']).next().unwrap_or("");
let host_port = authority
.rsplit_once('@')
.map_or(authority, |(_, host)| host);
match host_port.strip_prefix('[') {
Some(v6) => v6.split_once(']').map_or("", |(host, _)| host).to_owned(),
None => host_port
.rsplit_once(':')
.map_or(host_port, |(host, _)| host)
.to_owned(),
}
}

fn postgres(url: &str, schema: &str, synchronous_commit: &str) -> PostgresSelection {
let setting = match synchronous_commit {
"local" => SynchronousCommit::Local,
Expand Down
98 changes: 98 additions & 0 deletions engine/crates/layerfs-daemon/tests/postgres_unreachable.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
//! A daemon whose PostgreSQL Store server cannot be reached exits with a
//! clear `cannot reach PostgreSQL Store at <host>` message instead of raw
//! `pack persistence: Refused { status: "Closed" }` debug text, and never
//! includes the URL password.
#![cfg(any(target_os = "linux", target_os = "macos"))]

use layerfs_bridge::{
daemon_setup::{DaemonLimits, DaemonSetup},
duplex, DaemonStore, KernelRoute, StoreAuthority,
};
use std::{
fs::{self, File},
net::TcpListener,
os::unix::fs::{MetadataExt, PermissionsExt},
path::PathBuf,
process::{Command, Stdio},
sync::atomic::{AtomicU64, Ordering},
};

static NEXT: AtomicU64 = AtomicU64::new(0);
const SECRET: &str = "s3cr3t-pg-pw";

fn tempdir(tag: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!(
"layerfs-daemon-pg-unreach-{tag}-{}-{}",
std::process::id(),
NEXT.fetch_add(1, Ordering::Relaxed)
));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).unwrap();
fs::set_permissions(&dir, fs::Permissions::from_mode(0o700)).unwrap();
dir
}

#[test]
fn daemon_reports_unreachable_postgres_store_without_pack_persistence_debug_text() {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let closed_port = listener.local_addr().unwrap().port();
drop(listener);

let dir = tempdir("closed");
let mounts = dir.join("mounts");
fs::create_dir_all(&mounts).unwrap();
fs::set_permissions(&mounts, fs::Permissions::from_mode(0o700)).unwrap();
let id = fs::metadata(&dir).unwrap();
let setup = DaemonSetup {
listen: "127.0.0.1:0".into(),
private_key: [72; 32],
control_peer: duplex::public_key(&[71; 32]).unwrap(),
route: KernelRoute::Nfs,
overlay: dir.join("overlay.sqlite").display().to_string(),
mounts: mounts.display().to_string(),
command_uid: id.uid(),
command_gid: id.gid(),
limits: DaemonLimits {
connections: 4,
handshake_ms: 2000,
idle_ttl_ms: 60_000,
request_deadline_ms: 60_000,
cache_bytes: 1024 * 1024,
namespaces: 4,
pager_kib: 1024,
serial_low_water: 256,
},
store: DaemonStore::Postgres {
url: format!("postgres://app:{SECRET}@127.0.0.1:{closed_port}/shop?sslmode=disable"),
schema: "layerfs".to_owned(),
synchronous_commit: "local".to_owned(),
authority: StoreAuthority {
binding: vec![1; 16],
cursor_key: [2; 32],
},
},
};
let config = dir.join("daemon.config");
fs::write(&config, setup.encode().unwrap()).unwrap();
fs::set_permissions(&config, fs::Permissions::from_mode(0o600)).unwrap();
let stderr_path = dir.join("daemon.stderr");
let status = Command::new(env!("CARGO_BIN_EXE_layerfs-daemon"))
.arg("--config")
.arg(&config)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::from(File::create(&stderr_path).unwrap()))
.status()
.expect("run layerfs-daemon");
let stderr = fs::read_to_string(&stderr_path).unwrap();
let _ = fs::remove_dir_all(&dir);

assert!(!status.success(), "expected failure: {stderr}");
assert!(
stderr.contains("cannot reach PostgreSQL Store at 127.0.0.1"),
"{stderr}"
);
assert!(!stderr.contains("pack persistence"), "{stderr}");
assert!(!stderr.contains("Refused"), "{stderr}");
assert!(!stderr.contains(SECRET), "{stderr}");
}
Loading