instancectl: POST and GET /size, slice then serving generation, read back
Root's live size verbs (#329, spec §5.4), both legacy verbs behind claimAwareLegacy (503 with host claims on: no live change). POST /size validates the host, the size name, a size's memory and an active generation, refuses a memory shrink while the slice is populated, writes the slice (sliceSize, which sliceTier now wraps with identical output), then the generation unit's memory, and reads both back. parseSizeShow maps CPUQuotaPerSecUSec back through main's cpuQuotaShown. Client.Size and Client.ReadSize wrap 400/409/503 in ErrSizeRefused. startGen and removeGenFiles remove the generation unit's own <ControlDropInDir>/<unit>.d (default RuntimeControlDir), rebuilt from the parsed unit name, never a slice's, never through a symlink, so a reused generation number starts instead of failing "drop-in did not apply".
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
10 files changed,
+892
−23
internal/instancectl/claim_test.go+1 −1internal/instancectl/client.go+38 −0internal/instancectl/client_test.go+54 −0internal/instancectl/gen.go+7 −0internal/instancectl/names.go+7 −0internal/instancectl/names_test.go+6 −0internal/instancectl/server.go+38 −22internal/instancectl/server_gen_test.go+138 −0internal/instancectl/size.go+280 −0internal/instancectl/size_test.go+323 −0
diff --git a/internal/instancectl/claim_test.go b/internal/instancectl/claim_test.go| index be54b9562..ad3632330 100644 |
| --- a/internal/instancectl/claim_test.go |
| +++ b/internal/instancectl/claim_test.go |
| @@ -11,7 +11,7 @@ import ( |
| func TestClaimRootRefusesLegacyProcessMutations(t *testing.T) { |
| called := false |
| server := &Server{ClaimStop: http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}), Systemctl: func(context.Context, ...string) (string, error) { called = true; return "", nil }} |
| - for _, verb := range []string{"start", "seed", "stop", "reset", "sweep", "cmd"} { |
| + for _, verb := range []string{"start", "seed", "stop", "reset", "sweep", "cmd", "size"} { |
| response := httptest.NewRecorder() |
| server.Handler().ServeHTTP(response, httptest.NewRequest(http.MethodPost, "/"+verb+"?host=app.example&role=run&memory_max=536870912", strings.NewReader(""))) |
| if response.Code != http.StatusServiceUnavailable { |
diff --git a/internal/instancectl/client.go b/internal/instancectl/client.go| index 69d92e313..6dd5c9fb9 100644 |
| --- a/internal/instancectl/client.go |
| +++ b/internal/instancectl/client.go |
| @@ -320,6 +320,44 @@ func (c *Client) Parent(ctx context.Context, host string, memoryMax int64) error |
| return err |
| } |
| +// Size applies a size to host's slice and, with gen, to that serving |
| +// generation's unit, and returns root's read-back (#329, spec §5.4). |
| +// size names the CPU and IO shares; memoryMax is a size's memory, which |
| +// may be the larger one held while the slice is populated. A refusal |
| +// before any write (400, 409, or 503 with host claims on, where there is |
| +// no live change) wraps ErrSizeRefused; any other failure may have |
| +// written the slice. |
| +func (c *Client) Size(ctx context.Context, host string, gen uint64, size string, memoryMax int64) (SizeReadBack, error) { |
| + q := url.Values{"host": {host}, "size": {size}, "memory_max": {strconv.FormatInt(memoryMax, 10)}} |
| + if gen != 0 { |
| + q.Set("gen", strconv.FormatUint(gen, 10)) |
| + } |
| + return c.size(ctx, http.MethodPost, q) |
| +} |
| + |
| +// ReadSize reads what host's slice and, with gen, that generation's unit |
| +// hold now. Refusals wrap ErrSizeRefused, as Size's do. |
| +func (c *Client) ReadSize(ctx context.Context, host string, gen uint64) (SizeReadBack, error) { |
| + q := url.Values{"host": {host}} |
| + if gen != 0 { |
| + q.Set("gen", strconv.FormatUint(gen, 10)) |
| + } |
| + return c.size(ctx, http.MethodGet, q) |
| +} |
| + |
| +func (c *Client) size(ctx context.Context, method string, q url.Values) (SizeReadBack, error) { |
| + var out SizeReadBack |
| + status, _, err := c.do(ctx, DeadlineControl, method, "/size", q, &out) |
| + if err != nil { |
| + switch status { |
| + case http.StatusBadRequest, http.StatusConflict, http.StatusServiceUnavailable: |
| + return SizeReadBack{}, fmt.Errorf("%w: %w", ErrSizeRefused, err) |
| + } |
| + return SizeReadBack{}, err |
| + } |
| + return out, nil |
| +} |
| + |
| // Sweep stops every instance unit on the box (design §6.7). A 502 carries |
| // the units that were stopped and the ones that would not; both are |
| // returned with the error. |
diff --git a/internal/instancectl/client_test.go b/internal/instancectl/client_test.go| index 4837bd699..4fdac118c 100644 |
| --- a/internal/instancectl/client_test.go |
| +++ b/internal/instancectl/client_test.go |
| @@ -4,6 +4,7 @@ import ( |
| "context" |
| "encoding/json" |
| "errors" |
| + "net/http" |
| "os" |
| "path/filepath" |
| "strings" |
| @@ -196,3 +197,56 @@ func TestClientEgressVerbs(t *testing.T) { |
| t.Fatalf("EgressStatus after a failed write = %+v, %v", st, err) |
| } |
| } |
| + |
| +// Size and ReadSize: a refusal before any write (400 shape, 409 an |
| +// inactive generation or a held shrink, 503 with host claims on) wraps |
| +// ErrSizeRefused; a 502 (systemd failed, the slice may be written) does |
| +// not. |
| +func TestClientSizeMapsRefusalsToErrSizeRefused(t *testing.T) { |
| + ctx := context.Background() |
| + ok := sizeCtl("536870912", "MemoryMax=1073741824\nCPUQuotaPerSecUSec=2s\nCPUWeight=100\nIOWeight=100\n", "MemoryMax=1073741824\n") |
| + _, c := newClient(t, ok) |
| + rb, err := c.Size(ctx, sizeHost, 3, "large", 1073741824) |
| + if want := (SizeReadBack{SliceMemoryMax: 1073741824, CPUQuotaPercent: 200, CPUWeight: 100, IOWeight: 100, UnitMemoryMax: 1073741824}); err != nil || rb != want { |
| + t.Fatalf("Size = %+v, %v; want %+v", rb, err, want) |
| + } |
| + if !strings.Contains(ok.joined(), "set-property --runtime "+sizeUnit) { |
| + t.Errorf("Size did not carry the generation:\n%s", ok.joined()) |
| + } |
| + if rb, err := c.ReadSize(ctx, sizeHost, 3); err != nil || rb.UnitMemoryMax != 1073741824 { |
| + t.Fatalf("ReadSize = %+v, %v", rb, err) |
| + } |
| + |
| + inactive := sizeCtl("536870912", "", "") |
| + inactive.answers["show -p ActiveState --value "+sizeUnit] = "inactive\n" |
| + _, ci := newClient(t, inactive) |
| + _, claimed := newClient(t, sizeCtl("536870912", "", ""), func(s *Server) { |
| + s.ClaimStop = http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}) |
| + }) |
| + failing := sizeCtl("536870912", "", "") |
| + failing.fail = map[string]error{"set-property": errSizeWrite, "show -p MemoryMax -p": errSizeWrite} |
| + _, cf := newClient(t, failing) |
| + |
| + for name, tc := range map[string]struct { |
| + err func() error |
| + refused bool |
| + }{ |
| + "Size 400": {func() error { _, err := c.Size(ctx, sizeHost, 3, "huge", 1073741824); return err }, true}, |
| + "ReadSize 400": {func() error { _, err := c.ReadSize(ctx, "../etc", 0); return err }, true}, |
| + "Size 409": {func() error { _, err := ci.Size(ctx, sizeHost, 3, "large", 1073741824); return err }, true}, |
| + "ReadSize 409": {func() error { _, err := ci.ReadSize(ctx, sizeHost, 3); return err }, true}, |
| + "Size 503": {func() error { _, err := claimed.Size(ctx, sizeHost, 3, "large", 1073741824); return err }, true}, |
| + "ReadSize 503": {func() error { _, err := claimed.ReadSize(ctx, sizeHost, 3); return err }, true}, |
| + "Size 502": {func() error { _, err := cf.Size(ctx, sizeHost, 0, "large", 1073741824); return err }, false}, |
| + "ReadSize 502": {func() error { _, err := cf.ReadSize(ctx, sizeHost, 0); return err }, false}, |
| + } { |
| + err := tc.err() |
| + if err == nil { |
| + t.Errorf("%s: no error", name) |
| + continue |
| + } |
| + if errors.Is(err, ErrSizeRefused) != tc.refused { |
| + t.Errorf("%s: %v; errors.Is(ErrSizeRefused) = %v, want %v", name, err, !tc.refused, tc.refused) |
| + } |
| + } |
| +} |
diff --git a/internal/instancectl/gen.go b/internal/instancectl/gen.go| index be055a181..afdb696e2 100644 |
| --- a/internal/instancectl/gen.go |
| +++ b/internal/instancectl/gen.go |
| @@ -90,6 +90,7 @@ func (s *Server) removeGenFiles(unit string) error { |
| if s.DropInDir != "" { |
| errs = append(errs, os.RemoveAll(filepath.Join(s.DropInDir, unit+".d"))) |
| } |
| + errs = append(errs, s.removeGenControlDropIn(unit)) |
| iid, ok := Unescape(esc) |
| if !ok || iid == "" || strings.ContainsAny(iid, "/\x00") || iid == "." || iid == ".." { |
| return errors.Join(errs...) |
| @@ -197,6 +198,12 @@ func (s *Server) startGen(w http.ResponseWriter, r *http.Request, req request) { |
| http.Error(w, msg, status) |
| } |
| laidOut := time.Now() |
| + // A reused generation number must not start at a live /size's old |
| + // runtime memory, which outranks the drop-in (#329). |
| + if err := s.removeGenControlDropIn(unit); err != nil { |
| + fail(http.StatusBadGateway, "control drop-in: "+err.Error()) |
| + return |
| + } |
| if err := s.writeGenDropIn(req.host, req.gen, req.tier); err != nil { |
| fail(http.StatusBadGateway, "drop-in: "+err.Error()) |
| return |
diff --git a/internal/instancectl/names.go b/internal/instancectl/names.go| index 2dd8a4f1c..284b0adf2 100644 |
| --- a/internal/instancectl/names.go |
| +++ b/internal/instancectl/names.go |
| @@ -14,6 +14,7 @@ package instancectl |
| import ( |
| "fmt" |
| + "path" |
| "path/filepath" |
| "strconv" |
| "strings" |
| @@ -110,6 +111,12 @@ func SliceName(host string) string { |
| return "carlos-instances-" + Escape(provision.InstanceID(host)) + ".slice" |
| } |
| +// SliceControlGroup is host's slice as a path under the cgroup root |
| +// (carlos.slice/carlos-instances.slice/<slice>), for a cgroupfs read. |
| +func SliceControlGroup(host string) string { |
| + return path.Join(parentSlices, SliceName(host)) |
| +} |
| + |
| // UnitPrefixGen is the generation template (zero-downtime deploys spec |
| // §7.6): one instance per spawn of a host's run role. The four templates |
| // above stay for every box and binary still running them. |
diff --git a/internal/instancectl/names_test.go b/internal/instancectl/names_test.go| index 50b33f0f8..92c96ec96 100644 |
| --- a/internal/instancectl/names_test.go |
| +++ b/internal/instancectl/names_test.go |
| @@ -95,3 +95,9 @@ func TestFileNames(t *testing.T) { |
| t.Errorf("ProbeDirName %q is a valid host; it must never collide with one", ProbeDirName) |
| } |
| } |
| + |
| +func TestSliceControlGroupIsTheSlicesCgroupPath(t *testing.T) { |
| + if got, want := SliceControlGroup("shop-a.example.com"), `carlos.slice/carlos-instances.slice/carlos-instances-shop\x2da.example.com.slice`; got != want { |
| + t.Errorf("SliceControlGroup = %q, want %q", got, want) |
| + } |
| +} |
diff --git a/internal/instancectl/server.go b/internal/instancectl/server.go| index c21ec28bf..61ad91ca0 100644 |
| --- a/internal/instancectl/server.go |
| +++ b/internal/instancectl/server.go |
| @@ -75,6 +75,11 @@ type Server struct { |
| // (/run/systemd/system). Empty refuses every generation start: the |
| // template alone runs nothing (zero-downtime plan 2 D1). |
| DropInDir string |
| + // ControlDropInDir is systemd's directory for `set-property |
| + // --runtime` values (RuntimeControlDir). A generation start and its |
| + // file cleanup remove the generation unit's own <unit>.d there, which |
| + // a live /size leaves behind (#329). Empty skips that (tests). |
| + ControlDropInDir string |
| // ResolvConf is the box's resolv.conf and ResolvedConf resolved's |
| // upstream list; whichever an instance sees (resolverFile) has its |
| // nameservers re-opened through the egress fence before every probe |
| @@ -191,25 +196,26 @@ func runWithClaim(args []string, claim, heldRelease http.Handler, hostApp func(s |
| out, err := exec.CommandContext(ctx, args[0], args[1:]...).CombinedOutput() |
| return string(out), err |
| }, |
| - PeerOK: productionPeerOK(), |
| - CgroupRoot: "/sys/fs/cgroup", |
| - ProbeOut: filepath.Join(controlsock.Dir, "probe.out"), |
| - FixtureOK: ProbeFixturesOK, |
| - ProbeEvery: 5 * time.Minute, |
| - Logf: log.Printf, |
| - ExeRoot: filepath.Join(controlsock.Dir, "exe"), |
| - OptDir: "/opt/carlos", |
| - HostApp: hostApp, |
| - DropInDir: "/run/systemd/system", |
| - ResolvConf: "/etc/resolv.conf", |
| - ResolvedConf: ResolvedConf, |
| - LocalAddrs: func() ([]netip.Prefix, error) { return localPrefixes(fibTriePath, ifInet6Path) }, |
| - DataRoot: "/data/instances", |
| - Statfs: statfsBytes, |
| - DiskEvery: 30 * time.Second, |
| - Build: version.Build, |
| - ExeCurrent: installedBinaryCurrent, |
| - Egress: egress, |
| + PeerOK: productionPeerOK(), |
| + CgroupRoot: "/sys/fs/cgroup", |
| + ProbeOut: filepath.Join(controlsock.Dir, "probe.out"), |
| + FixtureOK: ProbeFixturesOK, |
| + ProbeEvery: 5 * time.Minute, |
| + Logf: log.Printf, |
| + ExeRoot: filepath.Join(controlsock.Dir, "exe"), |
| + OptDir: "/opt/carlos", |
| + HostApp: hostApp, |
| + DropInDir: "/run/systemd/system", |
| + ControlDropInDir: RuntimeControlDir, |
| + ResolvConf: "/etc/resolv.conf", |
| + ResolvedConf: ResolvedConf, |
| + LocalAddrs: func() ([]netip.Prefix, error) { return localPrefixes(fibTriePath, ifInet6Path) }, |
| + DataRoot: "/data/instances", |
| + Statfs: statfsBytes, |
| + DiskEvery: 30 * time.Second, |
| + Build: version.Build, |
| + ExeCurrent: installedBinaryCurrent, |
| + Egress: egress, |
| } |
| ln, activated, err := activatedListener() |
| if err != nil { |
| @@ -340,6 +346,10 @@ func (s *Server) Handler() http.Handler { |
| mux.HandleFunc("POST /parent", s.claimAwareLegacy(s.handleParent)) |
| mux.HandleFunc("POST /cmd", s.claimAwareLegacy(s.handleCmd)) |
| mux.HandleFunc("GET /cmd/{host}", s.claimAwareLegacy(s.handleCmdStatus)) |
| + // A live size is a legacy verb: with host claims on there is no live |
| + // change, and a new size waits for the next start (#329, spec §5.4). |
| + mux.HandleFunc("POST /size", s.claimAwareLegacy(s.handleSize)) |
| + mux.HandleFunc("GET /size", s.claimAwareLegacy(s.handleSizeReadBack)) |
| mux.HandleFunc("GET /ready", s.handleReady) |
| // Egress is root's own state, not a legacy unit verb: served with |
| // host claims on too, where the asserter writes no allow (ruling 9). |
| @@ -481,9 +491,15 @@ func (s *Server) setTier(ctx context.Context, host string, tier cgroup.Limit) er |
| // sliceTier is setTier's one systemctl call, shared with the claim launch. |
| func sliceTier(ctx context.Context, systemctl func(context.Context, ...string) (string, error), host string, tier cgroup.Limit) error { |
| - max := strconv.FormatInt(tier.MemoryMax, 10) |
| - high := strconv.FormatInt(cgroup.HighOf(tier.MemoryMax), 10) |
| - sh := cgroup.SharesOf(tier) |
| + return sliceSize(ctx, systemctl, host, tier, cgroup.SharesOf(tier)) |
| +} |
| + |
| +// sliceSize writes memory and shares onto the host slice in one call. They |
| +// are separate because a live /size may hold the memory in force while it |
| +// applies a smaller size's CPU and IO shares (#329). |
| +func sliceSize(ctx context.Context, systemctl func(context.Context, ...string) (string, error), host string, mem cgroup.Limit, sh cgroup.Shares) error { |
| + max := strconv.FormatInt(mem.MemoryMax, 10) |
| + high := strconv.FormatInt(cgroup.HighOf(mem.MemoryMax), 10) |
| _, err := systemctl(ctx, "set-property", "--runtime", SliceName(host), |
| "MemoryMax="+max, "MemoryHigh="+high, "MemorySwapMax="+max, |
| "CPUWeight="+strconv.Itoa(sh.CPUWeight), "CPUQuota="+strconv.Itoa(sh.CPUQuotaPercent)+"%", |
diff --git a/internal/instancectl/server_gen_test.go b/internal/instancectl/server_gen_test.go| index c53146719..8af380cd0 100644 |
| --- a/internal/instancectl/server_gen_test.go |
| +++ b/internal/instancectl/server_gen_test.go |
| @@ -847,3 +847,141 @@ func TestCPUQuotaShowsAsSystemdShowsIt(t *testing.T) { |
| } |
| } |
| } |
| + |
| +// TestStartGenClearsAStaleControlDropIn (Review Focus 1, Ruling C5): a |
| +// live /size leaves `set-property --runtime` memory in the control |
| +// directory's <unit>.d until reboot, and it outranks the generation's own |
| +// drop-in. A generation number reused after a cold start would read back |
| +// the old MemoryMax and fail its start with "drop-in did not apply". The |
| +// start removes the unit's own <unit>.d before it writes the drop-in, so |
| +// the reused generation starts; a slice's .d (plan 2's allow evidence) is |
| +// never touched, and a <unit>.d that is a symlink is unlinked, never |
| +// followed. The stop removes it with the other files. |
| +func TestStartGenClearsAStaleControlDropIn(t *testing.T) { |
| + ctl := genCtl() |
| + control, outside := t.TempDir(), t.TempDir() |
| + stale := filepath.Join(control, genUnit+".d", "50-MemoryMax.conf") |
| + sliceEvidence := filepath.Join(control, SliceName(genHost)+".d", "50-IPAddressAllow.conf") |
| + write := func(path, body string) { |
| + t.Helper() |
| + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.WriteFile(path, []byte(body), 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + write(stale, "[Service]\nMemoryMax=1073741824\n") |
| + write(sliceEvidence, "[Slice]\nIPAddressAllow=10.0.5.20\n") |
| + var ( |
| + mu sync.Mutex |
| + looked bool |
| + seen string |
| + ) |
| + // systemd's view: while the control drop-in is on disk, the unit's |
| + // memory is the stale runtime value whatever its own drop-in says, and |
| + // a daemon-reload does not change that. |
| + serve := func(controlDir string) (*Server, string) { |
| + dropins, exe := t.TempDir(), t.TempDir() |
| + return serveOnSocket(t, ctl, func(s *Server) { |
| + s.DropInDir, s.ExeRoot, s.ControlDropInDir = dropins, exe, controlDir |
| + s.Systemctl = func(ctx context.Context, args ...string) (string, error) { |
| + if line := strings.Join(args, " "); strings.HasPrefix(line, genShow) { |
| + _, staleErr := os.Lstat(filepath.Join(control, genUnit+".d")) |
| + _, dropErr := os.Stat(filepath.Join(dropins, genUnit+".d", DropInName)) |
| + mu.Lock() |
| + if !looked { |
| + looked = true |
| + seen = fmt.Sprintf("control .d present=%v, drop-in present=%v", staleErr == nil, dropErr == nil) |
| + } |
| + mu.Unlock() |
| + if staleErr == nil { |
| + ctl.mu.Lock() |
| + ctl.calls = append(ctl.calls, line) |
| + ctl.mu.Unlock() |
| + return "Slice=" + SliceName(genHost) + "\nNeedDaemonReload=no\nMemoryMax=1073741824\nMemoryHigh=966367638\nMemorySwapMax=1073741824\n", nil |
| + } |
| + } |
| + return ctl.run(ctx, args...) |
| + } |
| + }) |
| + } |
| + s, sock := serve(control) |
| + c := NewClient(sock) |
| + if _, err := c.StartGen(context.Background(), genHost, 7, cgroup.TierDefault.MemoryMax); err != nil { |
| + t.Fatalf("the reused generation did not start: %v", err) |
| + } |
| + mu.Lock() |
| + if seen != "control .d present=false, drop-in present=true" { |
| + t.Errorf("at systemd's first look: %s; want the control .d gone and the drop-in written", seen) |
| + } |
| + mu.Unlock() |
| + if strings.Contains(ctl.joined(), "daemon-reload") { |
| + t.Errorf("the start needed a reload:\n%s", ctl.joined()) |
| + } |
| + if _, err := os.Stat(sliceEvidence); err != nil { |
| + t.Errorf("the slice's control drop-in was touched: %v", err) |
| + } |
| + |
| + // The stop removes it with the other files. |
| + write(stale, "[Service]\nMemoryMax=1073741824\n") |
| + if err := c.StopGen(context.Background(), genHost, 7, false); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := os.Lstat(filepath.Join(control, genUnit+".d")); !os.IsNotExist(err) { |
| + t.Errorf("the stop left the control drop-in: %v", err) |
| + } |
| + if _, err := os.Stat(sliceEvidence); err != nil { |
| + t.Errorf("the stop touched the slice's control drop-in: %v", err) |
| + } |
| + |
| + // A <unit>.d that is a symlink is unlinked; its target is untouched. |
| + kept := filepath.Join(outside, "keep.conf") |
| + write(kept, "x") |
| + if err := os.Symlink(outside, filepath.Join(control, genUnit+".d")); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := s.removeGenFiles(genUnit); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := os.Lstat(filepath.Join(control, genUnit+".d")); !os.IsNotExist(err) { |
| + t.Errorf("the symlinked control .d is still there: %v", err) |
| + } |
| + if _, err := os.Stat(kept); err != nil { |
| + t.Errorf("the removal followed the symlink: %v", err) |
| + } |
| + |
| + // Without the removal (no ControlDropInDir), systemd's stale view fails |
| + // the start: this is the failure the removal turns into a start. |
| + write(stale, "[Service]\nMemoryMax=1073741824\n") |
| + _, bare := serve("") |
| + if _, err := NewClient(bare).StartGen(context.Background(), genHost, 7, cgroup.TierDefault.MemoryMax); err == nil || !strings.Contains(err.Error(), "did not apply") { |
| + t.Errorf("with the stale drop-in kept, StartGen = %v; want the drop-in did not apply", err) |
| + } |
| +} |
| + |
| +// A control directory that is itself a symlink is refused, never walked. |
| +func TestRemoveGenFilesRefusesASymlinkedControlDir(t *testing.T) { |
| + outside := t.TempDir() |
| + target := filepath.Join(outside, genUnit+".d") |
| + if err := os.MkdirAll(target, 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + link := filepath.Join(t.TempDir(), "system.control") |
| + if err := os.Symlink(outside, link); err != nil { |
| + t.Fatal(err) |
| + } |
| + s := &Server{ControlDropInDir: link} |
| + if err := s.removeGenFiles(genUnit); err == nil { |
| + t.Error("a symlinked control directory was accepted") |
| + } |
| + if _, err := os.Stat(target); err != nil { |
| + t.Errorf("the removal went through the symlinked control directory: %v", err) |
| + } |
| + // A unit that is not a generation unit names nothing to remove. |
| + for _, unit := range []string{SliceName(genHost), UnitName(RoleRun, genHost), "../x", ""} { |
| + if p, ok := genControlDropIn(t.TempDir(), unit); ok { |
| + t.Errorf("genControlDropIn(%q) = %q, want none", unit, p) |
| + } |
| + } |
| +} |
diff --git a/internal/instancectl/size.go b/internal/instancectl/size.go| new file mode 100644 |
| index 000000000..076acfd38 |
| --- /dev/null |
| +++ b/internal/instancectl/size.go |
| @@ -0,0 +1,280 @@ |
| +package instancectl |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "math" |
| + "net/http" |
| + "net/url" |
| + "os" |
| + "path/filepath" |
| + "strconv" |
| + "strings" |
| + |
| + "github.com/carlosframework/platform/internal/cgroup" |
| + "github.com/carlosframework/platform/internal/provision" |
| +) |
| + |
| +// Live size changes (#329, spec §5.4). A size is enforced in two places: |
| +// the host slice (memory, CPU and IO) and a running generation unit's own |
| +// memory lines, which its drop-in set at its start. POST /size writes the |
| +// slice, then the serving generation, and reads both back; GET /size only |
| +// reads. Both are legacy verbs: with host claims on they answer 503, and a |
| +// new size waits for the host's next start. |
| + |
| +// ErrSizeRefused wraps Size's and ReadSize's answer when root refused the |
| +// request before any write: a bad shape (400), a generation that is not |
| +// active or a memory shrink while the slice is populated (409), or host |
| +// claims on (503). Any other failure may have written the slice. |
| +var ErrSizeRefused = errors.New("instance control: size refused before any write") |
| + |
| +// SizeReadBack is what the slice and the serving generation unit hold, |
| +// as systemd reports them. A value systemd reports as unlimited, or in a |
| +// form this binary does not read, is 0. UnitMemoryMax is set only when the |
| +// request named a generation. |
| +type SizeReadBack struct { |
| + SliceMemoryMax int64 `json:"slice_memory_max"` |
| + CPUQuotaPercent int `json:"cpu_quota_percent"` |
| + CPUWeight int `json:"cpu_weight"` |
| + IOWeight int `json:"io_weight"` |
| + UnitMemoryMax int64 `json:"unit_memory_max,omitempty"` |
| +} |
| + |
| +// sizeRequest is the validated form of a /size query. |
| +type sizeRequest struct { |
| + host string |
| + gen uint64 // the serving generation; 0 is none (the run template) |
| + unit string // GenUnitName(host, gen), or "" with no generation |
| +} |
| + |
| +// parseSizeTarget validates host and the optional gen, as a positive |
| +// canonical integer. It calls nothing. |
| +func parseSizeTarget(q url.Values) (sizeRequest, error) { |
| + host := q.Get("host") |
| + if !provision.ValidHostShape(host) { |
| + return sizeRequest{}, fmt.Errorf("host %q is not a host", host) |
| + } |
| + req := sizeRequest{host: host} |
| + if q.Has("gen") { |
| + raw := q.Get("gen") |
| + n, err := strconv.ParseUint(raw, 10, 64) |
| + if err != nil || n == 0 || strconv.FormatUint(n, 10) != raw { |
| + return sizeRequest{}, fmt.Errorf("gen %q is not a generation", raw) |
| + } |
| + req.gen, req.unit = n, GenUnitName(host, n) |
| + } |
| + return req, nil |
| +} |
| + |
| +// refuseInactiveGen answers 409 unless the request's generation is active, |
| +// so no write is made, and no control drop-in left, for a unit that is |
| +// not running. It reports whether it answered. |
| +func (s *Server) refuseInactiveGen(ctx context.Context, w http.ResponseWriter, req sizeRequest) bool { |
| + if req.unit == "" { |
| + return false |
| + } |
| + if state := s.showValue(ctx, "ActiveState", req.unit); state != "active" { |
| + http.Error(w, req.unit+" is not active ("+strconv.Quote(state)+")", http.StatusConflict) |
| + return true |
| + } |
| + return false |
| +} |
| + |
| +// handleSize applies a size live: the slice first, then the serving |
| +// generation unit, then a read-back of both (spec §5.4). The request names |
| +// the size (its CPU and IO shares) and the memory separately, because a |
| +// smaller size keeps the memory in force while anything runs: the |
| +// activator sends the held memory with the smaller size's shares, and root |
| +// refuses any memory below what the slice or the unit holds while the |
| +// slice is populated (R1-3). |
| +func (s *Server) handleSize(w http.ResponseWriter, r *http.Request) { |
| + ctx := r.Context() |
| + q := r.URL.Query() |
| + req, err := parseSizeTarget(q) |
| + if err != nil { |
| + http.Error(w, err.Error(), http.StatusBadRequest) |
| + return |
| + } |
| + size, ok := cgroup.SizeByName(q.Get("size")) |
| + if !ok { |
| + http.Error(w, "size "+strconv.Quote(q.Get("size"))+" is not a platform size", http.StatusBadRequest) |
| + return |
| + } |
| + n, err := strconv.ParseInt(q.Get("memory_max"), 10, 64) |
| + if _, ok := cgroup.SizeOf(cgroup.Limit{MemoryMax: n}); err != nil || !ok { |
| + http.Error(w, "memory_max "+strconv.Quote(q.Get("memory_max"))+" is not a platform size's memory", http.StatusBadRequest) |
| + return |
| + } |
| + if s.refuseInactiveGen(ctx, w, req) { |
| + return |
| + } |
| + if s.slicePopulated(req.host) { |
| + held := []string{SliceName(req.host)} |
| + if req.unit != "" { |
| + held = append(held, req.unit) |
| + } |
| + for _, name := range held { |
| + raw := s.showValue(ctx, "MemoryMax", name) |
| + now, ok := showMemoryMax(raw) |
| + if !ok { |
| + http.Error(w, "show "+name+": MemoryMax "+strconv.Quote(raw)+" is not a number", http.StatusBadGateway) |
| + return |
| + } |
| + if n < now { |
| + http.Error(w, "memory never shrinks while the slice is populated: "+name+" holds "+raw, http.StatusConflict) |
| + return |
| + } |
| + } |
| + } |
| + mem := cgroup.Limit{MemoryMax: n} |
| + if err := sliceSize(ctx, s.Systemctl, req.host, mem, size.Shares); err != nil { |
| + http.Error(w, "set-property "+SliceName(req.host)+": "+err.Error(), http.StatusBadGateway) |
| + return |
| + } |
| + if req.unit != "" { |
| + max := strconv.FormatInt(n, 10) |
| + if out, err := s.Systemctl(ctx, "set-property", "--runtime", req.unit, |
| + "MemoryMax="+max, "MemoryHigh="+strconv.FormatInt(cgroup.HighOf(n), 10), "MemorySwapMax="+max); err != nil { |
| + http.Error(w, "set-property "+req.unit+": "+strings.TrimSpace(out+" "+err.Error()), http.StatusBadGateway) |
| + return |
| + } |
| + } |
| + s.logf("instance-control: %s: size %s memory.max=%d (gen %d)", req.host, size.Name, n, req.gen) |
| + s.writeSizeReadBack(ctx, w, req) |
| +} |
| + |
| +// handleSizeReadBack is GET /size: the read-back alone, writing nothing. |
| +func (s *Server) handleSizeReadBack(w http.ResponseWriter, r *http.Request) { |
| + req, err := parseSizeTarget(r.URL.Query()) |
| + if err != nil { |
| + http.Error(w, err.Error(), http.StatusBadRequest) |
| + return |
| + } |
| + if s.refuseInactiveGen(r.Context(), w, req) { |
| + return |
| + } |
| + s.writeSizeReadBack(r.Context(), w, req) |
| +} |
| + |
| +// writeSizeReadBack reads the slice's memory, CPU and IO and, with a |
| +// generation, the unit's memory, and answers them. A read that fails is a |
| +// 502: after a write, the caller cannot tell what is in force. |
| +func (s *Server) writeSizeReadBack(ctx context.Context, w http.ResponseWriter, req sizeRequest) { |
| + slice, err := s.Systemctl(ctx, "show", "-p", "MemoryMax", "-p", "CPUQuotaPerSecUSec", "-p", "CPUWeight", "-p", "IOWeight", SliceName(req.host)) |
| + if err != nil { |
| + http.Error(w, "show "+SliceName(req.host)+": "+strings.TrimSpace(slice+" "+err.Error()), http.StatusBadGateway) |
| + return |
| + } |
| + var unit string |
| + if req.unit != "" { |
| + if unit, err = s.Systemctl(ctx, "show", "-p", "MemoryMax", req.unit); err != nil { |
| + http.Error(w, "show "+req.unit+": "+strings.TrimSpace(unit+" "+err.Error()), http.StatusBadGateway) |
| + return |
| + } |
| + } |
| + writeJSON(w, http.StatusOK, parseSizeShow(slice, unit)) |
| +} |
| + |
| +// parseSizeShow reads systemctl show's answers for the slice and, if not |
| +// "", the unit. CPUQuotaPerSecUSec is mapped back to a size's percent |
| +// through cpuQuotaShown (500ms, 1s, 2s, 4s are 50, 100, 200, 400); any |
| +// other value, infinity included, is 0. MemoryMax=infinity is 0. |
| +func parseSizeShow(slice, unit string) SizeReadBack { |
| + sl := parseShow(slice) |
| + rb := SizeReadBack{ |
| + SliceMemoryMax: showBytes(sl["MemoryMax"]), |
| + CPUWeight: showInt(sl["CPUWeight"]), |
| + IOWeight: showInt(sl["IOWeight"]), |
| + } |
| + for _, size := range cgroup.Sizes { |
| + if pct := size.Shares.CPUQuotaPercent; sl["CPUQuotaPerSecUSec"] == cpuQuotaShown(pct) { |
| + rb.CPUQuotaPercent = pct |
| + break |
| + } |
| + } |
| + if unit != "" { |
| + rb.UnitMemoryMax = showBytes(parseShow(unit)["MemoryMax"]) |
| + } |
| + return rb |
| +} |
| + |
| +// showBytes is a MemoryMax= value in bytes; infinity, or anything that is |
| +// not a non-negative integer, is 0. |
| +func showBytes(v string) int64 { |
| + n, err := strconv.ParseInt(v, 10, 64) |
| + if err != nil || n < 0 { |
| + return 0 |
| + } |
| + return n |
| +} |
| + |
| +func showInt(v string) int { |
| + n, err := strconv.Atoi(v) |
| + if err != nil || n < 0 { |
| + return 0 |
| + } |
| + return n |
| +} |
| + |
| +// showMemoryMax is the pre-check's reading of a MemoryMax --value: |
| +// infinity is above every size, so nothing is lowered from it while the |
| +// slice is populated. A value it cannot read is not ok: the request fails |
| +// before any write rather than guess. |
| +func showMemoryMax(v string) (int64, bool) { |
| + if v == "infinity" { |
| + return math.MaxInt64, true |
| + } |
| + n, err := strconv.ParseInt(v, 10, 64) |
| + return n, err == nil && n >= 0 |
| +} |
| + |
| +// genControlDropIn is the path of a generation unit's own directory under |
| +// systemd's control directory, where `set-property --runtime` on the unit |
| +// keeps its values (/run/systemd/system.control/<unit>.d). The name is |
| +// rebuilt from the parsed unit name, so it is only ever a generation |
| +// unit's .d, never a slice's (plan 2 keeps the slice's allow evidence in |
| +// <slice>.d/50-IPAddressAllow.conf) and never another path. |
| +func genControlDropIn(controlDir, unit string) (string, bool) { |
| + esc, n, ok := ParseGenUnitName(unit) |
| + if !ok { |
| + return "", false |
| + } |
| + name := UnitPrefixGen + esc + ":" + strconv.FormatUint(n, 10) + ".service" |
| + if name != unit { |
| + return "", false |
| + } |
| + return filepath.Join(controlDir, name+".d"), true |
| +} |
| + |
| +// removeGenControlDropIn removes a generation unit's runtime properties: |
| +// systemd keeps a `set-property --runtime` on the unit until reboot, and |
| +// it outranks the generation's own drop-in, so a generation number reused |
| +// after a cold start would start at an old size (or, with genView's check, |
| +// not start at all). This also removes plan 2's nudge drop-in |
| +// (50-IPAddressAllow.conf) for that unit, which is correct: the unit is |
| +// not running, and AssertStart re-applies the slice's allow before any |
| +// start. The control directory itself must be a real directory, never a |
| +// symlink; the unit's .d is removed with os.RemoveAll, which unlinks a |
| +// symlink rather than following it and never follows one inside. An empty |
| +// ControlDropInDir skips it (tests). |
| +func (s *Server) removeGenControlDropIn(unit string) error { |
| + if s.ControlDropInDir == "" { |
| + return nil |
| + } |
| + path, ok := genControlDropIn(s.ControlDropInDir, unit) |
| + if !ok { |
| + return nil |
| + } |
| + fi, err := os.Lstat(s.ControlDropInDir) |
| + if errors.Is(err, os.ErrNotExist) { |
| + return nil |
| + } |
| + if err != nil { |
| + return err |
| + } |
| + if !fi.IsDir() { |
| + return fmt.Errorf("control drop-in directory %s is not a directory", s.ControlDropInDir) |
| + } |
| + return os.RemoveAll(path) |
| +} |
diff --git a/internal/instancectl/size_test.go b/internal/instancectl/size_test.go| new file mode 100644 |
| index 000000000..725d19de7 |
| --- /dev/null |
| +++ b/internal/instancectl/size_test.go |
| @@ -0,0 +1,323 @@ |
| +package instancectl |
| + |
| +import ( |
| + "encoding/json" |
| + "errors" |
| + "io" |
| + "net/http" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +const sizeHost = "shop-a.example.com" |
| + |
| +var errSizeWrite = errors.New("exit status 1") |
| + |
| +var ( |
| + sizeSlice = SliceName(sizeHost) |
| + sizeUnit = GenUnitName(sizeHost, 3) |
| + // sizeReadBackSlice and sizeReadBackUnit are the read-back's two shows. |
| + sizeReadBackSlice = "show -p MemoryMax -p CPUQuotaPerSecUSec -p CPUWeight -p IOWeight " + sizeSlice |
| + sizeReadBackUnit = "show -p MemoryMax " + sizeUnit |
| +) |
| + |
| +// sizeCtl answers the generation as active, the slice and the unit at |
| +// held bytes for the pre-check, and the read-back with the given shows. |
| +func sizeCtl(held, sliceShow, unitShow string) *fakeCtl { |
| + return &fakeCtl{answers: map[string]string{ |
| + "show -p ActiveState --value " + sizeUnit: "active\n", |
| + "show -p MemoryMax --value " + sizeSlice: held + "\n", |
| + "show -p MemoryMax --value " + sizeUnit: held + "\n", |
| + sizeReadBackSlice: sliceShow, |
| + sizeReadBackUnit: unitShow, |
| + }} |
| +} |
| + |
| +// sizePopulated writes the host slice's cgroup.events as the kernel would |
| +// for a slice with something running in it. |
| +func sizePopulated(t *testing.T, s *Server) { |
| + t.Helper() |
| + dir := filepath.Join(s.CgroupRoot, parentSlices, sizeSlice) |
| + if err := os.MkdirAll(dir, 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.WriteFile(filepath.Join(dir, "cgroup.events"), []byte("populated 1\nfrozen 0\n"), 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +func postSize(t *testing.T, c *http.Client, query string) (int, string) { |
| + t.Helper() |
| + resp, err := c.Post("http://control/size?"+query, "", nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer resp.Body.Close() |
| + body, _ := io.ReadAll(resp.Body) |
| + return resp.StatusCode, string(body) |
| +} |
| + |
| +func countSetProperty(calls string) int { |
| + return strings.Count(calls, "set-property") |
| +} |
| + |
| +func TestSizeGrowsTheSliceThenTheGenerationThenReadsBack(t *testing.T) { |
| + ctl := sizeCtl("536870912", |
| + "MemoryMax=1073741824\nCPUQuotaPerSecUSec=2s\nCPUWeight=100\nIOWeight=100\n", |
| + "MemoryMax=1073741824\n") |
| + s, c := newServer(t, ctl) |
| + sizePopulated(t, s) |
| + status, body := postSize(t, c, "host="+sizeHost+"&size=large&memory_max=1073741824&gen=3") |
| + if status != http.StatusOK { |
| + t.Fatalf("status %d: %s", status, body) |
| + } |
| + want := strings.Join([]string{ |
| + "show -p ActiveState --value " + sizeUnit, |
| + "show -p MemoryMax --value " + sizeSlice, |
| + "show -p MemoryMax --value " + sizeUnit, |
| + `set-property --runtime carlos-instances-shop\x2da.example.com.slice MemoryMax=1073741824 MemoryHigh=966367638 MemorySwapMax=1073741824 CPUWeight=100 CPUQuota=200% IOWeight=100`, |
| + "set-property --runtime " + sizeUnit + " MemoryMax=1073741824 MemoryHigh=966367638 MemorySwapMax=1073741824", |
| + sizeReadBackSlice, |
| + sizeReadBackUnit, |
| + }, "\n") |
| + if got := ctl.joined(); got != want { |
| + t.Errorf("calls =\n%s\nwant\n%s", got, want) |
| + } |
| + var rb SizeReadBack |
| + if err := json.Unmarshal([]byte(body), &rb); err != nil { |
| + t.Fatal(err) |
| + } |
| + if want := (SizeReadBack{SliceMemoryMax: 1073741824, CPUQuotaPercent: 200, CPUWeight: 100, IOWeight: 100, UnitMemoryMax: 1073741824}); rb != want { |
| + t.Errorf("read-back = %+v, want %+v", rb, want) |
| + } |
| +} |
| + |
| +// A CPU and IO shrink is applied live with memory held where it is: the |
| +// activator sends the held memory with the smaller size's shares. |
| +func TestSizeShrinksCPUWithMemoryHeld(t *testing.T) { |
| + ctl := sizeCtl("1073741824", |
| + "MemoryMax=1073741824\nCPUQuotaPerSecUSec=500ms\nCPUWeight=50\nIOWeight=50\n", "") |
| + s, c := newServer(t, ctl) |
| + sizePopulated(t, s) |
| + status, body := postSize(t, c, "host="+sizeHost+"&size=small&memory_max=1073741824") |
| + if status != http.StatusOK { |
| + t.Fatalf("status %d: %s", status, body) |
| + } |
| + line := `set-property --runtime carlos-instances-shop\x2da.example.com.slice MemoryMax=1073741824 MemoryHigh=966367638 MemorySwapMax=1073741824 CPUWeight=50 CPUQuota=50% IOWeight=50` |
| + if got := ctl.joined(); !strings.Contains(got, line) || countSetProperty(got) != 1 { |
| + t.Errorf("calls =\n%s\nwant exactly one set-property:\n%s", got, line) |
| + } |
| + var rb SizeReadBack |
| + if err := json.Unmarshal([]byte(body), &rb); err != nil { |
| + t.Fatal(err) |
| + } |
| + if want := (SizeReadBack{SliceMemoryMax: 1073741824, CPUQuotaPercent: 50, CPUWeight: 50, IOWeight: 50}); rb != want { |
| + t.Errorf("read-back = %+v, want %+v", rb, want) |
| + } |
| + if strings.Contains(body, "unit_memory_max") { |
| + t.Errorf("a read-back without a generation carries unit_memory_max: %s", body) |
| + } |
| +} |
| + |
| +func TestSizeRefusesAMemoryShrinkWhilePopulated(t *testing.T) { |
| + for _, q := range []string{ |
| + "host=" + sizeHost + "&size=standard&memory_max=536870912", |
| + "host=" + sizeHost + "&size=standard&memory_max=536870912&gen=3", |
| + } { |
| + ctl := sizeCtl("1073741824", "", "") |
| + s, c := newServer(t, ctl) |
| + sizePopulated(t, s) |
| + status, body := postSize(t, c, q) |
| + if status != http.StatusConflict || !strings.Contains(body, "memory never shrinks while the slice is populated") { |
| + t.Errorf("%s: status %d: %s, want 409", q, status, body) |
| + } |
| + if got := ctl.joined(); countSetProperty(got) != 0 { |
| + t.Errorf("%s: a refused shrink wrote:\n%s", q, got) |
| + } |
| + } |
| + // The unit alone held above the request is refused too. |
| + ctl := sizeCtl("536870912", "", "") |
| + ctl.answers["show -p MemoryMax --value "+sizeUnit] = "1073741824\n" |
| + s, c := newServer(t, ctl) |
| + sizePopulated(t, s) |
| + if status, body := postSize(t, c, "host="+sizeHost+"&size=standard&memory_max=536870912&gen=3"); status != http.StatusConflict { |
| + t.Errorf("unit held above: status %d: %s, want 409", status, body) |
| + } |
| + if got := ctl.joined(); countSetProperty(got) != 0 { |
| + t.Errorf("unit held above: a refused shrink wrote:\n%s", got) |
| + } |
| + // An unbounded slice (infinity) is above every size: never lowered |
| + // while anything runs. |
| + ctl = sizeCtl("infinity", "", "") |
| + s, c = newServer(t, ctl) |
| + sizePopulated(t, s) |
| + if status, body := postSize(t, c, "host="+sizeHost+"&size=xlarge&memory_max=2147483648"); status != http.StatusConflict { |
| + t.Errorf("infinity: status %d: %s, want 409", status, body) |
| + } |
| + if got := ctl.joined(); countSetProperty(got) != 0 { |
| + t.Errorf("infinity: a refused shrink wrote:\n%s", got) |
| + } |
| +} |
| + |
| +// An empty slice is a cold one: memory may go down, and nothing is read |
| +// for the pre-check. |
| +func TestSizeLowersMemoryOnAnEmptySlice(t *testing.T) { |
| + ctl := sizeCtl("1073741824", "MemoryMax=268435456\nCPUQuotaPerSecUSec=500ms\nCPUWeight=50\nIOWeight=50\n", "") |
| + _, c := newServer(t, ctl) |
| + if status, body := postSize(t, c, "host="+sizeHost+"&size=small&memory_max=268435456"); status != http.StatusOK { |
| + t.Fatalf("status %d: %s", status, body) |
| + } |
| + if got := ctl.joined(); strings.Contains(got, "--value") || countSetProperty(got) != 1 { |
| + t.Errorf("calls =\n%s\nwant one write and no pre-check", got) |
| + } |
| +} |
| + |
| +// A generation that is not active is refused before any write, so no |
| +// control drop-in is left for a unit that is not running (Review Focus 5). |
| +func TestSizeRefusesAnInactiveGeneration(t *testing.T) { |
| + for _, state := range []string{"inactive\n", "failed\n", "activating\n", ""} { |
| + ctl := sizeCtl("536870912", "", "") |
| + ctl.answers["show -p ActiveState --value "+sizeUnit] = state |
| + s, c := newServer(t, ctl) |
| + sizePopulated(t, s) |
| + status, body := postSize(t, c, "host="+sizeHost+"&size=large&memory_max=1073741824&gen=3") |
| + if status != http.StatusConflict { |
| + t.Errorf("ActiveState %q: status %d: %s, want 409", state, status, body) |
| + } |
| + if got := ctl.joined(); got != "show -p ActiveState --value "+sizeUnit { |
| + t.Errorf("ActiveState %q: calls =\n%s\nwant the state read only", state, got) |
| + } |
| + } |
| + // GET /size refuses the same way. |
| + ctl := sizeCtl("536870912", "", "") |
| + ctl.answers["show -p ActiveState --value "+sizeUnit] = "inactive\n" |
| + _, c := newServer(t, ctl) |
| + resp, err := c.Get("http://control/size?host=" + sizeHost + "&gen=3") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + resp.Body.Close() |
| + if resp.StatusCode != http.StatusConflict { |
| + t.Errorf("GET /size of an inactive generation: %d, want 409", resp.StatusCode) |
| + } |
| +} |
| + |
| +func TestSizeRefusesBadInputs(t *testing.T) { |
| + ok := "host=" + sizeHost + "&size=large&memory_max=1073741824" |
| + for _, q := range []string{ |
| + "host=" + sizeHost + "&size=huge&memory_max=1073741824", |
| + "host=" + sizeHost + "&size=Large&memory_max=1073741824", |
| + "host=" + sizeHost + "&memory_max=1073741824", |
| + "host=" + sizeHost + "&size=large&memory_max=805306368", |
| + "host=" + sizeHost + "&size=large&memory_max=x", |
| + "host=" + sizeHost + "&size=large", |
| + ok + "&gen=0", |
| + ok + "&gen=03", |
| + ok + "&gen=-1", |
| + ok + "&gen=", |
| + "host=../etc&size=large&memory_max=1073741824", |
| + "host=&size=large&memory_max=1073741824", |
| + } { |
| + ctl := sizeCtl("536870912", "", "") |
| + _, c := newServer(t, ctl) |
| + if status, body := postSize(t, c, q); status != http.StatusBadRequest { |
| + t.Errorf("%s: status %d: %s, want 400", q, status, body) |
| + } |
| + if got := ctl.joined(); got != "" { |
| + t.Errorf("%s: systemctl called:\n%s", q, got) |
| + } |
| + } |
| + for _, q := range []string{"host=../etc", "host=" + sizeHost + "&gen=0", "host=" + sizeHost + "&gen=03"} { |
| + ctl := sizeCtl("536870912", "", "") |
| + _, c := newServer(t, ctl) |
| + resp, err := c.Get("http://control/size?" + q) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + resp.Body.Close() |
| + if resp.StatusCode != http.StatusBadRequest { |
| + t.Errorf("GET %s: %d, want 400", q, resp.StatusCode) |
| + } |
| + if got := ctl.joined(); got != "" { |
| + t.Errorf("GET %s: systemctl called:\n%s", q, got) |
| + } |
| + } |
| +} |
| + |
| +func TestSizeUnitWriteFailureIs502(t *testing.T) { |
| + ctl := sizeCtl("536870912", "", "") |
| + ctl.fail = map[string]error{"set-property --runtime " + sizeUnit: errSizeWrite} |
| + s, c := newServer(t, ctl) |
| + sizePopulated(t, s) |
| + status, body := postSize(t, c, "host="+sizeHost+"&size=large&memory_max=1073741824&gen=3") |
| + if status != http.StatusBadGateway { |
| + t.Fatalf("status %d: %s, want 502", status, body) |
| + } |
| + got := ctl.joined() |
| + if !strings.Contains(got, "set-property --runtime "+sizeSlice) { |
| + t.Errorf("the slice was not written first:\n%s", got) |
| + } |
| + if strings.Contains(got, sizeReadBackSlice) { |
| + t.Errorf("a failed write was read back as if applied:\n%s", got) |
| + } |
| + // A slice write that fails stops before the unit. |
| + ctl = sizeCtl("536870912", "", "") |
| + ctl.fail = map[string]error{"set-property --runtime " + sizeSlice: errSizeWrite} |
| + s, c = newServer(t, ctl) |
| + sizePopulated(t, s) |
| + if status, body := postSize(t, c, "host="+sizeHost+"&size=large&memory_max=1073741824&gen=3"); status != http.StatusBadGateway { |
| + t.Fatalf("slice failure: status %d: %s, want 502", status, body) |
| + } |
| + if got := ctl.joined(); strings.Contains(got, "set-property --runtime "+sizeUnit) { |
| + t.Errorf("the unit was written after the slice write failed:\n%s", got) |
| + } |
| +} |
| + |
| +func TestSizeReadBackServesTheSliceAndUnit(t *testing.T) { |
| + ctl := sizeCtl("536870912", |
| + "CPUWeight=100\nIOWeight=100\nMemoryMax=536870912\nCPUQuotaPerSecUSec=1s\n", |
| + "MemoryMax=536870912\n") |
| + _, c := newServer(t, ctl) |
| + resp, err := c.Get("http://control/size?host=" + sizeHost + "&gen=3") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer resp.Body.Close() |
| + var rb SizeReadBack |
| + if resp.StatusCode != http.StatusOK || json.NewDecoder(resp.Body).Decode(&rb) != nil { |
| + t.Fatalf("GET /size: %d", resp.StatusCode) |
| + } |
| + if want := (SizeReadBack{SliceMemoryMax: 536870912, CPUQuotaPercent: 100, CPUWeight: 100, IOWeight: 100, UnitMemoryMax: 536870912}); rb != want { |
| + t.Errorf("read-back = %+v, want %+v", rb, want) |
| + } |
| + if got := ctl.joined(); countSetProperty(got) != 0 { |
| + t.Errorf("GET /size wrote:\n%s", got) |
| + } |
| +} |
| + |
| +func TestSizeReadBackParsesSystemd(t *testing.T) { |
| + for _, tc := range []struct { |
| + slice, unit string |
| + want SizeReadBack |
| + }{ |
| + {"MemoryMax=268435456\nCPUQuotaPerSecUSec=500ms\nCPUWeight=50\nIOWeight=50\n", "", |
| + SizeReadBack{SliceMemoryMax: 268435456, CPUQuotaPercent: 50, CPUWeight: 50, IOWeight: 50}}, |
| + {"MemoryMax=536870912\nCPUQuotaPerSecUSec=1s\nCPUWeight=100\nIOWeight=100\n", "MemoryMax=536870912\n", |
| + SizeReadBack{SliceMemoryMax: 536870912, CPUQuotaPercent: 100, CPUWeight: 100, IOWeight: 100, UnitMemoryMax: 536870912}}, |
| + {"MemoryMax=1073741824\nCPUQuotaPerSecUSec=2s\nCPUWeight=100\nIOWeight=100\n", "MemoryMax=infinity\n", |
| + SizeReadBack{SliceMemoryMax: 1073741824, CPUQuotaPercent: 200, CPUWeight: 100, IOWeight: 100}}, |
| + {"MemoryMax=2147483648\nCPUQuotaPerSecUSec=4s\nCPUWeight=200\nIOWeight=200\n", "", |
| + SizeReadBack{SliceMemoryMax: 2147483648, CPUQuotaPercent: 400, CPUWeight: 200, IOWeight: 200}}, |
| + {"MemoryMax=infinity\nCPUQuotaPerSecUSec=infinity\nCPUWeight=[not set]\nIOWeight=[not set]\n", "", |
| + SizeReadBack{}}, |
| + {"MemoryMax=805306368\nCPUQuotaPerSecUSec=1.500000s\nCPUWeight=100\nIOWeight=100\n", "", |
| + SizeReadBack{SliceMemoryMax: 805306368, CPUWeight: 100, IOWeight: 100}}, |
| + {"MemoryMax=x\nCPUQuotaPerSecUSec=3s\n", "", SizeReadBack{}}, |
| + } { |
| + if got := parseSizeShow(tc.slice, tc.unit); got != tc.want { |
| + t.Errorf("parseSizeShow(%q, %q) = %+v, want %+v", tc.slice, tc.unit, got, tc.want) |
| + } |
| + } |
| +} |