activator: the rootfs worker identity: its launch file, log socket, unit, stop and proof
Rootfs apps Plan 3, Group W, Task W1a (#366): the agent's half of a rootfs worker. RootfsWorkerBackend (ExecBackend, forwarded by SplitBackend for an exec row, refused for a unit-backed one): - LaunchRootfsWorker starts worker name of generation g from g's image (rootfsImage, RFS-2-C07 kept, Process = name) at g.Tier.MemoryMax, with web's launch environment through rootfsWorkerVars and rootfsLaunchEnv (never childEnv), CARLOS_CONTROL_SOCKET only when web's listener bound. Gates, a whole identity, the digest check and the exec gate come before root is asked; root's 403 and pre-start refusals are refusals (launch file removed, listener closed); any other failure returns a handle with the error and keeps the files. - prepareWorker reads no env file, binds no control listener, binds the log socket root's WorkerDropIn names (workerLogSocket) and clears only this worker's exit records. - The worker handle (newRootfsWorkerProc, rootfsUnitFor) watches WorkerUnitName, stops through StopRootfs(role=worker, kill=false), keeps its exit record (WorkerExit) and tells the member nothing: observe's exit, foreign-restart and replaced-after-stop lines are skipped for a worker. Web, cmd and binary handles are unchanged. - RootfsWorkerGone: StopRootfs on DeadlineControl then the unit's cgroup on roleEmptyBound, neither cancelled by the caller; only nil from both is the proof. removeRootfsWorkerFiles removes this worker's launch file and records, for a caller holding that proof. INV-1 and INV-5 gain worker rows, the production-seam test its RootfsWorkerBackend row, and plan3GroupsStarted gains "W" [pf W0.7]. No instancectl change. No copy. Dormant: nothing calls it until W1b.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
9 files changed,
+1,206
−9
internal/activator/backend_rootfs.go+179 −0internal/activator/backend_unit.go+23 −0internal/activator/prepare.go+65 −4internal/activator/production_backend_test.go+17 −0internal/activator/rootfs_invariants_test.go+80 −0internal/activator/rootfsenv.go+11 −0internal/activator/rootfsworkers_backend_test.go+746 −0internal/activator/unitproc.go+84 −4plan3_groups_test.go+1 −1
diff --git a/internal/activator/backend_rootfs.go b/internal/activator/backend_rootfs.go| index 221396b1b..91a65e611 100644 |
| --- a/internal/activator/backend_rootfs.go |
| +++ b/internal/activator/backend_rootfs.go |
| @@ -9,6 +9,7 @@ import ( |
| "io" |
| "log" |
| "os" |
| + "path/filepath" |
| "slices" |
| "strings" |
| "sync" |
| @@ -339,3 +340,181 @@ func (e lineEmitter) Write(p []byte) (int, error) { |
| } |
| return len(p), nil |
| } |
| + |
| +// RootfsWorkerBackend is the agent's half of a rootfs worker (Group W, |
| +// W1). The control verbs are Plan 2's RootfsControl (StartRootfsWorker, |
| +// StopRootfs). ExecBackend has it; SplitBackend forwards it for an exec |
| +// row. |
| +type RootfsWorkerBackend interface { |
| + // LaunchRootfsWorker starts worker name of generation g, whose web |
| + // handle is web, and returns once root has started its unit. A refusal |
| + // before root started anything returns no handle and an error marked |
| + // refuseRootfs or launchRefused; any other error may come with a |
| + // handle whose unit may run, which the caller proves gone |
| + // (RootfsWorkerGone). |
| + LaunchRootfsWorker(ctx context.Context, rt registry.Route, name string, g Gen, web Proc) (Proc, error) |
| + // RootfsWorkerGone stops the worker unit (kill=false) and proves its |
| + // cgroup empty. nil is the proof. |
| + RootfsWorkerGone(ctx context.Context, rt registry.Route, name string) error |
| +} |
| + |
| +var ( |
| + _ RootfsWorkerBackend = (*ExecBackend)(nil) |
| + _ RootfsWorkerBackend = (*SplitBackend)(nil) |
| +) |
| + |
| +// LaunchRootfsWorker implements RootfsWorkerBackend, in spawnRootfs's |
| +// shape: a rootfs row and a worker name; web's launch environment (a web |
| +// handle that kept none is refused, nothing prepared); every rootfs gate; |
| +// a control channel with a rootfs half; g's whole staged identity, its |
| +// image checked against its digest and named as rootfsImage names it |
| +// (RFS-2-C07 included) with the worker as its process; the worker's |
| +// directories, records and log listener (prepareWorker); its launch file, |
| +// the composed environment alone (rootfsWorkerVars through |
| +// rootfsLaunchEnv); the caller's exec gate, the last thing before root is |
| +// asked; then StartRootfsWorker at g's memory.max. Root's answers given |
| +// before systemctl start are refusals: the launch file goes and the |
| +// listener closes. Any other failure, or no invocation, may have started |
| +// the unit: a handle comes back with the error and the files stay, for |
| +// the caller's RootfsWorkerGone. |
| +func (b *ExecBackend) LaunchRootfsWorker(ctx context.Context, rt registry.Route, name string, g Gen, web Proc) (Proc, error) { |
| + if !rt.Rootfs() { |
| + return nil, refuseRootfs(fmt.Errorf("%s: a worker runs only on a rootfs instance", rt.Host)) |
| + } |
| + if !release.ValidWorkerName(name) { |
| + return nil, refuseRootfs(fmt.Errorf("%s: %q is not a worker name", rt.Host, name)) |
| + } |
| + var genEnv map[string]string |
| + if le, ok := web.(launchEnvProc); ok { |
| + genEnv = le.LaunchEnv() |
| + } |
| + if genEnv == nil { |
| + return nil, refuseRootfs(fmt.Errorf("%s: worker %s: its web generation kept no launch environment", rt.Host, name)) |
| + } |
| + haveControl := false |
| + if up, ok := web.(*unitProc); ok && up.ctl != nil { |
| + haveControl = true |
| + } |
| + if err := b.rootfsGates(ctx, rt); err != nil { |
| + return nil, err |
| + } |
| + rc, err := b.rootfsControl() |
| + if err != nil { |
| + return nil, refuseRootfs(fmt.Errorf("%s: %w", rt.Host, err)) |
| + } |
| + id, err := stagedIdentityOf(g) |
| + if err != nil { |
| + return nil, refuseRootfs(fmt.Errorf("%s: worker %s: %w", rt.Host, name, err)) |
| + } |
| + if err := release.VerifyStaged(id); err != nil { |
| + return nil, fmt.Errorf("%s: worker %s not started on %s: %w", rt.Host, name, id.Version, err) |
| + } |
| + img, err := b.rootfsImage(rt, id) |
| + if err != nil { |
| + return nil, err |
| + } |
| + img.Process = name |
| + p, logs, err := b.prepareWorker(rt, name) |
| + if err != nil { |
| + return nil, err |
| + } |
| + fail := func(err error) (Proc, error) { |
| + _ = os.Remove(filepath.Join(p.dataDir, instancectl.WorkerLaunchFileName(name))) |
| + logs.Close() |
| + return nil, err |
| + } |
| + env := rootfsLaunchEnv(b.rootfsWorkerVars(rt, g, p.dbPath, genEnv, haveControl)) |
| + if err := b.writeRootfsWorkerLaunch(p, rt.Host, name, env); err != nil { |
| + return fail(err) |
| + } |
| + // The caller's exec gate, right before root is asked: a refusal starts |
| + // nothing. |
| + if err := runExecGate(ctx); err != nil { |
| + return fail(err) |
| + } |
| + unit := rootfsUnitFor(rt, instancectl.RoleWorker, 0, name) |
| + inv, err := rc.StartRootfsWorker(ctx, rt.Host, name, g.Tier.MemoryMax, img) |
| + if errors.Is(err, instancectl.ErrStagedImage) || errors.Is(err, instancectl.ErrStartRefused) { |
| + // Answered before systemctl start: nothing of the build ran |
| + // (INV-4). |
| + return fail(refuseRootfs(fmt.Errorf("%s: start %s: %w", rt.Host, unit, err))) |
| + } |
| + if err != nil || inv == "" { |
| + if err == nil { |
| + err = exitedUnobserved{unit: unit} |
| + } |
| + // The request may have reached systemd: the unit may run, so its |
| + // files and listener stay with a handle the caller proves gone. |
| + log.Printf("activator: %s: start of %s (worker %s of build %s) failed, it may have begun: %v", rt.Host, unit, name, id.Version, err) |
| + up, perr := b.newRootfsWorkerProc(rt, name, p, inv, logs) |
| + if perr != nil { |
| + return nil, markStartUncertain(fmt.Errorf("%s: start %s: %w; %v", rt.Host, unit, err, perr)) |
| + } |
| + return up, markStartUncertain(fmt.Errorf("%s: start %s: %w", rt.Host, unit, err)) |
| + } |
| + log.Printf("activator: %s: started %s (worker %s of build %s) memory.max=%d", rt.Host, unit, name, id.Version, g.Tier.MemoryMax) |
| + up, err := b.newRootfsWorkerProc(rt, name, p, inv, logs) |
| + if err != nil { |
| + return nil, markStartUncertain(err) |
| + } |
| + return up, nil |
| +} |
| + |
| +// RootfsWorkerGone implements RootfsWorkerBackend: root stops the worker |
| +// unit (kill=false: root kills only a generation) on DeadlineControl, then |
| +// the agent reads the unit's cgroup (unitEvents) until it is empty or |
| +// roleEmptyBound passes. Neither bound is the caller's: a cancelled caller |
| +// still gets its answer. Every StopRootfs error is unproven (root's |
| +// ErrGenUnproven for a stop it could not prove or a start or removal in |
| +// flight, a 502, a transport failure), and so is a group still populated. |
| +// Only nil from both is the proof, and only a caller holding it removes |
| +// the worker's files (removeRootfsWorkerFiles). |
| +func (b *ExecBackend) RootfsWorkerGone(ctx context.Context, rt registry.Route, name string) error { |
| + if !rt.Rootfs() { |
| + return refuseRootfs(fmt.Errorf("%s: a worker runs only on a rootfs instance", rt.Host)) |
| + } |
| + unit := rootfsUnitFor(rt, instancectl.RoleWorker, 0, name) |
| + if unit == "" { |
| + return fmt.Errorf("%s: %q is not a worker name", rt.Host, name) |
| + } |
| + rc, err := b.rootfsControl() |
| + if err != nil { |
| + return fmt.Errorf("%s: %w", rt.Host, err) |
| + } |
| + sctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), instancectl.DeadlineControl) |
| + err = rc.StopRootfs(sctx, rt.Host, instancectl.RoleWorker, 0, name, false) |
| + cancel() |
| + if err != nil { |
| + log.Printf("activator: %s: stop %s: %v", rt.Host, unit, err) |
| + return fmt.Errorf("%s: stop %s: %w", rt.Host, unit, err) |
| + } |
| + wctx, wcancel := context.WithTimeout(context.WithoutCancel(ctx), roleEmptyBound) |
| + defer wcancel() |
| + if err := b.waitUnitCgroupEmpty(wctx, rt, unit); err != nil { |
| + log.Printf("activator: %s: %s after its stop: %v", rt.Host, unit, err) |
| + return fmt.Errorf("%s: %s after its stop: %w", rt.Host, unit, err) |
| + } |
| + return nil |
| +} |
| + |
| +// removeRootfsWorkerFiles removes what the agent wrote for the named |
| +// worker: its launch file in the instance directory and every exit record |
| +// of it in the run directory, with os.Remove (which never follows the |
| +// final component). Another worker's and every generation's files stay. |
| +// It is called only by a caller holding RootfsWorkerGone's nil (INV-2). |
| +func (b *ExecBackend) removeRootfsWorkerFiles(rt registry.Route, name string) { |
| + p := b.pathsFor(rt) |
| + if !rt.Rootfs() || p.layout != LayoutNested || !release.ValidWorkerName(name) { |
| + return |
| + } |
| + _ = os.Remove(filepath.Join(p.dataDir, instancectl.WorkerLaunchFileName(name))) |
| + entries, err := os.ReadDir(p.runDir) |
| + if err != nil { |
| + return |
| + } |
| + for _, e := range entries { |
| + if strings.HasPrefix(e.Name(), instancectl.WorkerExitPrefix(name)) { |
| + _ = os.Remove(filepath.Join(p.runDir, e.Name())) |
| + } |
| + } |
| +} |
diff --git a/internal/activator/backend_unit.go b/internal/activator/backend_unit.go| index c027f207e..ec26c6b18 100644 |
| --- a/internal/activator/backend_unit.go |
| +++ b/internal/activator/backend_unit.go |
| @@ -395,6 +395,29 @@ func (b *SplitBackend) StartRelease(ctx context.Context, rt registry.Route, id r |
| return nil, refuseRootfs(fmt.Errorf("%s: %w", rt.Host, errNoRootfsControl)) |
| } |
| +// LaunchRootfsWorker forwards a rootfs worker's start (Group W) to the |
| +// exec side. A unit-backed row, or an exec side without workers, is |
| +// refused as Processes refuses it: no handle, so nothing ran. |
| +func (b *SplitBackend) LaunchRootfsWorker(ctx context.Context, rt registry.Route, name string, g Gen, web Proc) (Proc, error) { |
| + if rt.Backing != registry.BackingUnit { |
| + if w, ok := b.Exec.(RootfsWorkerBackend); ok { |
| + return w.LaunchRootfsWorker(ctx, rt, name, g, web) |
| + } |
| + } |
| + return nil, refuseRootfs(fmt.Errorf("%s: %w", rt.Host, errNoRootfsControl)) |
| +} |
| + |
| +// RootfsWorkerGone forwards a rootfs worker's proof (Group W) to the exec |
| +// side, refused like LaunchRootfsWorker: a refusal is never the proof. |
| +func (b *SplitBackend) RootfsWorkerGone(ctx context.Context, rt registry.Route, name string) error { |
| + if rt.Backing != registry.BackingUnit { |
| + if w, ok := b.Exec.(RootfsWorkerBackend); ok { |
| + return w.RootfsWorkerGone(ctx, rt, name) |
| + } |
| + } |
| + return refuseRootfs(fmt.Errorf("%s: %w", rt.Host, errNoRootfsControl)) |
| +} |
| + |
| func (b *SplitBackend) Restore(ctx context.Context, rt registry.Route) (bool, error) { |
| return b.pick(rt).Restore(ctx, rt) |
| } |
diff --git a/internal/activator/prepare.go b/internal/activator/prepare.go| index 4ff929947..e921303f8 100644 |
| --- a/internal/activator/prepare.go |
| +++ b/internal/activator/prepare.go |
| @@ -191,6 +191,54 @@ func (b *ExecBackend) prepareKeyedAt(rt registry.Route, role instancectl.Role, s |
| return p, ctl, logs, env, keyLayer, nil |
| } |
| +// prepareWorker is prepare for a rootfs worker (rootfs apps Plan 3, W1): |
| +// the instance's two directories and the log socket's, this worker's |
| +// stale exit records cleared, and its log listener bound where root's |
| +// WorkerDropIn points StandardOutput= (workerLogSocket). It reads no env |
| +// file: a worker's environment is its web generation's launch environment |
| +// (LaunchRootfsWorker), never the sidecar's file prepareKeyedAt's default |
| +// arm reads. It binds no control listener (the web generation holds the |
| +// instance's) and asks no replica gate (a rootfs record is never a |
| +// replica). Another worker's and every generation's records are kept. |
| +func (b *ExecBackend) prepareWorker(rt registry.Route, name string) (instancePaths, *logListener, error) { |
| + p := b.pathsFor(rt) |
| + if !release.ValidWorkerName(name) { |
| + return p, nil, fmt.Errorf("%s: %q is not a worker name", rt.Host, name) |
| + } |
| + if err := os.MkdirAll(p.dataDir, 0o700); err != nil { |
| + return p, nil, err |
| + } |
| + if err := os.MkdirAll(p.runDir, 0o750|os.ModeSetgid); err != nil { |
| + return p, nil, err |
| + } |
| + sock := b.workerLogSocket(rt.Host, name) |
| + if err := os.MkdirAll(filepath.Dir(sock), 0o700); err != nil { |
| + return p, nil, err |
| + } |
| + if entries, err := os.ReadDir(p.runDir); err == nil { |
| + for _, e := range entries { |
| + if strings.HasPrefix(e.Name(), instancectl.WorkerExitPrefix(name)) { |
| + _ = os.Remove(filepath.Join(p.runDir, e.Name())) |
| + } |
| + } |
| + } |
| + logs, err := listenLogs(sock, b.logEmitter(rt)) |
| + if err != nil { |
| + return p, nil, fmt.Errorf("log listener for %s worker %s: %w", rt.Host, name, err) |
| + } |
| + return p, logs, nil |
| +} |
| + |
| +// workerLogSocket is a worker's log socket, honouring the test override |
| +// of the run directory (RunDirOverride) as logSocketFor does; otherwise |
| +// root's WorkerLogSocket, the path WorkerDropIn names. |
| +func (b *ExecBackend) workerLogSocket(host, name string) string { |
| + if b.RunDirOverride != "" { |
| + return filepath.Join(b.RunDirOverride, "logs", instancectl.WorkerKey(host, name)+".worker.sock") |
| + } |
| + return instancectl.WorkerLogSocket(host, name) |
| +} |
| + |
| // exitPrefix is the exit records prepare clears before a start: this |
| // role's for the original templates, this generation's alone otherwise. |
| // A sibling generation's record is never touched (zero-downtime spec |
| @@ -295,17 +343,30 @@ func (b *ExecBackend) writeRootfsLaunchFor(p instancePaths, role instancectl.Rol |
| Runtime: registry.RuntimeRootfsV1, Process: process, Env: env}) |
| } |
| +// writeRootfsWorkerLaunch is writeRootfsLaunchFor for the named worker: |
| +// launch.worker.<name>.json, the worker's process and env, no argv. |
| +func (b *ExecBackend) writeRootfsWorkerLaunch(p instancePaths, host, name string, env []string) error { |
| + return writeLaunchNamed(p, instancectl.WorkerLaunchFileName(name), instancectl.Launch{Schema: instancectl.LaunchSchemaRootfs, Host: host, |
| + Runtime: registry.RuntimeRootfsV1, Process: name, Env: env}) |
| +} |
| + |
| // writeLaunchFile is both shapes' atomic write, under the role's or the |
| // generation's launch file name. |
| func writeLaunchFile(p instancePaths, role instancectl.Role, gen uint64, l instancectl.Launch) error { |
| - raw, err := json.MarshalIndent(l, "", " ") |
| - if err != nil { |
| - return err |
| - } |
| name := instancectl.LaunchFileName(role) |
| if gen != 0 { |
| name = instancectl.GenLaunchFileName(gen) |
| } |
| + return writeLaunchNamed(p, name, l) |
| +} |
| + |
| +// writeLaunchNamed is the atomic write of a launch file named name in the |
| +// instance directory. |
| +func writeLaunchNamed(p instancePaths, name string, l instancectl.Launch) error { |
| + raw, err := json.MarshalIndent(l, "", " ") |
| + if err != nil { |
| + return err |
| + } |
| return instancefs.WriteAtomic(p.dataDir, name, append(raw, '\n'), 0o600) |
| } |
diff --git a/internal/activator/production_backend_test.go b/internal/activator/production_backend_test.go| index cbd6fc1ef..487fffe04 100644 |
| --- a/internal/activator/production_backend_test.go |
| +++ b/internal/activator/production_backend_test.go |
| @@ -84,6 +84,20 @@ func TestProductionBackendImplementsRootfsSeams(t *testing.T) { |
| } |
| return err |
| }, |
| + // W1a: both worker methods refuse, LaunchRootfsWorker hands back no |
| + // handle, and RootfsWorkerGone's refusal is never the proof. |
| + "RootfsWorkerBackend": func() error { |
| + w, ok := b.(RootfsWorkerBackend) |
| + if !ok { |
| + t.Fatal("SplitBackend is not a RootfsWorkerBackend") |
| + } |
| + id := stagedRootfsIdentity(t, eb, "v2") |
| + g := Gen{N: 7, Build: id.Version, StagedPath: id.StagedPath, Digest: id.Digest} |
| + if p, err := w.LaunchRootfsWorker(context.Background(), unit, "jobs", g, &fakeProc{}); p != nil || !errors.Is(err, errNoRootfsControl) || !errors.Is(err, errRootfsRefused) { |
| + t.Errorf("LaunchRootfsWorker on a unit row = %v, %v; want a marked errNoRootfsControl", p, err) |
| + } |
| + return w.RootfsWorkerGone(context.Background(), unit, "jobs") |
| + }, |
| } |
| for name, refusal := range rows { |
| if err := refusal(); err == nil { |
| @@ -105,6 +119,9 @@ func TestProductionBackendImplementsRootfsSeams(t *testing.T) { |
| if err := rows["ReleaseBackend"](); !errors.Is(err, errNoRootfsControl) || !errors.Is(err, errRootfsRefused) { |
| t.Errorf("StartRelease on a unit row = %v, want a marked errNoRootfsControl", err) |
| } |
| + if err := rows["RootfsWorkerBackend"](); !errors.Is(err, errNoRootfsControl) || !errors.Is(err, errRootfsRefused) { |
| + t.Errorf("RootfsWorkerGone on a unit row = %v, want a marked errNoRootfsControl", err) |
| + } |
| // An exec row is forwarded: the exec side's own answers. |
| if err := b.(rootfsStartable).rootfsStartable(context.Background(), rootfsRoute(eb)); err != nil { |
| t.Errorf("rootfsStartable on the exec side's passing row = %v", err) |
diff --git a/internal/activator/rootfs_invariants_test.go b/internal/activator/rootfs_invariants_test.go| index 00af978a2..13f0b5c7a 100644 |
| --- a/internal/activator/rootfs_invariants_test.go |
| +++ b/internal/activator/rootfs_invariants_test.go |
| @@ -705,6 +705,61 @@ var rootfsProofHandles = map[string]func(t *testing.T, r *rootfsProofRig){ |
| } |
| r.noBinaryVerb(t) |
| }, |
| + // W1a [pf W1.26]: a rootfs worker's handle stops and is proven through |
| + // the worker unit alone, with no binary unit loaded and that unit's |
| + // group populated: its Stop and RootfsWorkerGone stay unproven, the |
| + // launch file stays, and root is never asked to kill a worker. Proven |
| + // once the group empties. |
| + "rootfs worker unitProc": func(t *testing.T, r *rootfsProofRig) { |
| + old := roleEmptyBound |
| + roleEmptyBound = 100 * time.Millisecond |
| + t.Cleanup(func() { roleEmptyBound = old }) |
| + unit := instancectl.WorkerUnitName(r.rt.Host, "jobs") |
| + r.mu.Lock() |
| + r.unit[unit] = [2]string{"active", "inv1"} |
| + r.mu.Unlock() |
| + r.setPopulated(t, unit, true) |
| + id := stagedRootfsIdentity(t, r.b, "v2") |
| + g := Gen{N: 7, Control: nestedGenSocketIn(r.b.pathsFor(r.rt).runDir, 7) + ".control", Build: id.Version, StagedPath: id.StagedPath, Digest: id.Digest, Tier: r.b.GenTier(r.rt, id.Version)} |
| + p, err := r.b.LaunchRootfsWorker(context.Background(), r.rt, "jobs", g, &fakeProc{}) |
| + if err != nil { |
| + t.Fatalf("LaunchRootfsWorker: %v", err) |
| + } |
| + t.Cleanup(func() { |
| + r.setPopulated(t, unit, false) |
| + waitFor(t, "the worker to exit once its group is empty", p.Exited) |
| + }) |
| + if up := p.(*unitProc); up.unit != unit { |
| + t.Fatalf("the handle watches %q, want %q", up.unit, unit) |
| + } |
| + r.ctl.mustHaveCallPrefix(t, "start-rootfs-worker "+r.rt.Host+" jobs ") |
| + ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond) |
| + defer cancel() |
| + if err := p.Stop(ctx); !errors.Is(err, ErrStillRunning) { |
| + t.Fatalf("Stop with %s's group populated = %v, want ErrStillRunning", unit, err) |
| + } |
| + if p.Exited() { |
| + t.Fatal("the worker read as exited while its unit's group is populated") |
| + } |
| + r.ctl.mustHaveCallPrefix(t, "stop-rootfs "+r.rt.Host+" role=worker gen=0 worker=jobs kill=false") |
| + if err := r.b.RootfsWorkerGone(context.Background(), r.rt, "jobs"); err == nil { |
| + t.Fatalf("RootfsWorkerGone proved the worker gone while %s's group is populated", unit) |
| + } |
| + for _, c := range r.ctl.callList() { |
| + if strings.Contains(c, "role=worker") && strings.Contains(c, "kill=true") { |
| + t.Errorf("root was asked to kill a worker: %q", c) |
| + } |
| + } |
| + r.noBinaryVerb(t) |
| + if _, err := os.Stat(filepath.Join(r.b.pathsFor(r.rt).dataDir, instancectl.WorkerLaunchFileName("jobs"))); err != nil { |
| + t.Errorf("the unproven worker's launch file: %v, want it kept", err) |
| + } |
| + r.setPopulated(t, unit, false) |
| + if err := r.b.RootfsWorkerGone(context.Background(), r.rt, "jobs"); err != nil { |
| + t.Fatalf("RootfsWorkerGone once %s's group is empty: %v", unit, err) |
| + } |
| + r.noBinaryVerb(t) |
| + }, |
| } |
| // stagedRootfsIdentity stages acme/shop at ver as root's staging leaves it |
| @@ -1058,6 +1113,24 @@ var rootfsLaunchRows = map[string]func(t *testing.T) (instancectl.Launch, map[st |
| t.Cleanup(func() { u.(*cmdUnit).out.Close(); u.(*cmdUnit).errs.Close() }) |
| return readLaunchFile(t, eb, rt, instancectl.RoleCmd), vars |
| }, |
| + // W1a: a worker's launch file, written by LaunchRootfsWorker through |
| + // the production backend from its web generation's launch environment. |
| + "worker": func(t *testing.T) (instancectl.Launch, map[string]string) { |
| + eb, ctl, rt, units := newWorkerBackend(t) |
| + var b Backend = productionBackend(t, eb) |
| + web, g := startWorkerWeb(t, eb, ctl, rt, units, "SHOP_MODE=live\n") |
| + units.set(instancectl.WorkerUnitName(rt.Host, "jobs"), "active", "inv1", true) |
| + wp, err := b.(RootfsWorkerBackend).LaunchRootfsWorker(context.Background(), rt, "jobs", g, web) |
| + if err != nil { |
| + t.Fatalf("LaunchRootfsWorker: %v", err) |
| + } |
| + t.Cleanup(func() { wp.Stop(context.Background()) }) //nolint:errcheck |
| + vars := eb.rootfsWorkerVars(rt, g, eb.pathsFor(rt).dbPath, web.LaunchEnv(), true) |
| + if vars["SHOP_MODE"] != "live" { |
| + t.Fatalf("the instance's file did not reach the composed variables: %v", vars) |
| + } |
| + return readLaunchNamed(t, eb, rt, instancectl.WorkerLaunchFileName("jobs")), vars |
| + }, |
| } |
| // rootfsComposerRows: process -> its composer's variables, production-wired: |
| @@ -1085,6 +1158,13 @@ var rootfsComposerRows = map[string]func(t *testing.T, envFile string) map[strin |
| } |
| return vars |
| }, |
| + // W1a: a worker's composer, over the file environment its web |
| + // generation launched with. |
| + "worker": func(t *testing.T, envFile string) map[string]string { |
| + b, ctl, rt, units := newWorkerBackend(t) |
| + web, g := startWorkerWeb(t, b, ctl, rt, units, envFile) |
| + return b.rootfsWorkerVars(rt, g, b.pathsFor(rt).dbPath, web.LaunchEnv(), web.ctl != nil) |
| + }, |
| } |
| // rootfsAgentOnlyEnv is the agent's own environment for the INV-5 test: |
diff --git a/internal/activator/rootfsenv.go b/internal/activator/rootfsenv.go| index f51cac0d2..467406e51 100644 |
| --- a/internal/activator/rootfsenv.go |
| +++ b/internal/activator/rootfsenv.go |
| @@ -29,3 +29,14 @@ func (b *ExecBackend) rootfsCmdVars(rt registry.Route, fileEnv map[string]string |
| func (b *ExecBackend) rootfsReleaseVars(rt registry.Route, fileEnv map[string]string, dbPath string) map[string]string { |
| return withoutVars(b.rootfsCmdVars(rt, fileEnv, dbPath, "", ""), "CARLOS_RUN_ID", "CARLOS_RUN_DIR") |
| } |
| + |
| +// rootfsWorkerVars is a rootfs worker's environment (Group W, D1): the |
| +// file environment genEnv its web generation g launched with (that |
| +// handle's LaunchEnv), the agent-owned variables as web got them, with |
| +// g's control socket only when web's listener bound (haveControl), then |
| +// rootfsVars with the row's canonical socket and dbPath. So a worker's |
| +// launch file is web's, CARLOS_SOCKET aside: a worker serves nothing, and |
| +// names the instance's socket, never a generation's. |
| +func (b *ExecBackend) rootfsWorkerVars(rt registry.Route, g Gen, dbPath string, genEnv map[string]string, haveControl bool) map[string]string { |
| + return rootfsVars(b.agentOwnedVars(rt, g.Control, genEnv, haveControl), rt.Socket, dbPath) |
| +} |
diff --git a/internal/activator/rootfsworkers_backend_test.go b/internal/activator/rootfsworkers_backend_test.go| new file mode 100644 |
| index 000000000..daf7be644 |
| --- /dev/null |
| +++ b/internal/activator/rootfsworkers_backend_test.go |
| @@ -0,0 +1,746 @@ |
| +package activator |
| + |
| +// Rootfs apps Plan 3, Group W, Task W1a: the agent's half of a rootfs |
| +// worker. A worker of a rootfs generation starts from that generation's |
| +// image with that generation's environment, is observed, stopped and |
| +// proven gone through the rootfs worker unit, and through nothing else. |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "net" |
| + "os" |
| + "path/filepath" |
| + "slices" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/instancectl" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// workerUnits is per-unit systemd and cgroup state for the worker tests. |
| +// A unit not set is inactive, not loaded and has no cgroup. stopEmpties |
| +// makes a stop of a role leave that role's units inactive and empty, as a |
| +// proven stop by root does. |
| +type workerUnits struct { |
| + mu sync.Mutex |
| + m map[string]workerUnitState |
| + read []string // every unit whose cgroup was read |
| + stopEmpties bool |
| +} |
| + |
| +type workerUnitState struct { |
| + active, inv string |
| + populated bool |
| +} |
| + |
| +func newWorkerUnits() *workerUnits { |
| + return &workerUnits{m: map[string]workerUnitState{}, stopEmpties: true} |
| +} |
| + |
| +func (u *workerUnits) set(unit, active, inv string, populated bool) { |
| + u.mu.Lock() |
| + u.m[unit] = workerUnitState{active, inv, populated} |
| + u.mu.Unlock() |
| +} |
| + |
| +func (u *workerUnits) state(_ context.Context, unit string) (string, string, error) { |
| + u.mu.Lock() |
| + defer u.mu.Unlock() |
| + s, ok := u.m[unit] |
| + if !ok { |
| + return "inactive", "", nil |
| + } |
| + return s.active, s.inv, nil |
| +} |
| + |
| +func (u *workerUnits) events(_ string, unit string) (bool, bool, error) { |
| + u.mu.Lock() |
| + defer u.mu.Unlock() |
| + u.read = append(u.read, unit) |
| + s := u.m[unit] |
| + return s.populated, s.populated, nil |
| +} |
| + |
| +func (u *workerUnits) readUnits() []string { |
| + u.mu.Lock() |
| + defer u.mu.Unlock() |
| + return slices.Clone(u.read) |
| +} |
| + |
| +// stopped is the fake control's stop hook: a worker stop empties every |
| +// worker unit, any other stop every other unit. |
| +func (u *workerUnits) stopped(_ string, role instancectl.Role) { |
| + u.mu.Lock() |
| + defer u.mu.Unlock() |
| + if !u.stopEmpties { |
| + return |
| + } |
| + for name, s := range u.m { |
| + if strings.HasPrefix(name, instancectl.UnitPrefixRootfsWorker) == (role == instancectl.RoleWorker) { |
| + u.m[name] = workerUnitState{"inactive", s.inv, false} |
| + } |
| + } |
| +} |
| + |
| +// newWorkerBackend is newRootfsBackend with generations on and per-unit |
| +// state: every rootfs gate passes and acme/shop is staged. |
| +func newWorkerBackend(t *testing.T) (*ExecBackend, *fakeControl, registry.Route, *workerUnits) { |
| + t.Helper() |
| + b, ctl := newRootfsBackend(t) |
| + b.GenContainment = true |
| + units := newWorkerUnits() |
| + b.UnitState, b.CgroupEvents = units.state, units.events |
| + ctl.stopHook = units.stopped |
| + return b, ctl, rootfsRoute(b), units |
| +} |
| + |
| +// startWorkerWeb starts rootfs web generation 7 of acme/shop v2 through |
| +// the real backend, envFile as the instance's own file, and returns its |
| +// handle and generation. |
| +func startWorkerWeb(t *testing.T, b *ExecBackend, ctl *fakeControl, rt registry.Route, units *workerUnits, envFile string) (*unitProc, Gen) { |
| + t.Helper() |
| + writeInstanceEnv(t, b, rt, envFile) |
| + id := stagedRootfsIdentity(t, b, "v2") |
| + sock := nestedGenSocketIn(b.pathsFor(rt).runDir, 7) |
| + units.set(instancectl.RootfsGenUnitName(rt.Host, 7), "active", "inv1", true) |
| + ctl.onStart = serveHealthy(t, sock) |
| + p, g, err := b.StartGenExe(context.Background(), rt, 7, true, id) |
| + if err != nil { |
| + t.Fatalf("StartGenExe: %v", err) |
| + } |
| + t.Cleanup(func() { p.Stop(context.Background()) }) //nolint:errcheck |
| + if g.Build != "v2" || g.StagedPath != id.StagedPath || g.Digest != id.Digest || g.Control != sock+".control" { |
| + t.Fatalf("web generation = %+v", g) |
| + } |
| + return p.(*unitProc), g |
| +} |
| + |
| +// stagedWorkerGen is generation 7 of acme/shop v2 as a Gen, staged, for a |
| +// test whose web handle is not a started one. |
| +func stagedWorkerGen(t *testing.T, b *ExecBackend, rt registry.Route) Gen { |
| + t.Helper() |
| + id := stagedRootfsIdentity(t, b, "v2") |
| + sock := nestedGenSocketIn(b.pathsFor(rt).runDir, 7) |
| + return Gen{N: 7, Socket: sock, Control: sock + ".control", Build: id.Version, StagedPath: id.StagedPath, Digest: id.Digest, Tier: b.GenTier(rt, id.Version)} |
| +} |
| + |
| +func workerLaunchPath(b *ExecBackend, rt registry.Route, name string) string { |
| + return filepath.Join(b.pathsFor(rt).dataDir, instancectl.WorkerLaunchFileName(name)) |
| +} |
| + |
| +// socketBound reports whether something accepts on the unix socket path. |
| +func socketBound(path string) bool { |
| + c, err := net.DialTimeout("unix", path, time.Second) |
| + if err != nil { |
| + return false |
| + } |
| + c.Close() |
| + return true |
| +} |
| + |
| +func stopWorker(t *testing.T, p Proc) { |
| + t.Helper() |
| + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) |
| + defer cancel() |
| + if err := p.Stop(ctx); err != nil { |
| + t.Errorf("stop the worker: %v", err) |
| + } |
| +} |
| + |
| +func TestRootfsWorkerLaunchIsTheGenerationsEnv(t *testing.T) { |
| + t.Parallel() |
| + b, ctl, rt, units := newWorkerBackend(t) |
| + web, g := startWorkerWeb(t, b, ctl, rt, units, "SHOP_MODE=live\nCARLOS_SOCKET=/run/carlos/other.sock\n") |
| + if web.ctl == nil { |
| + t.Fatal("the web generation's control listener did not bind; this test needs it bound") |
| + } |
| + units.set(instancectl.WorkerUnitName(rt.Host, "jobs"), "active", "inv1", true) |
| + before := len(ctl.callList()) |
| + wp, err := b.LaunchRootfsWorker(context.Background(), rt, "jobs", g, web) |
| + if err != nil { |
| + t.Fatalf("LaunchRootfsWorker: %v", err) |
| + } |
| + t.Cleanup(func() { stopWorker(t, wp) }) |
| + want := fmt.Sprintf("start-rootfs-worker %s jobs memory_max=%d process=jobs version=%s", rt.Host, g.Tier.MemoryMax, g.Build) |
| + if calls := ctl.callList()[before:]; !slices.Equal(calls, []string{want}) { |
| + t.Fatalf("root was asked %q, want exactly %q", calls, want) |
| + } |
| + if img := ctl.lastRootfsImage(); img.Path != g.StagedPath || img.Digest != g.Digest || img.Version != g.Build || img.Process != "jobs" || len(img.Argv) != 0 { |
| + t.Errorf("image named to root = %+v, want the generation's with process jobs", img) |
| + } |
| + l := readLaunchNamed(t, b, rt, instancectl.WorkerLaunchFileName("jobs")) |
| + if l.Schema != instancectl.LaunchSchemaRootfs || l.Runtime != registry.RuntimeRootfsV1 || l.Process != "jobs" || l.Host != rt.Host || len(l.Argv) != 0 { |
| + t.Errorf("worker launch = %+v", l) |
| + } |
| + p := b.pathsFor(rt) |
| + if wantEnv := rootfsLaunchEnv(b.rootfsWorkerVars(rt, g, p.dbPath, web.LaunchEnv(), true)); !slices.Equal(l.Env, wantEnv) { |
| + t.Errorf("worker env:\n%s\nwant rootfsLaunchEnv(rootfsWorkerVars):\n%s", strings.Join(l.Env, "\n"), strings.Join(wantEnv, "\n")) |
| + } |
| + env := envMap(t, l.Env) |
| + if env["CARLOS_SOCKET"] != rt.Socket || env["CARLOS_CONTROL_SOCKET"] != g.Control || env["CARLOS_DB"] != rt.DBPath || env["SHOP_MODE"] != "live" { |
| + t.Errorf("socket %q control %q db %q mode %q; want %q, %q, %q, live", env["CARLOS_SOCKET"], env["CARLOS_CONTROL_SOCKET"], env["CARLOS_DB"], env["SHOP_MODE"], rt.Socket, g.Control, rt.DBPath) |
| + } |
| + // The web generation's own launch file, less its socket, is the |
| + // worker's, less its socket. |
| + webEnv := envMap(t, readLaunchNamed(t, b, rt, instancectl.GenLaunchFileName(7)).Env) |
| + if webEnv["CARLOS_SOCKET"] != g.Socket { |
| + t.Fatalf("web's socket %q, want %q", webEnv["CARLOS_SOCKET"], g.Socket) |
| + } |
| + delete(webEnv, "CARLOS_SOCKET") |
| + delete(env, "CARLOS_SOCKET") |
| + if !mapsEqual(webEnv, env) { |
| + t.Errorf("worker env less CARLOS_SOCKET:\n%v\nweb env less CARLOS_SOCKET:\n%v", env, webEnv) |
| + } |
| + |
| + // A web handle whose control listener never bound: no control socket |
| + // for the worker either. |
| + units.set(instancectl.WorkerUnitName(rt.Host, "mail"), "active", "inv1", true) |
| + unbound := &unitProc{launchEnv: web.LaunchEnv()} |
| + mp, err := b.LaunchRootfsWorker(context.Background(), rt, "mail", g, unbound) |
| + if err != nil { |
| + t.Fatalf("LaunchRootfsWorker beside an unbound listener: %v", err) |
| + } |
| + t.Cleanup(func() { stopWorker(t, mp) }) |
| + menv := envMap(t, readLaunchNamed(t, b, rt, instancectl.WorkerLaunchFileName("mail")).Env) |
| + if v, ok := menv["CARLOS_CONTROL_SOCKET"]; ok { |
| + t.Errorf("CARLOS_CONTROL_SOCKET=%q for a listener that never bound", v) |
| + } |
| + if menv["SHOP_MODE"] != "live" || menv["CARLOS_SOCKET"] != rt.Socket { |
| + t.Errorf("mail env = %v", menv) |
| + } |
| + |
| + // No launch environment: refused, nothing prepared, root asked nothing. |
| + for name, w := range map[string]Proc{"a handle with no launch env": &unitProc{}, "not a launchEnvProc": bareProc{}, "nil": nil} { |
| + before := len(ctl.callList()) |
| + p, err := b.LaunchRootfsWorker(context.Background(), rt, "cron", g, w) |
| + if p != nil || !errors.Is(err, errRootfsRefused) { |
| + t.Errorf("%s: LaunchRootfsWorker = %v, %v; want a refusal", name, p, err) |
| + } |
| + if calls := ctl.callList()[before:]; len(calls) != 0 { |
| + t.Errorf("%s: root was asked %q", name, calls) |
| + } |
| + if _, err := os.Stat(workerLaunchPath(b, rt, "cron")); !os.IsNotExist(err) { |
| + t.Errorf("%s: a launch file was written: %v", name, err) |
| + } |
| + if _, err := os.Stat(filepath.Dir(b.workerLogSocket(rt.Host, "cron"))); err == nil && socketBound(b.workerLogSocket(rt.Host, "cron")) { |
| + t.Errorf("%s: the worker's log listener was bound", name) |
| + } |
| + } |
| +} |
| + |
| +// ctxControl is the fake control with a StopRootfs that, like the real |
| +// client's, fails on a context that has already ended. |
| +type ctxControl struct{ *fakeControl } |
| + |
| +func (c ctxControl) StopRootfs(ctx context.Context, host string, role instancectl.Role, gen uint64, worker string, kill bool) error { |
| + if err := ctx.Err(); err != nil { |
| + c.rec(fmt.Sprintf("stop-rootfs %s role=%s gen=%d worker=%s kill=%v", host, role, gen, worker, kill)) |
| + return err |
| + } |
| + return c.fakeControl.StopRootfs(ctx, host, role, gen, worker, kill) |
| +} |
| + |
| +// bareProc is a Proc and nothing more: it kept no launch environment. |
| +type bareProc struct{} |
| + |
| +func (bareProc) Stop(context.Context) error { return nil } |
| +func (bareProc) Exited() bool { return false } |
| + |
| +func mapsEqual(a, b map[string]string) bool { |
| + if len(a) != len(b) { |
| + return false |
| + } |
| + for k, v := range a { |
| + if w, ok := b[k]; !ok || w != v { |
| + return false |
| + } |
| + } |
| + return true |
| +} |
| + |
| +func TestRootfsWorkerIdentity(t *testing.T) { |
| + t.Parallel() |
| + b, ctl, rt, units := newWorkerBackend(t) |
| + p := b.pathsFor(rt) |
| + for _, dir := range []string{p.dataDir, p.runDir} { |
| + if err := os.MkdirAll(dir, 0o700); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + // The sidecar's env file, with a marker no worker may carry. |
| + if err := os.WriteFile(p.sidecarEnv, []byte("SIDECAR_MARKER=sidecar\n"), 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + records := map[string]bool{ // name -> cleared by prepareWorker(jobs) |
| + instancectl.WorkerExitRecordName("jobs", "old"): true, |
| + instancectl.WorkerExitRecordName("jobs", "older"): true, |
| + instancectl.WorkerExitRecordName("mail", "old"): false, |
| + instancectl.GenExitRecordName(7, "old"): false, |
| + instancectl.ExitRecordName(instancectl.RoleRun, "old"): false, |
| + } |
| + for name := range records { |
| + if err := os.WriteFile(filepath.Join(p.runDir, name), []byte("{}"), 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + pp, logs, err := b.prepareWorker(rt, "jobs") |
| + if err != nil { |
| + t.Fatalf("prepareWorker: %v", err) |
| + } |
| + if pp.dataDir != p.dataDir || pp.runDir != p.runDir { |
| + t.Errorf("paths = %+v", pp) |
| + } |
| + sock := b.workerLogSocket(rt.Host, "jobs") |
| + if want := filepath.Join(b.RunDirOverride, "logs", instancectl.WorkerKey(rt.Host, "jobs")+".worker.sock"); sock != want { |
| + t.Errorf("workerLogSocket under the override = %q, want %q", sock, want) |
| + } |
| + if !socketBound(sock) { |
| + t.Error("the worker's log listener is not bound at workerLogSocket") |
| + } |
| + logs.Close() |
| + if socketBound(sock) { |
| + t.Error("the log listener still accepts after Close") |
| + } |
| + if socketBound(rt.Socket+".control") || socketBound(nestedGenSocketIn(p.runDir, 7)+".control") { |
| + t.Error("prepareWorker bound a control listener") |
| + } |
| + for name, cleared := range records { |
| + _, err := os.Stat(filepath.Join(p.runDir, name)) |
| + if gone := os.IsNotExist(err); gone != cleared { |
| + t.Errorf("record %s gone = %v, want %v", name, gone, cleared) |
| + } |
| + } |
| + if got, want := (&ExecBackend{}).workerLogSocket(rt.Host, "jobs"), instancectl.WorkerLogSocket(rt.Host, "jobs"); got != want { |
| + t.Errorf("workerLogSocket = %q, want root's %q (WorkerDropIn's StandardOutput=)", got, want) |
| + } |
| + |
| + // The handle: its unit, its stop, its exit record's name. |
| + units.set(instancectl.WorkerUnitName(rt.Host, "jobs"), "active", "inv1", true) |
| + g := stagedWorkerGen(t, b, rt) |
| + wp, err := b.LaunchRootfsWorker(context.Background(), rt, "jobs", g, &fakeProc{}) |
| + if err != nil { |
| + t.Fatalf("LaunchRootfsWorker: %v", err) |
| + } |
| + if env := envMap(t, readLaunchNamed(t, b, rt, instancectl.WorkerLaunchFileName("jobs")).Env); env["SIDECAR_MARKER"] != "" { |
| + t.Error("the sidecar's env file reached the worker's launch") |
| + } |
| + up := wp.(*unitProc) |
| + if up.unit != instancectl.WorkerUnitName(rt.Host, "jobs") || up.role != instancectl.RoleWorker || up.worker != "jobs" || up.gen != 0 { |
| + t.Errorf("handle unit %q role %s worker %q gen %d", up.unit, up.role, up.worker, up.gen) |
| + } |
| + if got, want := up.recordName(), instancectl.WorkerExitRecordName("jobs", "inv1"); got != want { |
| + t.Errorf("recordName = %q, want %q", got, want) |
| + } |
| + if up.ctl != nil { |
| + t.Error("the worker's handle holds a control listener") |
| + } |
| + stopWorker(t, wp) |
| + ctl.mustHaveCallPrefix(t, "stop-rootfs "+rt.Host+" role=worker gen=0 worker=jobs kill=false") |
| + noCallStarts(t, ctl, "stop "+rt.Host, "stopgen", "start "+rt.Host, "startgen") |
| + for _, c := range ctl.callList() { |
| + if strings.Contains(c, "role=worker") && strings.Contains(c, "kill=true") { |
| + t.Errorf("root was asked to kill a worker: %q", c) |
| + } |
| + } |
| + if !slices.Contains(units.readUnits(), instancectl.WorkerUnitName(rt.Host, "jobs")) { |
| + t.Errorf("the observer's proof read %v, not the worker unit", units.readUnits()) |
| + } |
| + // The launch file is the Service's to remove, after RootfsWorkerGone. |
| + if _, err := os.Stat(workerLaunchPath(b, rt, "jobs")); err != nil { |
| + t.Errorf("the worker's launch file after the handle's stop: %v, want it kept", err) |
| + } |
| + |
| + // The names: a worker's is rootfsUnitFor's alone. |
| + if got := unitNameFor(rt, instancectl.RoleWorker, 0); got != "" { |
| + t.Errorf("unitNameFor(worker) = %q, want \"\"", got) |
| + } |
| + if got := rootfsUnitFor(rt, instancectl.RoleWorker, 0, "jobs"); got != instancectl.WorkerUnitName(rt.Host, "jobs") { |
| + t.Errorf("rootfsUnitFor(worker jobs) = %q", got) |
| + } |
| + for _, role := range []instancectl.Role{instancectl.RoleRun, instancectl.RoleCmd, instancectl.RoleWorker} { |
| + if got, want := rootfsUnitFor(rt, role, 0, ""), unitNameFor(rt, role, 0); got != want { |
| + t.Errorf("rootfsUnitFor(%s) = %q, want unitNameFor's %q", role, got, want) |
| + } |
| + } |
| + if got, want := rootfsUnitFor(rt, instancectl.RoleRun, 7, ""), instancectl.RootfsGenUnitName(rt.Host, 7); got != want { |
| + t.Errorf("rootfsUnitFor(run 7) = %q, want %q", got, want) |
| + } |
| + |
| + // The handle refuses a binary row and a name that is no worker's. |
| + binary := rt |
| + binary.Runtime = "" |
| + if up, err := b.newRootfsWorkerProc(binary, "jobs", p, "inv1", nil); err == nil || up != nil { |
| + t.Errorf("newRootfsWorkerProc on a binary row = %v, %v", up, err) |
| + } |
| + for _, name := range []string{"", "web", "release", "../jobs", "Jobs", "jobs/x"} { |
| + if up, err := b.newRootfsWorkerProc(rt, name, p, "inv1", nil); err == nil || up != nil { |
| + t.Errorf("newRootfsWorkerProc(%q) = %v, %v", name, up, err) |
| + } |
| + before := len(ctl.callList()) |
| + if wp, err := b.LaunchRootfsWorker(context.Background(), rt, name, g, &fakeProc{}); wp != nil || !errors.Is(err, errRootfsRefused) { |
| + t.Errorf("LaunchRootfsWorker(%q) = %v, %v; want a refusal", name, wp, err) |
| + } |
| + if calls := ctl.callList()[before:]; len(calls) != 0 { |
| + t.Errorf("LaunchRootfsWorker(%q) asked root %q", name, calls) |
| + } |
| + if err := b.RootfsWorkerGone(context.Background(), rt, name); err == nil { |
| + t.Errorf("RootfsWorkerGone(%q) proved a name that is no worker's gone", name) |
| + } |
| + } |
| + if wp, err := b.LaunchRootfsWorker(context.Background(), binary, "jobs", g, &fakeProc{}); wp != nil || !errors.Is(err, errRootfsRefused) { |
| + t.Errorf("LaunchRootfsWorker on a binary row = %v, %v; want a refusal", wp, err) |
| + } |
| +} |
| + |
| +// Not parallel: it shrinks roleEmptyBound. |
| +func TestRootfsWorkerStopAnswers(t *testing.T) { |
| + old := roleEmptyBound |
| + roleEmptyBound = 150 * time.Millisecond |
| + t.Cleanup(func() { roleEmptyBound = old }) |
| + b, ctl, rt, units := newWorkerBackend(t) |
| + unit := instancectl.WorkerUnitName(rt.Host, "jobs") |
| + units.stopEmpties = false |
| + units.set(unit, "inactive", "inv1", false) |
| + stopAsk := "stop-rootfs " + rt.Host + " role=worker gen=0 worker=jobs kill=false" |
| + asks := func() int { |
| + n := 0 |
| + for _, c := range ctl.callList() { |
| + if c == stopAsk { |
| + n++ |
| + } |
| + } |
| + return n |
| + } |
| + |
| + // Root could not prove the stop (its in-flight refusal or an unproven |
| + // stop): unproven here, whatever the cgroup says. |
| + ctl.setStopRootfsErr(fmt.Errorf("%w: instance-control: HTTP 500: a start or removal of it is in flight", instancectl.ErrGenUnproven)) |
| + if err := b.RootfsWorkerGone(context.Background(), rt, "jobs"); err == nil || !errors.Is(err, instancectl.ErrGenUnproven) { |
| + t.Errorf("RootfsWorkerGone over root's unproven stop = %v, want unproven", err) |
| + } |
| + // A plain 502 or a transport failure: unproven. |
| + ctl.setStopRootfsErr(errors.New("instance-control: HTTP 502: stop: timed out")) |
| + if err := b.RootfsWorkerGone(context.Background(), rt, "jobs"); err == nil { |
| + t.Error("RootfsWorkerGone over a 502 proved the worker gone") |
| + } |
| + // Root's nil and an empty cgroup: proven. |
| + ctl.setStopRootfsErr(nil) |
| + if err := b.RootfsWorkerGone(context.Background(), rt, "jobs"); err != nil { |
| + t.Errorf("RootfsWorkerGone with root's nil and an empty group = %v", err) |
| + } |
| + if !slices.Contains(units.readUnits(), unit) { |
| + t.Errorf("the proof read %v, not %s", units.readUnits(), unit) |
| + } |
| + // Root's nil and a populated cgroup: unproven once roleEmptyBound passes. |
| + units.set(unit, "inactive", "inv1", true) |
| + if err := b.RootfsWorkerGone(context.Background(), rt, "jobs"); err == nil { |
| + t.Error("RootfsWorkerGone proved a populated worker group gone") |
| + } |
| + // The caller's cancelled context does not cut the stop or the proof |
| + // short: root is asked on a context of its own (a control that honours |
| + // its context, as the real client does), and the group that empties a |
| + // little later is still waited for. |
| + b.Control = ctxControl{ctl} |
| + n := asks() |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + cancel() |
| + go func() { |
| + time.Sleep(3 * b.ObservePoll) |
| + units.set(unit, "inactive", "inv1", false) |
| + }() |
| + if err := b.RootfsWorkerGone(ctx, rt, "jobs"); err != nil { |
| + t.Errorf("RootfsWorkerGone on a cancelled context = %v, want the stop and the proof to run anyway", err) |
| + } |
| + if asks() != n+1 { |
| + t.Errorf("root was asked %d stops on a cancelled context, want 1", asks()-n) |
| + } |
| + if asks() != 5 { |
| + t.Errorf("%d worker stops asked, want 5:\n%s", asks(), ctl.joined()) |
| + } |
| + for _, c := range ctl.callList() { |
| + if strings.Contains(c, "kill=true") { |
| + t.Errorf("root was asked to kill: %q", c) |
| + } |
| + } |
| + noCallStarts(t, ctl, "stop "+rt.Host, "stopgen") |
| + |
| + // No rootfs half: unproven. |
| + nb, _, nrt, _ := newWorkerBackend(t) |
| + nb.Control = plainControl(nb.Control) |
| + if err := nb.RootfsWorkerGone(context.Background(), nrt, "jobs"); err == nil { |
| + t.Error("RootfsWorkerGone with no rootfs control proved the worker gone") |
| + } |
| +} |
| + |
| +func TestRootfsWorkerExitIsSilentToMembers(t *testing.T) { |
| + t.Parallel() |
| + t.Run("an exit with its record", func(t *testing.T) { |
| + t.Parallel() |
| + b, ctl, rt, units := newWorkerBackend(t) |
| + sink := &rootfsSink{} |
| + b.Logs = sink |
| + web, g := startWorkerWeb(t, b, ctl, rt, units, "") |
| + unit := instancectl.WorkerUnitName(rt.Host, "jobs") |
| + units.set(unit, "active", "inv1", true) |
| + wp, err := b.LaunchRootfsWorker(context.Background(), rt, "jobs", g, web) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + up := wp.(*unitProc) |
| + if _, ok := up.WorkerExit(); ok { |
| + t.Error("an exit record before the worker exited") |
| + } |
| + rec := instancectl.ExitRecord{Invocation: "inv1", Result: "exit-code", Code: "exited", Status: "3"} |
| + raw, err := json.Marshal(rec) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + recPath := filepath.Join(up.runDir, instancectl.WorkerExitRecordName("jobs", "inv1")) |
| + if err := os.WriteFile(recPath, raw, 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + units.set(unit, "inactive", "inv1", false) |
| + waitFor(t, "the worker to exit", wp.Exited) |
| + if msgs := sink.msgs(); len(msgs) != 0 { |
| + t.Errorf("a worker's exit told the member %q", msgs) |
| + } |
| + got, ok := up.WorkerExit() |
| + if !ok || got.Code != "exited" || got.Status != "3" || got.Result != "exit-code" { |
| + t.Errorf("WorkerExit = %+v, %v; want the record (status 3)", got, ok) |
| + } |
| + if _, err := os.Stat(recPath); !os.IsNotExist(err) { |
| + t.Errorf("the consumed exit record: %v, want it removed", err) |
| + } |
| + if _, err := os.Stat(workerLaunchPath(b, rt, "jobs")); err != nil { |
| + t.Errorf("the observer removed the worker's launch file: %v", err) |
| + } |
| + if web.Exited() { |
| + t.Fatal("the worker's exit ended the web generation") |
| + } |
| + // The web generation's exit still tells the member, as today. |
| + units.set(instancectl.RootfsGenUnitName(rt.Host, 7), "inactive", "inv1", false) |
| + waitFor(t, "web to exit", web.Exited) |
| + if msgs := sink.msgs(); !slices.Equal(msgs, []string{exitLine(instancectl.ExitRecord{}, false)}) { |
| + t.Errorf("web's exit told the member %q, want today's line", msgs) |
| + } |
| + }) |
| + t.Run("restarted outside the activator", func(t *testing.T) { |
| + t.Parallel() |
| + b, ctl, rt, units := newWorkerBackend(t) |
| + sink := &rootfsSink{} |
| + b.Logs = sink |
| + units.stopEmpties = false |
| + unit := instancectl.WorkerUnitName(rt.Host, "jobs") |
| + units.set(unit, "active", "inv1", true) |
| + wp, err := b.LaunchRootfsWorker(context.Background(), rt, "jobs", stagedWorkerGen(t, b, rt), &fakeProc{}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + // A foreign invocation, outside the activator: stopped through the |
| + // worker unit, then proven by its empty group. |
| + units.set(unit, "active", "inv-foreign", true) |
| + waitFor(t, "the foreign worker invocation's stop", func() bool { |
| + return slices.Contains(ctl.callList(), "stop-rootfs "+rt.Host+" role=worker gen=0 worker=jobs kill=false") |
| + }) |
| + if wp.Exited() { |
| + t.Fatal("exited while the foreign invocation's group is populated") |
| + } |
| + units.set(unit, "inactive", "inv-foreign", false) |
| + waitFor(t, "the worker to exit", wp.Exited) |
| + if msgs := sink.msgs(); len(msgs) != 0 { |
| + t.Errorf("a worker's foreign restart told the member %q", msgs) |
| + } |
| + if _, ok := wp.(*unitProc).WorkerExit(); ok { |
| + t.Error("an exit record for an invocation that was not ours") |
| + } |
| + noCallStarts(t, ctl, "stop "+rt.Host, "stopgen") |
| + }) |
| + t.Run("replaced after stop", func(t *testing.T) { |
| + t.Parallel() |
| + b, ctl, rt, units := newWorkerBackend(t) |
| + sink := &rootfsSink{} |
| + b.Logs = sink |
| + unit := instancectl.WorkerUnitName(rt.Host, "jobs") |
| + units.set(unit, "active", "inv1", true) |
| + wp, err := b.LaunchRootfsWorker(context.Background(), rt, "jobs", stagedWorkerGen(t, b, rt), &fakeProc{}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + // Our stop is followed by a fresh invocation of the unit. |
| + ctl.stopHook = func(string, instancectl.Role) { units.set(unit, "activating", "inv2", true) } |
| + stopWorker(t, wp) |
| + if !wp.Exited() { |
| + t.Fatal("not exited after its replacement") |
| + } |
| + if msgs := sink.msgs(); len(msgs) != 0 { |
| + t.Errorf("a worker's replacement after stop told the member %q", msgs) |
| + } |
| + ctl.mustHaveCallPrefix(t, "stop-rootfs "+rt.Host+" role=worker gen=0 worker=jobs kill=false") |
| + }) |
| +} |
| + |
| +func TestRootfsWorkerRefusalsStartNothing(t *testing.T) { |
| + t.Parallel() |
| + for _, tc := range []struct { |
| + name string |
| + setup func(b *ExecBackend, ctl *fakeControl, g *Gen) context.Context |
| + // asked: root was asked to start (and refused before it started). |
| + asked bool |
| + isRefusal func(error) bool |
| + }{ |
| + {"a rootfs gate", func(b *ExecBackend, _ *fakeControl, _ *Gen) context.Context { |
| + b.RootfsOK = func(context.Context) error { return errors.New("root-image probe failed") } |
| + return context.Background() |
| + }, false, func(err error) bool { return errors.Is(err, errRootfsRefused) }}, |
| + {"no rootfs control", func(b *ExecBackend, _ *fakeControl, _ *Gen) context.Context { |
| + b.Control = plainControl(b.Control) |
| + return context.Background() |
| + }, false, func(err error) bool { return errors.Is(err, errRootfsRefused) }}, |
| + {"a partial identity", func(_ *ExecBackend, _ *fakeControl, g *Gen) context.Context { |
| + g.Digest = "" |
| + return context.Background() |
| + }, false, func(err error) bool { return errors.Is(err, errRootfsRefused) }}, |
| + {"a binary staged under the row (RFS-2-C07)", func(b *ExecBackend, _ *fakeControl, g *Gen) context.Context { |
| + g.Build, g.Digest = "v3", stageRootfsImage(t, b, "v3", "binary") |
| + g.StagedPath = release.VersionPath(b.OptDir, rootfsTestAcct, "v3", rootfsTestApp) |
| + return context.Background() |
| + }, false, func(err error) bool { |
| + return errors.Is(err, errRootfsRefused) && strings.Contains(err.Error(), rootfsBinaryStagedText) |
| + }}, |
| + {"the exec gate on ctx", func(*ExecBackend, *fakeControl, *Gen) context.Context { |
| + return withExecGate(context.Background(), func() error { return errors.New("the lease moved") }) |
| + }, false, func(err error) bool { var r launchRefused; return errors.As(err, &r) }}, |
| + {"root's 403 (ErrStagedImage)", func(_ *ExecBackend, ctl *fakeControl, _ *Gen) context.Context { |
| + ctl.startErr = fmt.Errorf("%w: instance-control: HTTP 403: digest", instancectl.ErrStagedImage) |
| + return context.Background() |
| + }, true, func(err error) bool { |
| + return errors.Is(err, errRootfsRefused) && errors.Is(err, instancectl.ErrStagedImage) |
| + }}, |
| + {"root's pre-start refusal (ErrStartRefused)", func(_ *ExecBackend, ctl *fakeControl, _ *Gen) context.Context { |
| + ctl.startErr = fmt.Errorf("%w: instance-control: HTTP 503: not ready", instancectl.ErrStartRefused) |
| + return context.Background() |
| + }, true, func(err error) bool { |
| + return errors.Is(err, errRootfsRefused) && errors.Is(err, instancectl.ErrStartRefused) |
| + }}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + t.Parallel() |
| + b, ctl, rt, units := newWorkerBackend(t) |
| + units.set(instancectl.WorkerUnitName(rt.Host, "jobs"), "active", "inv1", true) |
| + g := stagedWorkerGen(t, b, rt) |
| + ctx := tc.setup(b, ctl, &g) |
| + p, err := b.LaunchRootfsWorker(ctx, rt, "jobs", g, &fakeProc{}) |
| + if p != nil || err == nil || !tc.isRefusal(err) { |
| + t.Fatalf("LaunchRootfsWorker = %v, %v; want the refusal", p, err) |
| + } |
| + if startMayHaveRun(p, err) { |
| + t.Errorf("a refusal reads as a start that may have run: %v", err) |
| + } |
| + asked := slices.ContainsFunc(ctl.callList(), func(c string) bool { return strings.HasPrefix(c, "start-rootfs-worker ") }) |
| + if asked != tc.asked { |
| + t.Errorf("root asked to start = %v, want %v:\n%s", asked, tc.asked, ctl.joined()) |
| + } |
| + noCallStarts(t, ctl, "stop-rootfs", "stop "+rt.Host) |
| + if _, err := os.Stat(workerLaunchPath(b, rt, "jobs")); !os.IsNotExist(err) { |
| + t.Errorf("the worker's launch file after a refusal: %v", err) |
| + } |
| + if socketBound(b.workerLogSocket(rt.Host, "jobs")) { |
| + t.Error("the worker's log listener is still bound after a refusal") |
| + } |
| + }) |
| + } |
| + |
| + // Any other failure may have started the unit: a handle comes back |
| + // with the error, the files stay, and the caller's proof decides. |
| + t.Run("a 502 is no refusal", func(t *testing.T) { |
| + t.Parallel() |
| + b, ctl, rt, units := newWorkerBackend(t) |
| + unit := instancectl.WorkerUnitName(rt.Host, "jobs") |
| + units.set(unit, "active", "inv1", true) |
| + ctl.startErr = errors.New("instance-control: HTTP 502: start: failed") |
| + p, err := b.LaunchRootfsWorker(context.Background(), rt, "jobs", stagedWorkerGen(t, b, rt), &fakeProc{}) |
| + if err == nil || p == nil || errors.Is(err, errRootfsRefused) || !startMayHaveRun(p, err) { |
| + t.Fatalf("LaunchRootfsWorker over a 502 = %v, %v; want a handle with an uncertain start", p, err) |
| + } |
| + if up := p.(*unitProc); up.unit != unit { |
| + t.Errorf("the handle watches %q, want %q", up.unit, unit) |
| + } |
| + if _, err := os.Stat(workerLaunchPath(b, rt, "jobs")); err != nil { |
| + t.Errorf("the launch file after a start that may have run: %v, want it kept", err) |
| + } |
| + if !socketBound(b.workerLogSocket(rt.Host, "jobs")) { |
| + t.Error("the log listener was closed under a unit that may be writing to it") |
| + } |
| + if err := b.RootfsWorkerGone(context.Background(), rt, "jobs"); err != nil { |
| + t.Fatalf("RootfsWorkerGone: %v", err) |
| + } |
| + stopWorker(t, p) |
| + }) |
| +} |
| + |
| +func TestWorkersThroughTheProductionBackend(t *testing.T) { |
| + t.Parallel() |
| + eb, ctl, rt, units := newWorkerBackend(t) |
| + var b Backend = productionBackend(t, eb) |
| + wb, ok := b.(RootfsWorkerBackend) |
| + if !ok { |
| + t.Fatal("SplitBackend is not a RootfsWorkerBackend") |
| + } |
| + web, g := startWorkerWeb(t, eb, ctl, rt, units, "SHOP_MODE=live\n") |
| + units.set(instancectl.WorkerUnitName(rt.Host, "jobs"), "active", "inv1", true) |
| + wp, err := wb.LaunchRootfsWorker(context.Background(), rt, "jobs", g, web) |
| + if err != nil { |
| + t.Fatalf("LaunchRootfsWorker: %v", err) |
| + } |
| + ctl.mustHaveCallPrefix(t, "start-rootfs-worker "+rt.Host+" jobs ") |
| + if err := wb.RootfsWorkerGone(context.Background(), rt, "jobs"); err != nil { |
| + t.Fatalf("RootfsWorkerGone: %v", err) |
| + } |
| + ctl.mustHaveCallPrefix(t, "stop-rootfs "+rt.Host+" role=worker gen=0 worker=jobs kill=false") |
| + waitFor(t, "the worker's handle to see it gone", wp.Exited) |
| + stopWorker(t, wp) |
| + // The Service's removal, holding the proof: this worker's files only. |
| + p := eb.pathsFor(rt) |
| + keep := []string{instancectl.WorkerExitRecordName("mail", "x"), instancectl.GenExitRecordName(7, "x")} |
| + for _, name := range append([]string{instancectl.WorkerExitRecordName("jobs", "x")}, keep...) { |
| + if err := os.WriteFile(filepath.Join(p.runDir, name), []byte("{}"), 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + eb.removeRootfsWorkerFiles(rt, "jobs") |
| + if _, err := os.Stat(workerLaunchPath(eb, rt, "jobs")); !os.IsNotExist(err) { |
| + t.Errorf("the worker's launch file after its removal: %v", err) |
| + } |
| + if _, err := os.Stat(filepath.Join(p.runDir, instancectl.WorkerExitRecordName("jobs", "x"))); !os.IsNotExist(err) { |
| + t.Errorf("the worker's exit record after its removal: %v", err) |
| + } |
| + for _, name := range keep { |
| + if _, err := os.Stat(filepath.Join(p.runDir, name)); err != nil { |
| + t.Errorf("%s went with the worker jobs: %v", name, err) |
| + } |
| + } |
| + if _, err := os.Stat(filepath.Join(p.dataDir, instancectl.GenLaunchFileName(7))); err != nil { |
| + t.Errorf("the web generation's launch file went with the worker: %v", err) |
| + } |
| + |
| + // A unit-backed row: both refused, root asked nothing. |
| + unit := rt |
| + unit.Backing = registry.BackingUnit |
| + before := len(ctl.callList()) |
| + if p, err := wb.LaunchRootfsWorker(context.Background(), unit, "jobs", g, web); p != nil || !errors.Is(err, errNoRootfsControl) || !errors.Is(err, errRootfsRefused) { |
| + t.Errorf("LaunchRootfsWorker on a unit row = %v, %v; want a marked errNoRootfsControl", p, err) |
| + } |
| + if err := wb.RootfsWorkerGone(context.Background(), unit, "jobs"); !errors.Is(err, errNoRootfsControl) || !errors.Is(err, errRootfsRefused) { |
| + t.Errorf("RootfsWorkerGone on a unit row = %v; want a marked errNoRootfsControl", err) |
| + } |
| + if calls := ctl.callList()[before:]; len(calls) != 0 { |
| + t.Errorf("root was asked %q for a unit-backed row", calls) |
| + } |
| +} |
diff --git a/internal/activator/unitproc.go b/internal/activator/unitproc.go| index 612fe3357..a1ba655f5 100644 |
| --- a/internal/activator/unitproc.go |
| +++ b/internal/activator/unitproc.go |
| @@ -16,6 +16,7 @@ import ( |
| "github.com/carlosframework/platform/internal/instancefs" |
| "github.com/carlosframework/platform/internal/instancekey" |
| "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| ) |
| // ErrStillRunning is Stop's answer when ctx expired before termination was |
| @@ -73,6 +74,30 @@ type unitProc struct { |
| // from, decided by the read that composed launchEnv (instance-key |
| // ruling 29). Written with launchEnv, never again. |
| launchKeyLayer instancekey.Layer |
| + // worker is the rootfs worker this handle watches (rootfs apps Plan 3, |
| + // W1), "" for every other handle. A worker's unit is its own |
| + // (rootfsUnitFor), its stop names it, and observe tells the member |
| + // nothing of its end: the supervisor does (W1b). |
| + worker string |
| + // workerExit and workerExitOK are the exit record observe read for a |
| + // worker's own invocation, written once before done closes and read |
| + // through WorkerExit. |
| + workerExit instancectl.ExitRecord |
| + workerExitOK bool |
| +} |
| + |
| +// WorkerExit is the exit record observe read when this worker's own |
| +// invocation ended: ok is false while the handle has not ended, for a |
| +// worker that left no record or whose end was not its own invocation's |
| +// (a foreign restart, a replacement after stop), and for every handle |
| +// that is not a worker's. |
| +func (p *unitProc) WorkerExit() (instancectl.ExitRecord, bool) { |
| + select { |
| + case <-p.done: |
| + return p.workerExit, p.workerExitOK |
| + default: |
| + return instancectl.ExitRecord{}, false |
| + } |
| } |
| // launchEnvProc is a generation handle that kept the file environment its |
| @@ -158,6 +183,39 @@ func unitNameFor(rt registry.Route, role instancectl.Role, gen uint64) string { |
| return instancectl.RootfsUnitName(role, rt.Host) |
| } |
| +// rootfsUnitFor is unitNameFor with a worker's name: the named worker's |
| +// unit (WorkerUnitName) for RoleWorker on a rootfs row, and unitNameFor's |
| +// answer otherwise, so a worker with no name still has no unit. A worker |
| +// is never a generation, never on a binary row and always a valid worker |
| +// name; any of those answers "". |
| +func rootfsUnitFor(rt registry.Route, role instancectl.Role, gen uint64, worker string) string { |
| + if role != instancectl.RoleWorker || worker == "" { |
| + return unitNameFor(rt, role, gen) |
| + } |
| + if rt.Runtime != registry.RuntimeRootfsV1 || gen != 0 || !release.ValidWorkerName(worker) { |
| + return "" |
| + } |
| + return instancectl.WorkerUnitName(rt.Host, worker) |
| +} |
| + |
| +// newRootfsWorkerProc starts observing the named rootfs worker's unit, as |
| +// newUnitProcFor does a role's. The worker holds no control listener; |
| +// logs is its own log listener. A binary row or a name that is no |
| +// worker's is refused before anything watches. |
| +func (b *ExecBackend) newRootfsWorkerProc(rt registry.Route, name string, p instancePaths, inv string, logs *logListener) (*unitProc, error) { |
| + if !rt.Rootfs() { |
| + return nil, fmt.Errorf("%s: a worker unit is a rootfs instance's alone", rt.Host) |
| + } |
| + unit := rootfsUnitFor(rt, instancectl.RoleWorker, 0, name) |
| + if unit == "" { |
| + return nil, fmt.Errorf("%s: %q is not a worker name", rt.Host, name) |
| + } |
| + up := &unitProc{b: b, rt: rt, role: instancectl.RoleWorker, worker: name, unit: unit, slice: instancectl.SliceName(rt.Host), |
| + invocation: inv, runDir: p.runDir, dataDir: p.dataDir, logs: logs, done: make(chan struct{})} |
| + go b.observe(up) |
| + return up, nil |
| +} |
| + |
| // stopRole stops one role's unit: a rootfs row's through RootfsControl, a |
| // binary row's original template through Control and its generation |
| // through GenControl. A generation stop never touches a sibling |
| @@ -223,7 +281,16 @@ func (p *unitProc) Stop(ctx context.Context) error { |
| // stopUnit asks the control service to stop this proc's unit. For a |
| // generation, a stop that succeeded also removed the unit's files there. |
| +// A worker's stop names the worker and never kills: root refuses kill for |
| +// anything but a generation. |
| func (p *unitProc) stopUnit(ctx context.Context) error { |
| + if p.worker != "" { |
| + rc, err := p.b.rootfsControl() |
| + if err != nil { |
| + return fmt.Errorf("%s: %w", p.rt.Host, err) |
| + } |
| + return rc.StopRootfs(ctx, p.rt.Host, instancectl.RoleWorker, 0, p.worker, false) |
| + } |
| err := p.b.stopRole(ctx, p.rt, p.role, p.gen) |
| if err == nil && p.gen != 0 { |
| p.genFilesGone.Store(true) |
| @@ -325,7 +392,9 @@ func (b *ExecBackend) observe(p *unitProc) { |
| // disprove, because systemd's own state machine already disproved |
| // it by allowing a new invocation to begin. |
| if p.stopRequested.Load() && err == nil && !terminal && (foreign || inv == "") { |
| - emitEvent(b.Logs, p.rt, "warn", "instance exited (status unknown: replaced after stop)") |
| + if p.worker == "" { |
| + emitEvent(b.Logs, p.rt, "warn", "instance exited (status unknown: replaced after stop)") |
| + } |
| p.exited.Store(true) |
| close(p.done) |
| return |
| @@ -380,7 +449,13 @@ func (b *ExecBackend) observe(p *unitProc) { |
| if !exists || !populated { |
| if terminal { |
| rec, ok := p.readRecord() |
| - emitEvent(b.Logs, p.rt, exitLevel(rec, ok), exitLine(rec, ok)) |
| + if p.worker != "" { |
| + // A worker's end is the supervisor's to tell (W1b): |
| + // the record is kept for it, never worded here. |
| + p.workerExit, p.workerExitOK = rec, ok |
| + } else { |
| + emitEvent(b.Logs, p.rt, exitLevel(rec, ok), exitLine(rec, ok)) |
| + } |
| // The record is single-use (design §6.5): consumed |
| // exactly once into the member-facing line above, then |
| // cleared so it can never be misread as evidence for a |
| @@ -388,7 +463,7 @@ func (b *ExecBackend) observe(p *unitProc) { |
| // clears records left over from EARLIER invocations; |
| // this one is this invocation's own to remove). |
| p.removeRecord() |
| - } else { |
| + } else if p.worker == "" { |
| emitEvent(b.Logs, p.rt, "warn", "instance exited (status unknown: restarted outside the activator)") |
| } |
| p.finaliseGen() |
| @@ -453,6 +528,9 @@ func exitLevel(rec instancectl.ExitRecord, ok bool) string { |
| } |
| func (p *unitProc) recordName() string { |
| + if p.worker != "" { |
| + return instancectl.WorkerExitRecordName(p.worker, p.invocation) |
| + } |
| if p.gen == 0 { |
| return instancectl.ExitRecordName(p.role, p.invocation) |
| } |
| @@ -483,7 +561,9 @@ func (p *unitProc) removeRecord() { |
| // removeLaunch deletes a generation's launch file once the generation is |
| // proven gone. Generation numbers are never reused, so nothing else would. |
| // The original templates' launch file is rewritten by every start and is |
| -// left alone. os.Remove never follows the final component. |
| +// left alone, and so is a worker's: the Service removes a worker's files |
| +// only once RootfsWorkerGone proved it gone (removeRootfsWorkerFiles). |
| +// os.Remove never follows the final component. |
| func (p *unitProc) removeLaunch() { |
| if p.gen != 0 && p.dataDir != "" { |
| _ = os.Remove(filepath.Join(p.dataDir, instancectl.GenLaunchFileName(p.gen))) |
diff --git a/plan3_groups_test.go b/plan3_groups_test.go| index 2e3f85460..b6d44c159 100644 |
| --- a/plan3_groups_test.go |
| +++ b/plan3_groups_test.go |
| @@ -50,7 +50,7 @@ var ( |
| // plan3GroupsStarted and plan3GroupsLanded: "R" and "W" (and "A" in |
| // landed), each added by the task the file comment names. |
| var ( |
| - plan3GroupsStarted = []string{"R"} |
| + plan3GroupsStarted = []string{"R", "W"} |
| plan3GroupsLanded = []string{"A", "R"} |
| ) |