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
175 changes: 157 additions & 18 deletions api/crates/layerfs-api/tests/sandbox_machines.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,11 @@
//! LAYERFS_TEST_PG_PASSWORD, LAYERFS_TEST_DAEMON (a host daemon built with
//! `postgresql`); the docker half also LAYERFS_TEST_IMAGE (a local image
//! digest, the worker container's) and LAYERFS_BUNDLE (a sealed Linux
//! bundle whose daemon has `postgresql`). macOS reaches a loopback server
//! from the container as `host.docker.internal`.
//! bundle whose daemon has `postgresql`). The URL is never rewritten: on
//! Docker Desktop a loopback URL is refused for the docker machine, which
//! is then given its own URL naming `host.docker.internal`, which its
//! Sandboxes resolve with the worker's resolver files; their Workspace
//! and Commit never show those files.
//! - a sqlite Store pushed to the docker machine and its Sandbox, through the
//! docker worker: LAYERFS_TEST_IMAGE and LAYERFS_BUNDLE. The Sandbox runs
//! in namespaces inside the privileged worker container and shows
Expand Down Expand Up @@ -79,6 +82,26 @@ fn pg_record(home: &Path) {
.unwrap();
}

/// Sandbox `s1` of project `pg/app`, started on machine `machine`, as its
/// record keeps it (nothing runs).
fn sandbox_on(home: &Path, machine: &str) {
home::write_record(
&paths::sandbox_record(home, "s1"),
&SdkValue::map([
("v", SdkValue::Int(1)),
("name", t("s1")),
("project", t("pg/app")),
("machine", t(machine)),
("created", SdkValue::Int(1)),
("id", t("s1")),
("platform", t("lima")),
("runtime", t("namespaces")),
("backend", t("namespaces")),
]),
)
.unwrap();
}

