carlos / platform Public

ship --check: keep the data volume between containers (#366)

The check made the instance's data directory a local-driver tmpfs volume.
Docker and Podman unmount a tmpfs volume when no container holds it, so
everything release wrote under /data/instances/check (a Rails migration
into CARLOS_DB) was gone before web started, and examples/rails-shop
answered 500 (Could not find table 'pings'). Found by rootfs Plan 4
Task 11 on a dev fleet box.

The data volume is now a plain local volume, which persists as a box's
disk does. A new volume is root's, so before any process runs one
"prepare" container makes it 65534:65534 mode 0700: the probe binary's
new hidden verb __rootfs-check-prepare (dispatched beside
__rootfs-check-probe), run as 0:0 with --cap-drop ALL --cap-add CHOWN,
no-new-privileges, --read-only, --network none, only the data volume and
the probe mounted. The verb chmods then chowns that one directory (Lstat,
no symlink, no recursion). The container is recorded for cleanup like
every other, and a status other than 0 fails the check. The run volume
(the socket's) stays tmpfs.

No user-facing copy changes. A failed prepare reports as a runtime
diagnostic: "<runtime> run: __rootfs-check-prepare exited with status N"
and the container's last lines.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 85f31f069ce440a524ca98115079cfd3e3e79e78 parent 1fa2a99
6 files changed, +437 −39
  • main.go +4 −0
  • ship_check.go +95 −27
  • ship_check_prepare_test.go +154 −0
  • ship_check_probe.go +39 −0
  • ship_check_test.go +144 −12
  • ship_rootfs_unix_test.go +1 −0
diff --git a/main.go b/main.go
index cd4d1ecaf..62f138eb2 100644
--- a/main.go
+++ b/main.go
@@ -45,6 +45,10 @@ func main() {
if cmd == "__rootfs-check-probe" {
os.Exit(runRootfsCheckProbe(args))
}
+ // And the container that makes the check's data volume its user's.
+ if cmd == "__rootfs-check-prepare" {
+ os.Exit(runRootfsCheckPrepare(args))
+ }
switch cmd {
// Asking for help is not an error: it prints on stdout and exits 0, so
// `carlos help | less` works. A bare `carlos` still fails (stderr, 2).
diff --git a/ship_check.go b/ship_check.go
index 0cec4f41f..7c823f248 100644
--- a/ship_check.go
+++ b/ship_check.go
@@ -29,6 +29,9 @@ const (
checkHost = "shop.example.com"
workerSettle = 5 * time.Second
checkLogLines = 20
+ // checkPrepareTimeout bounds the prepare container, which changes one
+ // directory's owner and mode, even under emulation.
+ checkPrepareTimeout = 60 * time.Second
)
// The instance's paths in every check container, as a box lays them out.
@@ -95,8 +98,8 @@ type checkProbeResult struct {
Ports []int `json:"ports"`
}
-// runRootfsCheck runs b's image with rt: release, if declared, to its end;
-// then web, probed with the binary at probe; then each worker, after a
+// runRootfsCheck runs b's image with rt: a container that makes the data
+// volume the check user's; release, if declared, to its end; then web, probed with the binary at probe; then each worker, after a
// healthy web. console is never started (spec §5.10). It writes each line
// of its report to out as it goes. Every container, volume and image it
// made is removed before it returns, on every path, and a removal that
@@ -137,7 +140,7 @@ func (c *rootfsCheck) check(ctx context.Context) {
c.say(fmt.Sprintf("the %s process runs %s, which needs a JIT, and this release does not declare one. it passes here but stops at start on a box. ship it with --jit", name, prog))
}
}
- if !c.checkArch(ctx) || !c.makeImageAndVolumes(ctx) {
+ if !c.checkArch(ctx) || !c.makeImageAndVolumes(ctx) || !c.prepareData(ctx) {
return
}
if _, ok := c.b.procs[release.ProcessRelease]; ok && !c.runRelease(ctx) {
@@ -166,25 +169,75 @@ func (c *rootfsCheck) checkArch(ctx context.Context) bool {
}
// makeImageAndVolumes imports the tree and makes the instance's two
-// directories, each a tmpfs volume owned by the check's user. Each name is
-// recorded before the runtime is asked, so a call cut short is cleaned up.
+// directories as volumes. The data volume is a plain local volume, so what
+// release writes there (a migrated CARLOS_DB) is still there for web and
+// the workers, as on a box's disk: Docker and Podman unmount a tmpfs
+// volume, and so empty it, whenever no container holds it. It starts out
+// root's; prepareData gives it to the check's user. The run volume holds
+// only the socket, which web makes afresh, so it stays a tmpfs volume
+// owned by the check's user. Each name is recorded before the runtime is
+// asked, so a call cut short is cleaned up.
func (c *rootfsCheck) makeImageAndVolumes(ctx context.Context) bool {
c.image = c.prefix + ":latest"
if err := c.rt.importTree(ctx, c.b.tree, c.image); err != nil {
return c.runtimeFailed(ctx, "import", err)
}
- for _, v := range []string{c.prefix + "-data", c.prefix + "-run"} {
- c.volumes = append(c.volumes, v)
- _, err := c.rt.run(ctx, nil, "volume", "create", "--label", "carlos-check="+c.id, "--driver", "local",
- "--opt", "type=tmpfs", "--opt", "device=tmpfs",
- "--opt", fmt.Sprintf("o=uid=%d,gid=%d,mode=0700", checkUID, checkUID), v)
- if err != nil {
+ for _, v := range []struct {
+ name string
+ opts []string
+ }{
+ {c.prefix + "-data", nil},
+ {c.prefix + "-run", []string{"--opt", "type=tmpfs", "--opt", "device=tmpfs",
+ "--opt", fmt.Sprintf("o=uid=%d,gid=%d,mode=0700", checkUID, checkUID)}},
+ } {
+ c.volumes = append(c.volumes, v.name)
+ args := append([]string{"volume", "create", "--label", "carlos-check=" + c.id, "--driver", "local"}, v.opts...)
+ if _, err := c.rt.run(ctx, nil, append(args, v.name)...); err != nil {
return c.runtimeFailed(ctx, "volume create", err)
}
}
return true
}
+// prepareData makes the data volume's root the check user's, mode 0700, as
+// a box makes an instance's directory, before any process runs. A
+// container of its own runs the probe binary's __rootfs-check-prepare as
+// root with CAP_CHOWN alone, no new privileges, no network, a read-only
+// root, and nothing mounted but the data volume and the probe; the check
+// waits for it to exit 0. It is recorded like every container, so the
+// cleanup removes it.
+func (c *rootfsCheck) prepareData(ctx context.Context) bool {
+ ctr := c.prefix + "-prepare"
+ args := []string{"run", "-d", "--name", ctr,
+ "--read-only", "--network", "none",
+ "--cap-drop", "ALL", "--cap-add", "CHOWN", "--security-opt", "no-new-privileges",
+ "--platform", "linux/arm64", "--user", "0:0",
+ "-v", c.volumes[0] + ":" + checkDataDir,
+ "-v", c.probe + ":" + checkProbeMount + ":ro",
+ "--entrypoint", checkProbeMount,
+ "--label", "carlos-check=" + c.id,
+ c.image,
+ "__rootfs-check-prepare", "--dir", checkDataDir, "--uid", strconv.Itoa(checkUID),
+ }
+ if !c.launch(ctx, ctr, args) {
+ return false
+ }
+ code, _, err := c.waitExit(ctx, ctr, checkPrepareTimeout)
+ if err != nil {
+ return c.runtimeFailed(ctx, "wait", err)
+ }
+ if code == 0 {
+ return true
+ }
+ logs := c.logs(ctx, ctr)
+ if execFormatError(logs...) {
+ return c.fail(checkNoEmulation)
+ }
+ c.runtimeFailed(ctx, "run", fmt.Errorf("__rootfs-check-prepare exited with status %d", code))
+ c.sayLogs(logs)
+ return false
+}
+
// processVars is process name's environment in the check: its own env,
// then --env's values, then the instance's CARLOS_* values (validation keeps CARLOS_ names out of
// a process's env). There is no CARLOS_CONTROL_SOCKET or CARLOS_PURGE:
@@ -242,19 +295,41 @@ func (c *rootfsCheck) runArgs(ctr, name string) []string {
return append(args, p.Command[1:]...)
}
-// start runs process name detached and answers its container. A run the
-// runtime refused is reported: an arm64 program this machine cannot run is
-// RFS-1-C62.
+// start runs process name detached and answers its container.
func (c *rootfsCheck) start(ctx context.Context, name string) (string, bool) {
ctr := c.prefix + "-" + name
+ return ctr, c.launch(ctx, ctr, c.runArgs(ctr, name))
+}
+
+// launch records container ctr, then asks the runtime to run args, which
+// name it. A run the runtime refused is reported: an arm64 program this
+// machine cannot run is RFS-1-C62.
+func (c *rootfsCheck) launch(ctx context.Context, ctr string, args []string) bool {
c.containers = append(c.containers, ctr)
- if _, err := c.rt.run(ctx, nil, c.runArgs(ctr, name)...); err != nil {
+ if _, err := c.rt.run(ctx, nil, args...); err != nil {
if ctx.Err() == nil && execFormatError(err.Error()) {
- return ctr, c.fail(checkNoEmulation)
+ return c.fail(checkNoEmulation)
}
- return ctr, c.runtimeFailed(ctx, "run", err)
+ return c.runtimeFailed(ctx, "run", err)
}
- return ctr, true
+ return true
+}
+
+// waitExit waits up to timeout for ctr to exit and answers its status.
+// timedOut says the wait ran out of time rather than ctx ending.
+func (c *rootfsCheck) waitExit(ctx context.Context, ctr string, timeout time.Duration) (code int, timedOut bool, err error) {
+ wctx, cancel := context.WithTimeout(ctx, timeout)
+ out, err := c.rt.run(wctx, nil, "wait", ctr)
+ timedOut = wctx.Err() != nil && ctx.Err() == nil
+ cancel()
+ if err != nil {
+ return 0, timedOut, err
+ }
+ code, err = strconv.Atoi(lastLine(string(out)))
+ if err != nil {
+ return 0, false, fmt.Errorf("%q is not an exit status", strings.TrimSpace(string(out)))
+ }
+ return code, false, nil
}
// runRelease runs release to its end, under its timeout. A failure stops
@@ -269,20 +344,13 @@ func (c *rootfsCheck) runRelease(ctx context.Context) bool {
if s := c.b.procs[release.ProcessRelease].TimeoutSec; s > 0 {
timeout = time.Duration(s) * time.Second
}
- wctx, cancel := context.WithTimeout(ctx, timeout)
- out, err := c.rt.run(wctx, nil, "wait", ctr)
- timedOut := wctx.Err() != nil
- cancel()
+ code, timedOut, err := c.waitExit(ctx, ctr, timeout)
if err != nil {
- if ctx.Err() == nil && timedOut {
+ if timedOut {
return c.fail(fmt.Sprintf("release did not finish within %s", checkDuration(timeout)))
}
return c.runtimeFailed(ctx, "wait", err)
}
- code, err := strconv.Atoi(lastLine(string(out)))
- if err != nil {
- return c.runtimeFailed(ctx, "wait", fmt.Errorf("%q is not an exit status", strings.TrimSpace(string(out))))
- }
if code == 0 {
c.say(fmt.Sprintf("release finished in %s", checkDuration(time.Since(began))))
return true
diff --git a/ship_check_prepare_test.go b/ship_check_prepare_test.go
new file mode 100644
index 000000000..939b671e3
--- /dev/null
+++ b/ship_check_prepare_test.go
@@ -0,0 +1,154 @@
+//go:build unix
+
+package main
+
+import (
+ "errors"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "syscall"
+ "testing"
+)
+
+// __rootfs-check-prepare makes one directory the given user's, mode 0700:
+// that directory alone, never what is in it, and never through a symlink.
+// The test chowns to its own user and group, which needs no privilege.
+func TestPrepareCheckDir(t *testing.T) {
+ uid, gid := os.Getuid(), os.Getgid()
+ owner := func(t *testing.T, p string) (os.FileMode, int, int) {
+ t.Helper()
+ fi, err := os.Lstat(p)
+ if err != nil {
+ t.Fatal(err)
+ }
+ st := fi.Sys().(*syscall.Stat_t)
+ return fi.Mode().Perm(), int(st.Uid), int(st.Gid)
+ }
+
+ dir := filepath.Join(t.TempDir(), "check")
+ if err := os.Mkdir(dir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ inside := filepath.Join(dir, "shop.db")
+ if err := os.WriteFile(inside, nil, 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if err := prepareCheckDir(dir, uid, gid); err != nil {
+ t.Fatalf("prepareCheckDir: %v", err)
+ }
+ if mode, u, g := owner(t, dir); mode != 0o700 || u != uid || g != gid {
+ t.Errorf("dir is %v %d:%d, want 0700 %d:%d", mode, u, g, uid, gid)
+ }
+ if mode, _, _ := owner(t, inside); mode != 0o644 {
+ t.Errorf("a file inside became %v: prepare recursed", mode)
+ }
+
+ // A symlink is refused, and its target is left as it was.
+ target := filepath.Join(t.TempDir(), "elsewhere")
+ if err := os.Mkdir(target, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ link := filepath.Join(t.TempDir(), "check")
+ if err := os.Symlink(target, link); err != nil {
+ t.Fatal(err)
+ }
+ if err := prepareCheckDir(link, uid, gid); err == nil {
+ t.Error("prepareCheckDir followed a symlink")
+ }
+ if mode, _, _ := owner(t, target); mode != 0o755 {
+ t.Errorf("the symlink's target became %v", mode)
+ }
+
+ // A file, and a path that is not there, are refused.
+ if err := prepareCheckDir(inside, uid, gid); err == nil {
+ t.Error("prepareCheckDir took a file")
+ }
+ if mode, _, _ := owner(t, inside); mode != 0o644 {
+ t.Errorf("a refused file became %v", mode)
+ }
+ if err := prepareCheckDir(filepath.Join(dir, "missing"), uid, gid); err == nil {
+ t.Error("prepareCheckDir took a missing path")
+ }
+}
+
+// The verb's exit statuses: 0 done, 1 refused, 2 a flag error.
+func TestRunRootfsCheckPrepareExits(t *testing.T) {
+ dir := filepath.Join(t.TempDir(), "check")
+ if err := os.Mkdir(dir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ link := filepath.Join(t.TempDir(), "link")
+ if err := os.Symlink(dir, link); err != nil {
+ t.Fatal(err)
+ }
+ // The verb gives --uid as both user and group, so run it with the group
+ // it would set only when this user's group has the same number.
+ if os.Getuid() == os.Getgid() {
+ if got := runRootfsCheckPrepare([]string{"--dir", dir, "--uid", strconv.Itoa(os.Getuid())}); got != 0 {
+ t.Errorf("a directory: exit %d, want 0", got)
+ }
+ }
+ if got := runRootfsCheckPrepare([]string{"--dir", link, "--uid", strconv.Itoa(os.Getuid())}); got != 1 {
+ t.Errorf("a symlink: exit %d, want 1", got)
+ }
+ for _, args := range [][]string{
+ nil,
+ {"--uid", "65534"},
+ {"--dir", dir},
+ {"--dir", dir, "--uid", "-1"},
+ {"--dir", dir, "--uid", "x"},
+ {"--dir", dir, "--uid", "65534", "extra"},
+ {"--nope"},
+ } {
+ if got := runRootfsCheckPrepare(args); got != 2 {
+ t.Errorf("%q: exit %d, want 2", args, got)
+ }
+ }
+}
+
+// The binary dispatches the verb before its command switch, as it does
+// __rootfs-check-probe: the prepare container runs it by that name.
+func TestRootfsCheckPrepareThroughTheBinary(t *testing.T) {
+ if testing.Short() {
+ t.Skip("runs the carlos binary")
+ }
+ if os.Getuid() != os.Getgid() {
+ t.Skip("the verb sets --uid as the group too, which this user may not")
+ }
+ bin := buildCarlos(t)
+ dir := filepath.Join(t.TempDir(), "check")
+ if err := os.Mkdir(dir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ link := filepath.Join(t.TempDir(), "link")
+ if err := os.Symlink(dir, link); err != nil {
+ t.Fatal(err)
+ }
+ run := func(args ...string) (int, string) {
+ cmd := exec.Command(bin, append([]string{"__rootfs-check-prepare"}, args...)...)
+ cmd.Env = carlosTestEnv(t)
+ cmd.Dir = t.TempDir()
+ out, err := cmd.CombinedOutput()
+ var ee *exec.ExitError
+ if errors.As(err, &ee) {
+ return ee.ExitCode(), string(out)
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ return 0, string(out)
+ }
+ uid := strconv.Itoa(os.Getuid())
+ if code, out := run("--dir", link, "--uid", uid); code != 1 || !strings.Contains(out, "is not a directory") {
+ t.Errorf("a symlink: exit %d, %q; want 1 and the reason", code, out)
+ }
+ if code, out := run("--dir", dir, "--uid", uid); code != 0 {
+ t.Fatalf("a directory: exit %d, %q", code, out)
+ }
+ if fi, err := os.Lstat(dir); err != nil || fi.Mode().Perm() != 0o700 {
+ t.Errorf("after the verb the directory is %v (%v), want 0700", fi.Mode().Perm(), err)
+ }
+}
diff --git a/ship_check_probe.go b/ship_check_probe.go
index 0be29f778..9f01df979 100644
--- a/ship_check_probe.go
+++ b/ship_check_probe.go
@@ -100,6 +100,45 @@ func runRootfsCheckProbe(args []string) int {
}
}
+// runRootfsCheckPrepare is __rootfs-check-prepare, run in the check's
+// prepare container as root with CAP_CHOWN alone: it makes the directory at
+// --dir mode 0700 and owned by --uid, as user and group (prepareCheckDir).
+// Exit 0 when done, 1 when refused or failed (the reason on stderr, which
+// the check shows as the container's last lines), 2 on a flag error.
+func runRootfsCheckPrepare(args []string) int {
+ fs := flag.NewFlagSet("__rootfs-check-prepare", flag.ContinueOnError)
+ fs.SetOutput(io.Discard)
+ dir := fs.String("dir", "", "the directory to prepare")
+ uid := fs.Int("uid", -1, "its owner, as user and group")
+ if err := fs.Parse(args); err != nil || *dir == "" || *uid < 0 || fs.NArg() > 0 {
+ return 2
+ }
+ if err := prepareCheckDir(*dir, *uid, *uid); err != nil {
+ fmt.Fprintln(os.Stderr, err)
+ return 1
+ }
+ return 0
+}
+
+// prepareCheckDir makes dir mode 0700 and owned by uid:gid: dir alone,
+// never what is in it, and never through a symlink, which Lstat refuses
+// with anything else that is not a directory. The mode goes first: once
+// the directory is another user's, root without CAP_FOWNER could no longer
+// change it.
+func prepareCheckDir(dir string, uid, gid int) error {
+ fi, err := os.Lstat(dir)
+ if err != nil {
+ return err
+ }
+ if !fi.IsDir() {
+ return fmt.Errorf("%s is not a directory", dir)
+ }
+ if err := os.Chmod(dir, 0o700); err != nil {
+ return err
+ }
+ return os.Lchown(dir, uid, gid)
+}
+
// checkProbeGet asks GET / once, for the check's host, and answers the
// status.
func checkProbeGet(ctx context.Context, client *http.Client) (int, error) {
diff --git a/ship_check_test.go b/ship_check_test.go
index 95cf367a0..8922a6a87 100644
--- a/ship_check_test.go
+++ b/ship_check_test.go
@@ -39,8 +39,9 @@ type fakeCheck struct {
cleaning bool
arch string
- waitOut string
- waitHang bool
+ waitOut string // every wait's answer, unless waitBy has the process
+ waitBy map[string]string // wait's answer, by process
+ waitHang string // the process whose wait never returns
probeOut string
probeErr error
runErr map[string]error // by process
@@ -60,6 +61,7 @@ func newFakeCheck(t *testing.T) *fakeCheck {
t: t, made: map[string]bool{}, live: map[string]bool{},
arch: "aarch64", waitOut: "0\n", probeOut: `{"status":200,"after_ms":42}` + "\n",
runErr: map[string]error{}, state: map[string]string{}, logs: map[string]string{},
+ waitBy: map[string]string{},
failAt: -1, cancelAt: -1, out: &bytes.Buffer{},
removeErr: map[string]error{},
}
@@ -160,10 +162,14 @@ func (f *fakeCheck) run(ctx context.Context, stdin io.Reader, args ...string) ([
case "run":
return []byte("0123abcd\n"), f.runErr[procOf(flagValue(args, "--name"))]
case "wait":
- if f.waitHang {
+ proc := procOf(last)
+ if f.waitHang == proc {
<-ctx.Done()
return nil, ctx.Err()
}
+ if out, ok := f.waitBy[proc]; ok {
+ return []byte(out), nil
+ }
return []byte(f.waitOut), nil
case "exec":
return []byte(f.probeOut), f.probeErr
@@ -295,8 +301,9 @@ func TestRootfsCheckHappyPath(t *testing.T) {
want := []string{
"info", "import", "volume create data", "volume create run",
+ "run prepare", "wait prepare",
"run release", "wait release", "run web", "exec web", "run jobs", "inspect jobs",
- "rm -f release", "rm -f web", "rm -f jobs", "volume rm data", "volume rm run", "rmi",
+ "rm -f prepare", "rm -f release", "rm -f web", "rm -f jobs", "volume rm data", "volume rm run", "rmi",
}
if got := f.summary(); !slices.Equal(got, want) {
t.Errorf("calls:\n got %q\nwant %q", got, want)
@@ -457,12 +464,30 @@ func TestRootfsCheckRunArgs(t *testing.T) {
if want := []string{"exec", name, "/opt/carlos/carlos", "__rootfs-check-probe", "--socket", "/run/carlos/instances/check/app.sock", "--timeout", "120s"}; !slices.Equal(exec, want) {
t.Errorf("exec = %q, want %q", exec, want)
}
- // Volumes are tmpfs, owned by the check's user.
- if want := []string{"volume", "create", "--label", "carlos-check=" + id, "--driver", "local", "--opt", "type=tmpfs", "--opt", "device=tmpfs", "--opt", "o=uid=65534,gid=65534,mode=0700", prefix + "-data"}; !slices.Equal(f.calls[2], want) {
- t.Errorf("volume create = %q, want %q", f.calls[2], want)
+ // The data volume is a plain local volume, so what release writes is
+ // still there for web, as on a box's disk: a tmpfs volume is emptied
+ // whenever no container holds it. The run volume, the socket's, is
+ // tmpfs, owned by the check's user.
+ creates := map[string][]string{}
+ for _, c := range f.calls {
+ if c[0] == "volume" && c[1] == "create" {
+ creates[procOf(c[len(c)-1])] = c
+ }
+ }
+ if want := []string{"volume", "create", "--label", "carlos-check=" + id, "--driver", "local", prefix + "-data"}; !slices.Equal(creates["data"], want) {
+ t.Errorf("data volume create = %q, want %q", creates["data"], want)
}
- if want := []string{"inspect", "--format", "{{json .State}}", prefix + "-jobs"}; !slices.Equal(f.calls[9], want) {
- t.Errorf("inspect = %q, want %q", f.calls[9], want)
+ if want := []string{"volume", "create", "--label", "carlos-check=" + id, "--driver", "local", "--opt", "type=tmpfs", "--opt", "device=tmpfs", "--opt", "o=uid=65534,gid=65534,mode=0700", prefix + "-run"}; !slices.Equal(creates["run"], want) {
+ t.Errorf("run volume create = %q, want %q", creates["run"], want)
+ }
+ var inspect []string
+ for _, c := range f.calls {
+ if c[0] == "inspect" {
+ inspect = c
+ }
+ }
+ if want := []string{"inspect", "--format", "{{json .State}}", prefix + "-jobs"}; !slices.Equal(inspect, want) {
+ t.Errorf("inspect = %q, want %q", inspect, want)
}
}
@@ -535,7 +560,7 @@ func TestRootfsCheckReleaseFailureStopsTheCheck(t *testing.T) {
noSettle(t)
t.Run("an exit", func(t *testing.T) {
f := newFakeCheck(t)
- f.waitOut = "3\n"
+ f.waitBy["release"] = "3\n"
f.logs["release"] = "migrating\nno such table: orders\n"
r := runRootfsCheck(context.Background(), f.rt(), shopBuild(t, shopProcs()), "/probe/carlos", f.out)
want := []string{"release exited with status 3. its last lines:", " migrating", " no such table: orders", checkC75}
@@ -549,7 +574,7 @@ func TestRootfsCheckReleaseFailureStopsTheCheck(t *testing.T) {
})
t.Run("a timeout", func(t *testing.T) {
f := newFakeCheck(t)
- f.waitHang = true
+ f.waitHang = release.ProcessRelease
procs := shopProcs()
procs[release.ProcessRelease] = release.Process{Command: []string{"/srv/migrate"}, TimeoutSec: 1}
r := runRootfsCheck(context.Background(), f.rt(), shopBuild(t, procs), "/probe/carlos", f.out)
@@ -564,6 +589,110 @@ func TestRootfsCheckReleaseFailureStopsTheCheck(t *testing.T) {
})
}
+// The data volume is a new local volume, so root's: before any process
+// runs, one container of its own makes it the check user's, mode 0700, as
+// root with CAP_CHOWN alone, no network, and only that volume and the
+// probe binary mounted.
+func TestRootfsCheckPreparesTheDataVolume(t *testing.T) {
+ noSettle(t)
+ for _, c := range []struct {
+ name string
+ procs map[string]release.Process
+ first string // the first process after prepare
+ }{
+ {"with release", shopProcs(), "run release"},
+ {"web alone", map[string]release.Process{release.ProcessWeb: shopProcs()[release.ProcessWeb]}, "run web"},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ f := newFakeCheck(t)
+ r := runRootfsCheck(context.Background(), f.rt(), shopBuild(t, c.procs), "/probe/carlos", f.out)
+ if r.failed {
+ t.Fatalf("report = %q", r.lines)
+ }
+ sum := f.summary()
+ at := slices.Index(sum, "run prepare")
+ if at < 0 || at+2 >= len(sum) || sum[at+1] != "wait prepare" || sum[at+2] != c.first {
+ t.Fatalf("calls %q: want run prepare, wait prepare, then %s", sum, c.first)
+ }
+ if create := slices.Index(sum, "volume create data"); create < 0 || create > at {
+ t.Errorf("calls %q: prepare before the data volume exists", sum)
+ }
+ prep := f.runOf("prepare")
+ name := flagValue(prep, "--name")
+ prefix := strings.TrimSuffix(name, "-prepare")
+ id := strings.TrimPrefix(prefix, "carlos-check-")
+ want := []string{"run", "-d", "--name", name,
+ "--read-only", "--network", "none",
+ "--cap-drop", "ALL", "--cap-add", "CHOWN", "--security-opt", "no-new-privileges",
+ "--platform", "linux/arm64", "--user", "0:0",
+ "-v", prefix + "-data:/data/instances/check",
+ "-v", "/probe/carlos:/opt/carlos/carlos:ro",
+ "--entrypoint", "/opt/carlos/carlos",
+ "--label", "carlos-check=" + id,
+ prefix + ":latest",
+ "__rootfs-check-prepare", "--dir", "/data/instances/check", "--uid", "65534",
+ }
+ if !slices.Equal(prep, want) {
+ t.Errorf("prepare's argv\n got %q\nwant %q", prep, want)
+ }
+ var caps []string
+ for i, a := range prep {
+ if a == "--cap-add" {
+ caps = append(caps, prep[i+1])
+ }
+ }
+ if !slices.Equal(caps, []string{"CHOWN"}) {
+ t.Errorf("prepare adds %q, want CHOWN alone", caps)
+ }
+ if !slices.Contains(sum, "rm -f prepare") {
+ t.Errorf("calls %q: the prepare container is never removed", sum)
+ }
+ f.checkLeftNothing(t)
+ })
+ }
+}
+
+// A prepare that does not exit 0 fails the check before any process runs,
+// and the check still removes everything it made.
+func TestRootfsCheckPrepareFailureStopsTheCheck(t *testing.T) {
+ noSettle(t)
+ for _, c := range []struct {
+ name string
+ setup func(f *fakeCheck)
+ want []string
+ }{
+ {"an exit", func(f *fakeCheck) {
+ f.waitBy["prepare"] = "1\n"
+ f.logs["prepare"] = "chown /data/instances/check: operation not permitted\n"
+ }, []string{"docker run: __rootfs-check-prepare exited with status 1", " chown /data/instances/check: operation not permitted", checkC75}},
+ {"an amd64 probe", func(f *fakeCheck) {
+ f.waitBy["prepare"] = "255\n"
+ f.logs["prepare"] = `exec /opt/carlos/carlos: exec format error` + "\n"
+ }, []string{checkNoEmulation, checkC75}},
+ {"not an exit status", func(f *fakeCheck) {
+ f.waitBy["prepare"] = "gone\n"
+ }, []string{`docker wait: "gone" is not an exit status`, checkC75}},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ f := newFakeCheck(t)
+ c.setup(f)
+ r := runRootfsCheck(context.Background(), f.rt(), shopBuild(t, shopProcs()), "/probe/carlos", f.out)
+ if !r.failed || !slices.Equal(r.lines[1:], c.want) {
+ t.Errorf("report = %q (failed %v), want C60 then %q", r.lines, r.failed, c.want)
+ }
+ for _, s := range f.summary() {
+ if s == "run release" || s == "run web" || s == "run jobs" {
+ t.Errorf("%q after prepare failed", s)
+ }
+ }
+ if !slices.Contains(f.summary(), "rm -f prepare") {
+ t.Errorf("calls %q: the prepare container is never removed", f.summary())
+ }
+ f.checkLeftNothing(t)
+ })
+ }
+}
+
func TestRootfsCheckWorkerThatExits(t *testing.T) {
noSettle(t)
f := newFakeCheck(t)
@@ -787,6 +916,7 @@ run) env | LC_ALL=C sort > "$work/env-run"
done
find "$TMPDIR" -name '*.env' >> "$log" ;;
exec) echo "$FAKE_PROBE"; exit "$FAKE_PROBE_EXIT" ;;
+wait) echo 0 ;;
inspect) echo '{"Running":true}' ;;
esac
exit 0
@@ -833,7 +963,8 @@ exit 0
}
log, _ := os.ReadFile(logPath)
for _, want := range []string{"rm -f carlos-check-", "volume rm carlos-check-", "rmi carlos-check-",
- " -e HTTP_PROXY=http://proxy.example.com:3128 ", " -e docker_host=tcp://example.com:2375 "} {
+ " -e HTTP_PROXY=http://proxy.example.com:3128 ", " -e docker_host=tcp://example.com:2375 ",
+ " --cap-add CHOWN ", " __rootfs-check-prepare --dir /data/instances/check --uid 65534\n"} {
if !strings.Contains(string(log), want) {
t.Errorf("the runtime never saw %q:\n%s", want, log)
}
@@ -1148,6 +1279,7 @@ run) env | LC_ALL=C sort > "$work/env-run"
prev=$a
done ;;
exec) echo '{"status":200,"after_ms":7}' ;;
+wait) echo 0 ;;
inspect) echo '{"Running":true}' ;;
esac
exit 0
diff --git a/ship_rootfs_unix_test.go b/ship_rootfs_unix_test.go
index f85f9197b..18d1ad00a 100644
--- a/ship_rootfs_unix_test.go
+++ b/ship_rootfs_unix_test.go
@@ -111,6 +111,7 @@ func TestShipRootfsCheckCleansUpOnInterrupt(t *testing.T) {
case "$1" in
info) echo aarch64 ;;
import) cat > /dev/null ;;
+wait) echo 0 ;;
exec) : > "$FAKE_READY"; exec sleep 60 ;;
esac
exit 0