fn env(name: &str) -> Option<String> {
std::env::var(name).ok().filter(|v| !v.is_empty())
}
Expand Down Expand Up @@ -202,8 +225,39 @@ fn a_sandbox_runs_where_its_store_can_be_reached() {
layerfs_platform::StoreKind::Postgresql,
) {
Ok(()) => {
// a loopback URL is refused before the machine is asked: lima
// does not share this host's loopback, and nothing rewrites it
assert_eq!(code, "Unsupported", "{message}");
assert!(message.contains("host.lima.internal"), "{message}");
assert!(
message.contains("`layerfs store connect pg <url> --machine dev`"),
"{message}"
);
// a Sandbox already on the machine is still read and removed:
// the calls that never dial the Store's URL are not refused for
// it, and reach the machine (here stopped) instead
sandbox_on(&home, "dev");
ok(&home, "sandbox.get", &[("sandbox", t("s1"))]);
let (code, message) =
call(&home, "sandbox.remove", &[("sandbox", t("s1"))]).unwrap_err();
assert!(!message.contains("loopback"), "{code}: {message}");
assert!(message.contains("layerfs machine start dev"), "{message}");
std::fs::remove_dir_all(paths::sandbox_dir(&home, "s1")).unwrap();
// any other host: the stopped machine is refused naming its start
let record = paths::store_record(&home, "pg");
let mut fields = home::read_record(&record).unwrap().unwrap();
if let SdkValue::Map(entries) = &mut fields {
for (name, value) in entries.iter_mut() {
if name == "url" {
*value = t("postgres://db.invalid:1/db");
}
}
}
home::write_record(&record, &fields).unwrap();
let (code, message) = create("dev");
assert_eq!(code, "Unavailable", "{message}");
assert!(message.contains("layerfs machine start dev"), "{message}");
pg_record(&home);
}
Err(reason) => {
assert_eq!(code, "Unsupported", "{message}");
Expand Down Expand Up @@ -390,22 +444,47 @@ fn a_postgresql_store_s_sandboxes_on_native_and_docker() {
ok(
&home,
"machine.update",
&[("name", t("docker")), ("image", t(&image))],
&[("machine", t("docker")), ("image", t(&image))],
);
let outcome = std::panic::catch_unwind(|| {
// only `machine.start` starts a machine (D11)
ok(&home, "machine.start", &[("name", t("docker"))]);
// docker runs the Store's Sandboxes with no step before the
// create, whose reach check dials from the worker container
ok(
&home,
"sandbox.create",
&[
("project", t("pg/app")),
("name", t("d")),
("machine", t("docker")),
],
);
ok(&home, "machine.start", &[("machine", t("docker"))]);
let create = || {
call(
&home,
"sandbox.create",
&[
("project", t("pg/app")),
("name", t("d")),
("machine", t("docker")),
],
)
};
// Docker Desktop's worker does not share this host's loopback:
// a loopback URL is refused, naming the host's name there, and
// the machine gets its own URL (nothing is rewritten)
let loopback = ["127.0.0.1", "localhost", "[::1]"]
.iter()
.find(|host| address.starts_with(*host));
if let (Some(host), false) = (loopback, cfg!(target_os = "linux")) {
let (code, message) = create().unwrap_err();
assert_eq!(code, "Unsupported", "{message}");
assert!(message.contains("host.docker.internal"), "{message}");
assert!(message.contains("--machine docker"), "{message}");
let own = address.replacen(host, "host.docker.internal", 1);
ok(
&home,
"store.connect",
&[
("store", t("pg")),
("url", t(&format!("{scheme}://{own}"))),
("machine", t("docker")),
],
);
}
// the create's reach check dials from the worker container
create().unwrap();
resolves_as_the_worker(&home, "pg/app", "d");
work(&home, "pg/app", "d", "on-docker", "docker.txt");
ok(&home, "sandbox.remove", &[("sandbox", t("d"))]);
});
Expand Down Expand Up @@ -435,6 +514,61 @@ fn a_postgresql_store_s_sandboxes_on_native_and_docker() {
std::fs::remove_dir_all(&folder).unwrap();
}

/// A Sandbox resolves names as its machine's worker does: the worker's
/// `/etc/resolv.conf` and `/etc/hosts` are bound over its root's, so
/// `host.docker.internal` resolves in it on Docker Desktop. Reading them
/// changes nothing a Workspace shows: no change, an UpToDate Commit, and
/// neither file in the Workspace's tree.
fn resolves_as_the_worker(home: &Path, project: &str, sandbox: &str) {
ok(
home,
"branch.fork",
&[
("project", t(project)),
("name", t("resolver")),
("from", t("main")),
],
);
let mounted = ok(
home,
"workspace.mount",
&[("sandbox", t(sandbox)), ("branch", t("resolver"))],
);
let ws = mounted.get_text("workspace").unwrap().to_owned();
let name = if cfg!(target_os = "linux") {
"localhost"
} else {
"host.docker.internal"
};
let ran = ok(
home,
"workspace.exec",
&[
("workspace", t(&ws)),
(
"command",
t(&format!(
"test -s /etc/resolv.conf && test -s /etc/hosts && getent hosts {name} && ls -a"
)),
),
],
);
assert_eq!(ran.get_int("exit_code"), Some(0), "{ran:?}");
let listed = ran.get_text("stdout").unwrap_or_default().to_owned();
for line in listed.lines() {
assert!(!matches!(line, "etc" | "resolv.conf" | "hosts"), "{listed}");
}
let status = ok(home, "workspace.status", &[("workspace", t(&ws))]);
assert_eq!(
status.get("changes"),
Some(&SdkValue::List(Vec::new())),
"{status:?}"
);
let committed = ok(home, "workspace.commit", &[("workspace", t(&ws))]);
assert!(committed.get("unchanged").is_some(), "{committed:?}");
ok(home, "workspace.unmount", &[("workspace", t(&ws))]);
}

/// Removes the docker worker container and data volume of the home `id`,
/// whatever its test did.
fn remove_worker(id: &str) {
Expand Down Expand Up @@ -473,7 +607,7 @@ fn a_sqlite_store_s_sandbox_on_the_docker_machine() {
ok(
&home,
"machine.update",
&[("name", t("docker")), ("image", t(&image))],
&[("machine", t("docker")), ("image", t(&image))],
);
ok(&home, "store.create", &[("name", t("shop"))]);
ok(
Expand All @@ -486,7 +620,7 @@ fn a_sqlite_store_s_sandbox_on_the_docker_machine() {
);
let outcome = std::panic::catch_unwind(|| {
// only `machine.start` starts a machine (D11)
ok(&home, "machine.start", &[("name", t("docker"))]);
ok(&home, "machine.start", &[("machine", t("docker"))]);
let moved = ok(
&home,
"store.move",
Expand Down Expand Up @@ -537,7 +671,12 @@ fn a_sqlite_store_s_sandbox_on_each_running_vm_machine() {
};
let home = PathBuf::from(home);
for machine in machines.split(',') {
let status = ok(&home, "machine.status", &[("name", t(machine))]);
let live = SdkValue::List(vec![t("live")]);
let status = ok(
&home,
"machine.get",
&[("machine", t(machine)), ("with", live)],
);
assert_eq!(
status.get_text("state"),
Some("running"),
Expand Down
16 changes: 10 additions & 6 deletions control/crates/layerfs-control/src/store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -247,10 +247,10 @@ fn runs_postgresql_sandboxes(home: &Path, store: &str, machine: &str) -> Result<
}

/// `refusal` of the check from machine `machine`, naming it, the Store and
/// the host it dialled (never the URL), with the platform's `hint` when
/// the server was not reached (a server that answered with another Store
/// was reached). A worker from a bundle without the check says how to
/// update it.
/// the host it dialled (never the URL), with the platform's `hint` only
/// when no connection was made (a server that answered, with a refused
/// login or another Store, was reached). A worker from a bundle without
/// the check says how to update it.
fn from_machine(
refusal: SdkRefusal,
(store, machine, host): (&str, &str, &str),
Expand All @@ -265,7 +265,10 @@ fn from_machine(
),
),
"Unavailable" if !message.starts_with(check::ANOTHER_STORE) => {
let hint = hint.map(|hint| format!("; {hint}")).unwrap_or_default();
let hint = hint
.filter(|_| layerfs_store::postgresql::open::not_connected(&message))
.map(|hint| format!("; {hint}"))
.unwrap_or_default();
refused(
"Unavailable",
format!(
Expand Down Expand Up @@ -328,7 +331,8 @@ pub(crate) fn check_from(
}
}
};
let checked = checked.map_err(|refusal| from_machine(refusal, (name, machine, &host), hint));
let checked =
checked.map_err(|refusal| from_machine(refusal, (name, machine, &host), hint.as_deref()));
(Some(host), checked)
}

Expand Down
8 changes: 4 additions & 4 deletions control/crates/layerfs-platform/src/adapter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,10 @@ pub(crate) trait Adapter: Sync {
fn provider_state(&self, spec: &Spec) -> Result<State, MachineError>;
/// The machine's state now; starts nothing.
fn status(&self, spec: &Spec) -> Result<Status, MachineError>;
/// The PostgreSQL Store URL the machine's Sandbox daemons dial for
/// `url`: a loopback host becomes the machine's host alias, or is
/// refused naming what is missing (`crate::reach`). Starts nothing.
fn reach(&self, spec: &Spec, url: &str) -> Result<String, MachineError>;
/// How the machine's Sandboxes reach the caller's loopback, which
/// `crate::reach` checks every PostgreSQL Store URL against. Reads
/// nothing from the machine.
fn loopback(&self, spec: &Spec) -> crate::reach::Loopback;
/// The host loopback address at which this process reaches a Sandbox
/// daemon listening on `127.0.0.1:<guest_port>` in the machine (the
/// worker's network namespace), or why the machine forwards none
Expand Down
4 changes: 2 additions & 2 deletions control/crates/layerfs-platform/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,8 @@ pub use probe::{native_missing, probe, Probe};
pub use setup::find_tool;
pub use setup::{
cached_image, copy_in, copy_out, create, data_volume, forward, forward_close, load_image,
name_limit, provider_within, reach, remove, start, status, status_within, stop, stop_force,
worker_port, State, Status,
loopback_hint, name_limit, provider_within, reach, remove, start, status, status_within, stop,
stop_force, worker_port, State, Status,
};
pub use spec::{
parse_size, search_path, tool_fallbacks, Bundle, Endpoint, Forward, Lasting, NameLimit,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
//! `apple-container`'s adapter.
use super::observe::gateway;
use super::{create, guest, remove, start, status, stop};
use crate::adapter::Adapter;
use crate::error::{Code, MachineError};
use crate::platform::HostOs;
use crate::probe::{macos_missing, tool_version};
use crate::reach::{dial, Loopback};
use crate::reach::Loopback;
use crate::setup::forward::refuse;
use crate::setup::guest::Guest;
use crate::setup::Status;
Expand Down Expand Up @@ -54,16 +53,19 @@ impl Adapter for AppleContainer {
fn status(&self, spec: &Spec) -> Result<Status, MachineError> {
status(spec)
}
/// A loopback URL becomes the container network's gateway (G7 receipt):
/// the one its last start recorded (#66), else read from the machine
/// (a record from before #66, or a start that could not read it). A
/// recorded gateway that went stale is dialled as recorded and fails
/// there, explicitly; nothing looks it up again.
fn reach(&self, spec: &Spec, url: &str) -> Result<String, MachineError> {
match spec.state.gateway {
Some(recorded) => dial(spec, url, Loopback::Alias(&recorded.to_string())),
None => dial(spec, url, Loopback::Lookup(&|| gateway(spec))),
}
/// The guest has no name for this host: it reaches it at the container
/// network's gateway (G7 receipt), the one its last start recorded
/// (#66) when there is one, on which the server must listen (0.0.0.0,
/// as Docker Desktop publishes a port), not on 127.0.0.1 alone.
fn loopback(&self, spec: &Spec) -> Loopback {
let gateway = match spec.state.gateway {
Some(recorded) => recorded.to_string(),
None => "the container network's gateway, 192.168.64.1 on vmnet's default network"
.to_owned(),
};
Loopback::Apart(format!(
"{gateway}, on which the server must listen, not on 127.0.0.1 alone; the machine has no name for this host"
))
}
fn forward(&self, spec: &Spec, _guest_port: u16) -> Result<Forward, MachineError> {
Err(refuse(spec, Code::Unsupported, FORWARD))
Expand Down
22 changes: 12 additions & 10 deletions control/crates/layerfs-platform/src/platforms/docker/adapter.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
//! `docker`'s adapter: the built-in machine on Docker's kernel, whose worker
//! container runs `namespaces` Sandboxes (D-8).
use super::{guest, host_address, start, status, stop};
use super::{guest, start, status, stop};
use crate::adapter::{refused, Adapter};
use crate::docker_socket::{socket_state, SocketState, SOCKET_ANSWER};
use crate::error::{Code, MachineError};
use crate::platform::{ExecutorKind, HostOs, Platform};
use crate::probe::first_line;
use crate::reach::{dial, Loopback};
use crate::reach::Loopback;
use crate::setup::forward::refuse;
use crate::setup::guest::Guest;
use crate::setup::{tool, Status};
Expand All @@ -17,6 +17,9 @@ use crate::spec::{Bundle, Forward, NameLimit, Running, Spec, Tools};
/// way Docker publishes one, so a later daemon's port cannot be (D-8).
const FORWARD: &str = "Docker publishes a container's ports only when it starts, so a Sandbox daemon's port in the worker container cannot be published later; its Workspace calls go through the worker";

/// The name Docker Desktop's DNS gives this host in its containers.
const DESKTOP_HOST: &str = "host.docker.internal";

pub(crate) struct Docker;
pub(crate) static ADAPTER: Docker = Docker;

Expand Down Expand Up @@ -82,16 +85,15 @@ impl Adapter for Docker {
status(spec)
}
/// On a Linux Engine the worker shares the host's network, and its
/// `namespaces` Sandboxes share the worker's (D-8), so a loopback URL is
/// dialled as given. Elsewhere (Docker Desktop) a loopback URL becomes
/// the address the running worker container resolves
/// `host.docker.internal` to: a Sandbox image's root cannot resolve
/// the name.
fn reach(&self, spec: &Spec, url: &str) -> Result<String, MachineError> {
/// `namespaces` Sandboxes share the worker's (D-8), so loopback is
/// shared. Docker Desktop's worker has a network of its own, which
/// calls this host `host.docker.internal` (Docker Desktop's DNS, which
/// the worker's Sandboxes use too).
fn loopback(&self, _spec: &Spec) -> Loopback {
if cfg!(target_os = "linux") {
return dial(spec, url, Loopback::Shared);
return Loopback::Shared;
}
dial(spec, url, Loopback::Lookup(&|| host_address(spec)))
Loopback::Apart(format!("{DESKTOP_HOST} names this host there"))
}
fn forward(&self, spec: &Spec, _guest_port: u16) -> Result<Forward, MachineError> {
Err(refuse(spec, Code::Unsupported, FORWARD))
Expand Down
Loading