sizes: no live memory change (ruling 12); CPU and IO stay live
Root's POST /size writes only CPUWeight, CPUQuota and IOWeight on the host slice and reads the slice back; memory_max and gen are refused. Removed: the populated-slice shrink pre-check, the generation unit write, the in-flight start tier records and GET /size's generation read. The per-host lock stays where /size and /parent both write the slice. The activator sends the effective size once per column change. A failed or disagreeing read-back is owed and retried next sweep; a refusal is recorded and not retried. Removed: read before write, MaxLimit memory, captured-tier updates and the unsettled swap block; swaps wait only for a call in flight.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
18 files changed,
+531
−1,275
internal/activator/activator.go+6 −4internal/activator/containment.go+7 −17internal/activator/containment_test.go+11 −22internal/activator/control.go+4 −5internal/activator/genbackend.go+2 −10internal/activator/opset.go+11 −14internal/activator/size.go+58 −95internal/activator/size_live_test.go+134 −229internal/activator/swap.go+7 −6internal/activator/swap_fixture_test.go+24 −50internal/instancectl/client.go+13 −23internal/instancectl/client_test.go+17 −23internal/instancectl/cmd.go+0 −3internal/instancectl/gen.go+3 −3internal/instancectl/server.go+20 −78internal/instancectl/server_gen_test.go+28 −51internal/instancectl/size.go+67 −166internal/instancectl/size_test.go+119 −476
diff --git a/internal/activator/activator.go b/internal/activator/activator.go| index 2335c7a00..1fbe631fd 100644 |
| --- a/internal/activator/activator.go |
| +++ b/internal/activator/activator.go |
| @@ -618,13 +618,15 @@ type actEntry struct { |
| // The live size change's view of the size column (#329, size.go), all |
| // written under a.mu. sizeSeen is the column this entry last acted on: |
| // the wake's row, then each pass's. sizeDirty is NoteSize's hint that |
| - // the column may have moved. sizeChecking marks a pass in flight, from |
| - // its registry compare to its end; unlike ops.resizing it holds nothing |
| - // back (no swap, stop or lease waits on it). sizeCheckedAt paces the |
| - // slow backstop compare. |
| + // the column may have moved. sizeOwed is a CPU and IO write that failed |
| + // and is sent again on the next sweep. sizeChecking marks a pass in |
| + // flight, from its registry compare to its end; unlike ops.resizing it |
| + // holds nothing back (no swap, stop or lease waits on it). |
| + // sizeCheckedAt paces the slow backstop compare. |
| sizeSeen string |
| sizeSeenSet bool |
| sizeDirty bool |
| + sizeOwed bool |
| sizeChecking bool |
| sizeCheckedAt time.Time |
| // genReaping is true while reapCurrentGen is running for this pending |
diff --git a/internal/activator/containment.go b/internal/activator/containment.go| index 19a7358ca..088faa926 100644 |
| --- a/internal/activator/containment.go |
| +++ b/internal/activator/containment.go |
| @@ -404,8 +404,8 @@ func (b *ExecBackend) ParentLimit(ctx context.Context, rt registry.Route, l cgro |
| // liveSizeControl is the size channel for rt, which only a nested host has: |
| // root owns its slice. Every other layout, and a channel without the size |
| -// verbs, is errSizeNotLive. Unlike ParentLimit it does not need |
| -// GenContainment: gen 0 is the run template's slice alone. |
| +// verb, is errSizeNotLive. Unlike ParentLimit it does not need |
| +// GenContainment: the call names the slice alone. |
| func (b *ExecBackend) liveSizeControl(rt registry.Route) (SizeControl, error) { |
| if p := b.pathsFor(rt); p.layout != LayoutNested { |
| return nil, fmt.Errorf("%s: %w (layout %q)", rt.Host, errSizeNotLive, p.layout) |
| @@ -413,25 +413,15 @@ func (b *ExecBackend) liveSizeControl(rt registry.Route) (SizeControl, error) { |
| return b.sizeControl() |
| } |
| -// ResizeLive asks root to size rt's slice and, with gen, that generation's |
| -// unit (#329): CPU and IO from size, memory at memoryMax, which the caller |
| -// never puts below what it read. It answers root's read-back. |
| -func (b *ExecBackend) ResizeLive(ctx context.Context, rt registry.Route, gen uint64, size cgroup.Size, memoryMax int64) (instancectl.SizeReadBack, error) { |
| +// ResizeLive asks root to set rt's slice to size's CPU and IO shares |
| +// (#329, spec §5.4 rev 10). Memory is never changed live. It answers |
| +// root's read-back of the slice. |
| +func (b *ExecBackend) ResizeLive(ctx context.Context, rt registry.Route, size cgroup.Size) (instancectl.SizeReadBack, error) { |
| sc, err := b.liveSizeControl(rt) |
| if err != nil { |
| return instancectl.SizeReadBack{}, err |
| } |
| - return sc.Size(ctx, rt.Host, gen, size.Name, memoryMax) |
| -} |
| - |
| -// ReadSize reads what rt's slice and, with gen, that generation's unit hold |
| -// now. It writes nothing. |
| -func (b *ExecBackend) ReadSize(ctx context.Context, rt registry.Route, gen uint64) (instancectl.SizeReadBack, error) { |
| - sc, err := b.liveSizeControl(rt) |
| - if err != nil { |
| - return instancectl.SizeReadBack{}, err |
| - } |
| - return sc.ReadSize(ctx, rt.Host, gen) |
| + return sc.Size(ctx, rt.Host, size.Name) |
| } |
| // KillGen kills generation n outright and returns once its child is empty |
diff --git a/internal/activator/containment_test.go b/internal/activator/containment_test.go| index 79170f722..746cee3a2 100644 |
| --- a/internal/activator/containment_test.go |
| +++ b/internal/activator/containment_test.go |
| @@ -51,7 +51,7 @@ func (f fakeGenControl) Parent(_ context.Context, host string, max int64) error |
| return nil |
| } |
| -// fakeSizeControl is fakeGenControl plus root's /size verbs (Task 6, Astra |
| +// fakeSizeControl is fakeGenControl plus root's /size verb (Task 6, Astra |
| // plan R8-2): a separate interface, as GenControl's method set has none. |
| type fakeSizeControl struct { |
| fakeGenControl |
| @@ -59,47 +59,36 @@ type fakeSizeControl struct { |
| err error |
| } |
| -func (f fakeSizeControl) Size(_ context.Context, host string, gen uint64, size string, mem int64) (instancectl.SizeReadBack, error) { |
| - f.rec(fmt.Sprintf("size %s %d %s %d", host, gen, size, mem)) |
| - return f.rb, f.err |
| -} |
| - |
| -func (f fakeSizeControl) ReadSize(_ context.Context, host string, gen uint64) (instancectl.SizeReadBack, error) { |
| - f.rec(fmt.Sprintf("readsize %s %d", host, gen)) |
| +func (f fakeSizeControl) Size(_ context.Context, host, size string) (instancectl.SizeReadBack, error) { |
| + f.rec(fmt.Sprintf("size %s %s", host, size)) |
| return f.rb, f.err |
| } |
| // The exec backend sizes a nested host only through SizeControl, never |
| -// GenControl, and refuses every other layout and a channel without the |
| -// verbs before any call (Astra plan R8-2). |
| +// GenControl, naming the host and the size alone (no memory, no |
| +// generation: ruling 12), and refuses every other layout and a channel |
| +// without the verb before any call (Astra plan R8-2). |
| func TestExecBackendSizesThroughSizeControl(t *testing.T) { |
| t.Parallel() |
| large, _ := cgroup.SizeByName("large") |
| - rb := instancectl.SizeReadBack{SliceMemoryMax: 1 << 30, UnitMemoryMax: 1 << 30, CPUQuotaPercent: 200, CPUWeight: 100, IOWeight: 100} |
| + rb := instancectl.SizeReadBack{SliceMemoryMax: 1 << 29, CPUQuotaPercent: 200, CPUWeight: 100, IOWeight: 100} |
| ctx := context.Background() |
| ctl := &fakeControl{} |
| b, rt := nestedBackend(t, ctl, &fakeUnit{}) |
| b.Control = fakeSizeControl{fakeGenControl: fakeGenControl{ctl}, rb: rb} |
| - got, err := b.ReadSize(ctx, rt, 3) |
| - if err != nil || got != rb { |
| - t.Fatalf("ReadSize = %+v, %v; want %+v", got, err, rb) |
| - } |
| - got, err = b.ResizeLive(ctx, rt, 3, large, 1<<30) |
| + got, err := b.ResizeLive(ctx, rt, large) |
| if err != nil || got != rb { |
| t.Fatalf("ResizeLive = %+v, %v; want %+v", got, err, rb) |
| } |
| - if calls, want := strings.Join(ctl.calls, "\n"), "readsize h.example.com 3\nsize h.example.com 3 large 1073741824"; calls != want { |
| + if calls, want := strings.Join(ctl.calls, "\n"), "size h.example.com large"; calls != want { |
| t.Fatalf("calls:\n%s\nwant:\n%s", calls, want) |
| } |
| refused := func(name string, b *ExecBackend, rt registry.Route, ctl *fakeControl) { |
| t.Helper() |
| before := len(ctl.calls) |
| - if _, err := b.ReadSize(ctx, rt, 3); !errors.Is(err, errSizeNotLive) { |
| - t.Errorf("%s: ReadSize = %v, want errSizeNotLive", name, err) |
| - } |
| - if _, err := b.ResizeLive(ctx, rt, 3, large, 1<<30); !errors.Is(err, errSizeNotLive) { |
| + if _, err := b.ResizeLive(ctx, rt, large); !errors.Is(err, errSizeNotLive) { |
| t.Errorf("%s: ResizeLive = %v, want errSizeNotLive", name, err) |
| } |
| if len(ctl.calls) != before { |
| @@ -107,7 +96,7 @@ func TestExecBackendSizesThroughSizeControl(t *testing.T) { |
| } |
| } |
| - // A channel with the generation verbs but no size verbs. |
| + // A channel with the generation verbs but no size verb. |
| ctl2 := &fakeControl{} |
| b2, rt2 := nestedBackend(t, ctl2, &fakeUnit{}) |
| b2.Control = fakeGenControl{ctl2} |
diff --git a/internal/activator/control.go b/internal/activator/control.go| index e2416d17d..cd5d1332a 100644 |
| --- a/internal/activator/control.go |
| +++ b/internal/activator/control.go |
| @@ -46,15 +46,14 @@ type GenControl interface { |
| var _ GenControl = (*instancectl.Client)(nil) |
| -// SizeControl is root's live size verbs (#329, spec §5.4): POST /size |
| -// writes host's slice and, with gen, that generation unit's memory; GET |
| -// /size reads both back. It is separate from GenControl, as |
| +// SizeControl is root's live size verb (#329, spec §5.4 rev 10): POST |
| +// /size sets host's slice to a size's CPU and IO shares and reads the |
| +// slice back; it never changes memory. It is separate from GenControl, as |
| // StagedExeControl is, so a channel without it (a fake, an older client) |
| // still satisfies GenControl, and no call through genControl() can reach a |
| // size verb (Astra plan R8-2). |
| type SizeControl interface { |
| - Size(ctx context.Context, host string, gen uint64, size string, memoryMax int64) (instancectl.SizeReadBack, error) |
| - ReadSize(ctx context.Context, host string, gen uint64) (instancectl.SizeReadBack, error) |
| + Size(ctx context.Context, host, size string) (instancectl.SizeReadBack, error) |
| } |
| var _ SizeControl = (*instancectl.Client)(nil) |
diff --git a/internal/activator/genbackend.go b/internal/activator/genbackend.go| index 29bf2134b..176ab7442 100644 |
| --- a/internal/activator/genbackend.go |
| +++ b/internal/activator/genbackend.go |
| @@ -375,20 +375,12 @@ func (b *SplitBackend) sizeExec(rt registry.Route) (SizeBackend, error) { |
| return sb, nil |
| } |
| -func (b *SplitBackend) ResizeLive(ctx context.Context, rt registry.Route, gen uint64, size cgroup.Size, memoryMax int64) (instancectl.SizeReadBack, error) { |
| +func (b *SplitBackend) ResizeLive(ctx context.Context, rt registry.Route, size cgroup.Size) (instancectl.SizeReadBack, error) { |
| sb, err := b.sizeExec(rt) |
| if err != nil { |
| return instancectl.SizeReadBack{}, err |
| } |
| - return sb.ResizeLive(ctx, rt, gen, size, memoryMax) |
| -} |
| - |
| -func (b *SplitBackend) ReadSize(ctx context.Context, rt registry.Route, gen uint64) (instancectl.SizeReadBack, error) { |
| - sb, err := b.sizeExec(rt) |
| - if err != nil { |
| - return instancectl.SizeReadBack{}, err |
| - } |
| - return sb.ReadSize(ctx, rt, gen) |
| + return sb.ResizeLive(ctx, rt, size) |
| } |
| func (b *SplitBackend) GenReady(rt registry.Route, g Gen, p Proc) { |
diff --git a/internal/activator/opset.go b/internal/activator/opset.go| index 1cc2442ea..7e1ac5f96 100644 |
| --- a/internal/activator/opset.go |
| +++ b/internal/activator/opset.go |
| @@ -81,21 +81,18 @@ type straySidecar struct { |
| // (final review R2-2). |
| // |
| // resizing marks a live size change in flight (#329, retrySizeLocked), and |
| -// resizeDone closes when it has finished. It writes the host's slice, which |
| -// a later instance of the host would share, so it is joined like a |
| -// restore: the barrier waits for it, and a pending stop keeps the lease |
| -// until it returns. sizeUnsettled records that a live write may have left |
| -// the slice and the serving unit at different memory limits (a write that |
| -// failed partway, or a read-back that disagreed): no swap is admitted until |
| -// a write settles it. |
| +// resizeDone closes when it has finished. It writes the host's slice (CPU |
| +// and IO only, spec §5.4 rev 10), which a later instance of the host would |
| +// share, so it is joined like a restore: the barrier waits for it, a |
| +// pending stop keeps the lease until it returns, and no swap is admitted |
| +// while it runs. |
| type opSet struct { |
| - members map[uint64]*genMember |
| - raised bool |
| - restoring bool |
| - restoreDone chan struct{} |
| - resizing bool |
| - resizeDone chan struct{} |
| - sizeUnsettled bool |
| + members map[uint64]*genMember |
| + raised bool |
| + restoring bool |
| + restoreDone chan struct{} |
| + resizing bool |
| + resizeDone chan struct{} |
| } |
| // opJoinBound bounds the barrier's wait. A member's owner needs at most a |
diff --git a/internal/activator/size.go b/internal/activator/size.go| index 84efdc927..f56a0d208 100644 |
| --- a/internal/activator/size.go |
| +++ b/internal/activator/size.go |
| @@ -51,13 +51,13 @@ func EffectiveSize(gb interface { |
| } |
| // SizeBackend is the optional Backend capability behind a live size change |
| -// (#329, spec §5.4): root's /size verbs for a nested host. ResizeLive sizes |
| -// rt's slice and, with gen, that generation's unit; ReadSize reads both |
| -// back and writes nothing. A host with no live change (another layout, a |
| -// channel without the verbs, a unit-backed row) answers errSizeNotLive. |
| +// (#329, spec §5.4 rev 10): root's /size verb for a nested host. |
| +// ResizeLive sets rt's slice to size's CPU and IO shares and answers the |
| +// slice's read-back; memory never changes while the instance runs. A host |
| +// with no live change (another layout, a channel without the verb, a |
| +// unit-backed row) answers errSizeNotLive. |
| type SizeBackend interface { |
| - ResizeLive(ctx context.Context, rt registry.Route, gen uint64, size cgroup.Size, memoryMax int64) (instancectl.SizeReadBack, error) |
| - ReadSize(ctx context.Context, rt registry.Route, gen uint64) (instancectl.SizeReadBack, error) |
| + ResizeLive(ctx context.Context, rt registry.Route, size cgroup.Size) (instancectl.SizeReadBack, error) |
| } |
| var ( |
| @@ -95,12 +95,12 @@ func (a *Service) tierSource() genTierer { |
| return sizedDefault{} |
| } |
| -// genUnitOf is the generation unit a live size change names for g: g.N |
| -// when the entry runs in a generation unit of its own (not a worker, and |
| -// the generation bound a socket of its own, so startRole started it through |
| -// GenControl), else 0. A canonical handle is numbered with generations off |
| -// too, but no unit has that number, and root would refuse it (Astra plan |
| -// R1-8). 0 is root's run-template path: the slice alone. |
| +// genUnitOf is the generation unit g serves from: g.N when the entry runs |
| +// in a generation unit of its own (not a worker, and the generation bound |
| +// a socket of its own, so startRole started it through GenControl), else 0, |
| +// the run template's slice alone. A canonical handle is numbered with |
| +// generations off too, but no unit has that number (Astra plan R1-8). The |
| +// agent's status reads the memory in force from that unit's cgroup. |
| func genUnitOf(rt registry.Route, g Gen) uint64 { |
| if !g.Worker && linksCanonical(rt, g) { |
| return g.N |
| @@ -108,15 +108,15 @@ func genUnitOf(rt registry.Route, g Gen) uint64 { |
| return 0 |
| } |
| -// SizeState is an awake instance's live size (#329): Gen is the generation |
| -// unit a change names (0: the slice alone), Raised that a swap holds the |
| -// parent, Unsettled that a live write may have left the slice and the unit |
| -// apart, and Want the size its route and build run at now. |
| +// SizeState is an awake instance's size (#329): Gen is the generation unit |
| +// it serves from (0: the slice alone), Raised that a swap holds the parent, |
| +// and Want the size its route and build run at now. Memory reaches Want at |
| +// the next start or swap (spec §5.4 rev 10); until then the status shows |
| +// the change pending. |
| type SizeState struct { |
| - Gen uint64 |
| - Raised bool |
| - Unsettled bool |
| - Want cgroup.Size |
| + Gen uint64 |
| + Raised bool |
| + Want cgroup.Size |
| } |
| // SizeState answers for an awake instance that is not a worker. |
| @@ -127,7 +127,7 @@ func (a *Service) SizeState(host string) (SizeState, bool) { |
| a.mu.Unlock() |
| return SizeState{}, false |
| } |
| - st := SizeState{Gen: genUnitOf(e.route, e.gen), Raised: e.ops.raised, Unsettled: e.ops.sizeUnsettled} |
| + st := SizeState{Gen: genUnitOf(e.route, e.gen), Raised: e.ops.raised} |
| rt, build := e.route, e.gen.Build |
| a.mu.Unlock() |
| st.Want = EffectiveSize(a.tierSource(), rt, build) |
| @@ -157,22 +157,22 @@ func (a *Service) sizeEligibleLocked(e *actEntry) bool { |
| // sizeSnap is what a size pass took from its entry under a.mu. |
| type sizeSnap struct { |
| - sb SizeBackend |
| - gt genTierer |
| - rt registry.Route |
| - g Gen |
| - seen string |
| - dirty bool |
| - unsettled bool |
| + sb SizeBackend |
| + gt genTierer |
| + rt registry.Route |
| + g Gen |
| + seen string |
| + dirty bool |
| + owed bool |
| } |
| // retrySizeLocked starts a live size pass for e when one is due (#329, |
| -// spec §5.4): NoteSize marked the column moved, a previous write left the |
| -// host unsettled, or the slow backstop compare is due. Otherwise it does |
| -// nothing at all. The pass first compares the column off a.mu, holding |
| -// nothing back (preflight C6), and only a change takes the resizing mark, |
| -// after the eligibility checks again. The caller holds a.mu; called from |
| -// the sweep (finishPendingStops), patterned on retryParentRestoreLocked. |
| +// spec §5.4): NoteSize marked the column moved, a previous CPU and IO write |
| +// is owed, or the slow backstop compare is due. Otherwise it does nothing |
| +// at all. The pass first compares the column off a.mu, holding nothing |
| +// back (preflight C6), and only a change takes the resizing mark, after |
| +// the eligibility checks again. The caller holds a.mu; called from the |
| +// sweep (finishPendingStops), patterned on retryParentRestoreLocked. |
| func (a *Service) retrySizeLocked(e *actEntry) { |
| if e.sizeChecking || !a.sizeEligibleLocked(e) { |
| return |
| @@ -186,13 +186,13 @@ func (a *Service) retrySizeLocked(e *actEntry) { |
| // The wake's fresh row: the size the entry was started at. |
| e.sizeSeen, e.sizeSeenSet, e.sizeCheckedAt = e.route.Size, true, now |
| } |
| - dirty, unsettled := e.sizeDirty, e.ops.sizeUnsettled |
| - if !dirty && !unsettled && now.Sub(e.sizeCheckedAt) < sizeBackstop { |
| + dirty, owed := e.sizeDirty, e.sizeOwed |
| + if !dirty && !owed && now.Sub(e.sizeCheckedAt) < sizeBackstop { |
| return |
| } |
| e.sizeChecking, e.sizeDirty, e.sizeCheckedAt = true, false, now |
| go a.sizePass(e, sizeSnap{sb: sb, gt: a.tierSource(), rt: e.route, g: e.gen, |
| - seen: e.sizeSeen, dirty: dirty, unsettled: unsettled}) |
| + seen: e.sizeSeen, dirty: dirty, owed: owed}) |
| } |
| // endSizeCheck ends a pass that wrote nothing. redo keeps the change marked |
| @@ -210,16 +210,14 @@ func (a *Service) endSizeCheck(e *actEntry, redo bool) { |
| // entry; every entry field is read and written under a.mu. |
| // |
| // With no operator change (the column is what the entry last acted on) and |
| -// nothing unsettled it ends after the registry read, with no root call. |
| -// Otherwise it reads what the slice and the serving unit hold, and writes |
| -// the size with memory never below anything observed (R1-3, Astra plan |
| -// R1-9): a shrink sends CPU and IO only, and a unit lagging the slice is |
| -// brought up to it. The captured tier comes from the read-back, never from |
| -// the request (R2-1). A refusal (root under host claims, a host with no |
| -// live change) writes nothing: the size is recorded on the route, and the |
| -// next start, an overlap successor's included, sizes from it (Astra plan |
| -// R6-1). Any other failure of the write marks the host unsettled, and no |
| -// swap is admitted until a write settles it. |
| +// no write owed it ends after the registry read, with no root call. |
| +// Otherwise it sends the effective size once: root sets the slice's CPU |
| +// and IO shares and never memory (spec §5.4 rev 10). It is applied when |
| +// the read-back shows the size's shares; anything else leaves the write |
| +// owed, and the next sweep sends it again. A refusal (root under host |
| +// claims, a host with no live change) is not retried. In both cases the |
| +// size is recorded on the route, and the next start, an overlap |
| +// successor's included, sizes its memory from it (Astra plan R6-1). |
| func (a *Service) sizePass(e *actEntry, s sizeSnap) { |
| host := s.rt.Host |
| fresh := s.rt |
| @@ -239,7 +237,7 @@ func (a *Service) sizePass(e *actEntry, s sizeSnap) { |
| } |
| fresh = *r |
| } |
| - if !s.unsettled && fresh.Size == s.seen { |
| + if !s.owed && fresh.Size == s.seen { |
| a.endSizeCheck(e, false) |
| return |
| } |
| @@ -257,67 +255,32 @@ func (a *Service) sizePass(e *actEntry, s sizeSnap) { |
| e.ops.resizing, e.ops.resizeDone = true, done |
| a.mu.Unlock() |
| - unit := genUnitOf(s.rt, s.g) |
| want := EffectiveSize(s.gt, fresh, s.g.Build) |
| - wrote := false |
| ctx, cancel := context.WithTimeout(context.Background(), instancectl.DeadlineControl) |
| - rb, err := s.sb.ReadSize(ctx, fresh, unit) |
| + rb, err := s.sb.ResizeLive(ctx, fresh, want) |
| cancel() |
| - if err == nil { |
| - observed := cgroup.Limit{MemoryMax: rb.SliceMemoryMax} |
| - if unit > 0 { |
| - observed = cgroup.MaxLimit(observed, cgroup.Limit{MemoryMax: rb.UnitMemoryMax}) |
| - } |
| - mem := cgroup.MaxLimit(want.Limit, observed) |
| - ctx, cancel := context.WithTimeout(context.Background(), instancectl.DeadlineControl) |
| - rb, err = s.sb.ResizeLive(ctx, fresh, unit, want, mem.MemoryMax) |
| - cancel() |
| - wrote = true |
| - } |
| refused := errors.Is(err, instancectl.ErrSizeRefused) || errors.Is(err, errSizeNotLive) |
| + sh := want.Shares |
| + applied := err == nil && rb.CPUQuotaPercent == sh.CPUQuotaPercent && rb.CPUWeight == sh.CPUWeight && rb.IOWeight == sh.IOWeight |
| a.mu.Lock() |
| - switch { |
| - case err == nil: |
| - // Settled only when the read-back shows the slice and the serving |
| - // unit at one memory limit. |
| - if rb.SliceMemoryMax > 0 && (unit == 0 || rb.UnitMemoryMax == rb.SliceMemoryMax) { |
| - e.ops.sizeUnsettled = false |
| - if e.gen.N == s.g.N { |
| - e.gen.Tier = cgroup.Limit{MemoryMax: rb.SliceMemoryMax} |
| - } |
| - } else { |
| - e.ops.sizeUnsettled = true |
| - } |
| - e.sizeSeen, e.route.Size = fresh.Size, fresh.Size |
| - case refused: |
| - // Nothing written: the next start sizes from the column. The |
| - // captured tier and the unsettled mark are unchanged, since a |
| - // refusal proves nothing about the limits already on the host. |
| - e.sizeSeen, e.route.Size = fresh.Size, fresh.Size |
| - case !wrote: |
| - // The read failed: nothing was written, so nothing is unsettled, |
| - // and the change is retried next sweep. |
| - e.sizeDirty = true |
| - default: |
| - // The write failed partway or not at all: the slice may be written. |
| - e.ops.sizeUnsettled = true |
| + if applied || refused { |
| + e.sizeSeen, e.route.Size, e.sizeOwed = fresh.Size, fresh.Size, false |
| + } else { |
| + e.sizeOwed = true |
| } |
| - unsettled := e.ops.sizeUnsettled |
| e.ops.resizing, e.ops.resizeDone, e.sizeChecking = false, nil, false |
| a.mu.Unlock() |
| close(done) |
| switch { |
| - case err == nil && unsettled: |
| - log.Printf("activator: %s: size %s: the slice holds %d and generation %d holds %d; retried until they agree", host, want.Name, rb.SliceMemoryMax, unit, rb.UnitMemoryMax) |
| - case err == nil: |
| - log.Printf("activator: %s: size %s applied live (memory.max=%d, gen %d)", host, want.Name, rb.SliceMemoryMax, unit) |
| + case applied: |
| + log.Printf("activator: %s: size %s: cpu and io applied live; memory changes at the next start", host, want.Name) |
| case refused: |
| log.Printf("activator: %s: size %s not applied live: %v; it takes effect at the next start", host, want.Name, err) |
| - case !wrote: |
| - log.Printf("activator: %s: size check: read: %v (retried next sweep)", host, err) |
| + case err == nil: |
| + log.Printf("activator: %s: size %s: the slice reads back cpu quota %d%%, cpu weight %d, io weight %d (retried next sweep)", host, want.Name, rb.CPUQuotaPercent, rb.CPUWeight, rb.IOWeight) |
| default: |
| - log.Printf("activator: %s: size %s: %v (no swap until a write settles it)", host, want.Name, err) |
| + log.Printf("activator: %s: size %s: %v (retried next sweep)", host, want.Name, err) |
| } |
| } |
diff --git a/internal/activator/size_live_test.go b/internal/activator/size_live_test.go| index f92e265e5..e5f3eafca 100644 |
| --- a/internal/activator/size_live_test.go |
| +++ b/internal/activator/size_live_test.go |
| @@ -94,7 +94,7 @@ func (r *liveRoutes) arm() (gate, entered chan struct{}) { |
| // sizeFixture is the swap fixture with a size column: the entry's route |
| // carries size, the incumbent runs at tier (captured), and the fake slice |
| -// and unit hold tier. The local registry (a.Routes) holds the same row. |
| +// holds tier. The local registry (a.Routes) holds the same row. |
| type sizeFixture struct { |
| *swapFixture |
| routes *liveRoutes |
| @@ -112,7 +112,7 @@ func newSizeFixture(t *testing.T, size string, tier int64) *sizeFixture { |
| routes := &liveRoutes{rows: map[string]registry.Route{f.host: rt}} |
| f.a.Routes = routes |
| f.b.gmu.Lock() |
| - f.b.sliceMem, f.b.unitMem = tier, tier |
| + f.b.sliceMem = tier |
| f.b.gmu.Unlock() |
| return &sizeFixture{swapFixture: f, routes: routes} |
| } |
| @@ -151,7 +151,7 @@ func (f *sizeFixture) state(t *testing.T) SizeState { |
| func sizeEvents(ev []string) []string { |
| var out []string |
| for _, e := range ev { |
| - if strings.HasPrefix(e, "readsize:") || strings.HasPrefix(e, "size:") { |
| + if strings.HasPrefix(e, "size:") { |
| out = append(out, e) |
| } |
| } |
| @@ -172,16 +172,13 @@ func (a *Service) resizingForTest(host string) bool { |
| return e != nil && e.ops.resizing |
| } |
| -func readSizeEv(n uint64) string { return fmt.Sprintf("readsize:%d", n) } |
| -func sizeEv(name string, mem int64, n uint64) string { |
| - return fmt.Sprintf("size:%s/%d/%d", name, mem, n) |
| -} |
| +func sizeEv(name string) string { return "size:" + name } |
| func refusedByRoot(code int) error { |
| return fmt.Errorf("%w: instance control /size: %d: refused", instancectl.ErrSizeRefused, code) |
| } |
| -var errSize502 = errors.New("instance control /size: 502: set-property carlos-instance-gen@swap.example.com:1.service: failed") |
| +var errSize502 = errors.New("instance control /size: 502: set-property carlos-instances-swap.example.com.slice: failed") |
| func swapBusy(t *testing.T, f *sizeFixture) { |
| t.Helper() |
| @@ -191,83 +188,54 @@ func swapBusy(t *testing.T, f *sizeFixture) { |
| } |
| } |
| -// An operator growth writes the slice and the serving unit, after reading |
| -// what they hold, and the captured tier comes from the read-back. |
| -func TestLiveGrowthWritesSliceAndUnitAndCapturesTheReadBack(t *testing.T) { |
| - t.Parallel() |
| - f := newSizeFixture(t, "", half) |
| - n := f.incumbent.N |
| - f.operatorSets("large") |
| - f.sweep(t) |
| - if got, want := f.sizeEvents(), []string{readSizeEv(n), sizeEv("large", gib, n)}; !slices.Equal(got, want) { |
| - t.Fatalf("size calls %v, want %v", got, want) |
| - } |
| - if got := f.tier(); got != cgroup.TierChildren.MemoryMax { |
| - t.Fatalf("captured tier %d, want %d", got, cgroup.TierChildren.MemoryMax) |
| - } |
| - if st := f.state(t); st.Unsettled || st.Raised || st.Gen != n || st.Want.Name != "large" { |
| - t.Fatalf("SizeState = %+v", st) |
| - } |
| -} |
| - |
| -// The captured tier is root's read-back, never the request: a read-back |
| -// that settles (slice and unit at one value) at a figure other than the one |
| -// asked for is what the entry records. |
| -func TestLiveGrowthCapturesTheReadBackNotTheRequest(t *testing.T) { |
| +// Ruling 12 (spec §5.4 rev 10): an operator change sends the size once, |
| +// which root applies as CPU and IO only. The captured tier (the memory the |
| +// serving generation started at) never moves; the memory lands at the |
| +// next swap, whose successor starts at the larger of the new size and the |
| +// incumbent's (Task 4), or at a cold start for a shrink. |
| +func TestLiveSizeChangeSendsCPUAndIOOnly(t *testing.T) { |
| t.Parallel() |
| - const held = int64(1610612736) // 1.5 GiB: what the slice and unit hold after the write |
| - f := newSizeFixture(t, "", half) |
| - n := f.incumbent.N |
| - f.b.setSizeHooks(nil, func(_ uint64, _ cgroup.Size, _ int64) (instancectl.SizeReadBack, error) { |
| - return instancectl.SizeReadBack{SliceMemoryMax: held, UnitMemoryMax: held}, nil |
| - }) |
| - f.operatorSets("large") |
| - f.sweep(t) |
| - if got, want := f.sizeEvents(), []string{readSizeEv(n), sizeEv("large", gib, n)}; !slices.Equal(got, want) { |
| - t.Fatalf("size calls %v, want %v", got, want) |
| - } |
| - if g, ok := f.a.Current(f.host); !ok || g.Tier.MemoryMax != held { |
| - t.Fatalf("Current = %+v, %v; want Tier %d from the read-back, not the requested %d", g, ok, held, gib) |
| - } |
| - if st := f.state(t); st.Unsettled { |
| - t.Fatalf("SizeState = %+v, want settled", st) |
| - } |
| -} |
| - |
| -// Astra plan R1-8: with generations off the handle is numbered but no unit |
| -// has that number, so the pass sizes the run template's slice (gen 0). |
| -func TestLiveGrowthWithGenerationsOffUsesTheRunTemplate(t *testing.T) { |
| - t.Parallel() |
| - f := newSizeFixture(t, "", half) |
| - f.a.gens = false |
| - f.a.mu.Lock() |
| - rt := f.a.entries[f.host].route |
| - f.a.mu.Unlock() |
| - g := canonicalGen(rt, 7, "v1") |
| - g.Tier = cgroup.Limit{MemoryMax: half} |
| - setCurrentGen(t, f.a, f.host, g) |
| - f.b.setSizeHooks(func(gen uint64) (instancectl.SizeReadBack, error) { |
| - if gen != 0 { |
| - return instancectl.SizeReadBack{}, refusedByRoot(409) |
| - } |
| - return instancectl.SizeReadBack{SliceMemoryMax: half}, nil |
| - }, func(gen uint64, _ cgroup.Size, mem int64) (instancectl.SizeReadBack, error) { |
| - if gen != 0 { |
| - return instancectl.SizeReadBack{}, refusedByRoot(409) |
| - } |
| - return instancectl.SizeReadBack{SliceMemoryMax: mem}, nil |
| - }) |
| - f.operatorSets("large") |
| - f.sweep(t) |
| - if got, want := f.sizeEvents(), []string{readSizeEv(0), sizeEv("large", gib, 0)}; !slices.Equal(got, want) { |
| - t.Fatalf("size calls %v, want %v", got, want) |
| - } |
| - st := f.state(t) |
| - if st.Gen != 0 || st.Unsettled || st.Want.Name != "large" { |
| - t.Fatalf("SizeState = %+v", st) |
| - } |
| - if got := f.tier(); got != gib { |
| - t.Fatalf("captured tier %d, want %d (no pending mark)", got, gib) |
| + for _, tc := range []struct { |
| + name string |
| + from, to string |
| + tier int64 |
| + raise string |
| + successor int64 |
| + wantSwapAt int64 |
| + }{ |
| + {"growth", "", "xlarge", half, fmt.Sprintf("raise:%d+%d", half, two), two, two}, |
| + {"shrink", "large", "small", gib, fmt.Sprintf("raise:%d+%d", gib, gib), gib, gib}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + t.Parallel() |
| + f := newSizeFixture(t, tc.from, tc.tier) |
| + n := f.incumbent.N |
| + f.operatorSets(tc.to) |
| + f.sweep(t) |
| + if got, want := f.sizeEvents(), []string{sizeEv(tc.to)}; !slices.Equal(got, want) { |
| + t.Fatalf("size calls %v, want %v", got, want) |
| + } |
| + if got := f.tier(); got != tc.tier { |
| + t.Fatalf("captured tier %d, want %d: memory never changes live", got, tc.tier) |
| + } |
| + if st := f.state(t); st.Raised || st.Gen != n || st.Want.Name != tc.to { |
| + t.Fatalf("SizeState = %+v, want %s pending on gen %d", st, tc.to, n) |
| + } |
| + // Applied: further sweeps and the backstop send nothing more. |
| + f.sweep(t) |
| + f.clk.advance(sizeBackstop) |
| + f.sweep(t) |
| + if got := f.sizeEvents(); len(got) != 1 { |
| + t.Fatalf("size calls %v after the change was applied, want one", got) |
| + } |
| + res := f.a.Swap(context.Background(), f.attempt(ModeOverlap), f.newest) |
| + if res.Outcome != SwapDone || res.Gen.Tier.MemoryMax != tc.wantSwapAt { |
| + t.Fatalf("Swap = %+v, want done at %d", res, tc.wantSwapAt) |
| + } |
| + if ev := f.b.events(); indexPrefix(ev, tc.raise) < 0 { |
| + t.Fatalf("events %v: want %s", ev, tc.raise) |
| + } |
| + }) |
| } |
| } |
| @@ -313,27 +281,27 @@ func TestLiveChangeWaitsForTheSwapToRestore(t *testing.T) { |
| if len(sizes) != 1 || restore < 0 || sizes[0] < restore { |
| t.Fatalf("events %v: want exactly one size call, after the parent restore", ev) |
| } |
| - succ, _ := f.a.genStateForTest(f.host) |
| - if want := sizeEv("large", gib, succ.N); ev[sizes[0]] != want { |
| + if want := sizeEv("large"); ev[sizes[0]] != want { |
| t.Fatalf("size call %q, want %q", ev[sizes[0]], want) |
| } |
| } |
| -// Astra plan R6-1: a refused live change still records the size on the |
| -// entry's route, so the next start, an overlap successor included, sizes |
| -// from it. |
| +// Astra plan R6-1: a refused live change is not retried, and still records |
| +// the size on the entry's route, so the next start, an overlap successor |
| +// included, sizes from it. |
| func TestARefusedLiveResizeStillReachesTheNextSwap(t *testing.T) { |
| t.Parallel() |
| f := newSizeFixture(t, "standard", half) |
| - f.b.setSizeHooks(func(uint64) (instancectl.SizeReadBack, error) { |
| + f.b.setSizeHook(func(cgroup.Size) (instancectl.SizeReadBack, error) { |
| return instancectl.SizeReadBack{}, fmt.Errorf("flat row: %w", errSizeNotLive) |
| - }, nil) |
| + }) |
| f.operatorSets("xlarge") |
| f.sweep(t) |
| - if got, want := f.sizeEvents(), []string{readSizeEv(f.incumbent.N)}; !slices.Equal(got, want) { |
| + f.sweep(t) |
| + if got, want := f.sizeEvents(), []string{sizeEv("xlarge")}; !slices.Equal(got, want) { |
| t.Fatalf("size calls %v, want %v", got, want) |
| } |
| - if st := f.state(t); st.Unsettled || st.Want.Name != "xlarge" { |
| + if st := f.state(t); st.Want.Name != "xlarge" { |
| t.Fatalf("SizeState = %+v", st) |
| } |
| res := f.a.Swap(context.Background(), f.attempt(ModeOverlap), f.newest) |
| @@ -345,159 +313,108 @@ func TestARefusedLiveResizeStillReachesTheNextSwap(t *testing.T) { |
| } |
| } |
| -// A resize in flight, and then a write that did not settle, keep every |
| -// swap out until a write's read-back shows slice and unit at one value. |
| -func TestSwapRefusedWhileResizingOrUnsettled(t *testing.T) { |
| +// Swap admission refuses only while a /size call is in flight: the call |
| +// and the swap both write the host's slice. |
| +func TestSwapRefusedOnlyWhileResizing(t *testing.T) { |
| t.Parallel() |
| f := newSizeFixture(t, "", half) |
| - n := f.incumbent.N |
| entered, gate := make(chan struct{}, 1), make(chan struct{}) |
| - var failing atomic.Bool |
| - failing.Store(true) |
| - f.b.setSizeHooks(nil, func(_ uint64, _ cgroup.Size, mem int64) (instancectl.SizeReadBack, error) { |
| + f.b.setSizeHook(func(size cgroup.Size) (instancectl.SizeReadBack, error) { |
| select { |
| case entered <- struct{}{}: |
| default: |
| } |
| <-gate |
| - if failing.Load() { |
| - return instancectl.SizeReadBack{}, errSize502 |
| - } |
| - return instancectl.SizeReadBack{SliceMemoryMax: mem, UnitMemoryMax: mem}, nil |
| + return sizeApplied(size, half), nil |
| }) |
| f.operatorSets("large") |
| f.a.sweepOnce() |
| <-entered |
| - swapBusy(t, f) // resizing |
| + swapBusy(t, f) |
| close(gate) |
| waitFor(t, "the size pass to finish", func() bool { return f.a.sizeIdleForTest(f.host) }) |
| - if st := f.state(t); !st.Unsettled { |
| - t.Fatalf("SizeState = %+v after a 502, want unsettled", st) |
| - } |
| - swapBusy(t, f) // unsettled |
| - |
| - failing.Store(false) |
| - f.sweep(t) // no operator change: the unsettled mark alone retries |
| - want := []string{readSizeEv(n), sizeEv("large", gib, n), readSizeEv(n), sizeEv("large", gib, n)} |
| - if got := f.sizeEvents(); !slices.Equal(got, want) { |
| - t.Fatalf("size calls %v, want %v", got, want) |
| - } |
| - if st := f.state(t); st.Unsettled { |
| - t.Fatalf("SizeState = %+v, want settled", st) |
| - } |
| - if got := f.tier(); got != gib { |
| - t.Fatalf("captured tier %d, want %d from the read-back", got, gib) |
| - } |
| if res := f.a.Swap(context.Background(), f.attempt(ModeOverlap), f.newest); res.Outcome != SwapDone { |
| - t.Fatalf("Swap = %+v once settled", res) |
| + t.Fatalf("Swap = %+v once the call returned", res) |
| } |
| } |
| -// Astra plan R1-9: a policy reversed after a partial growth brings the |
| -// unit up to the slice rather than asking for a shrink, and only a write |
| -// that settles clears the mark. |
| -func TestPolicyReversalAfterAPartialGrowthStaysUnsettled(t *testing.T) { |
| +// A failed call, or one whose read-back does not show the size's shares, |
| +// is owed: the next sweep sends it again with no operator change, and no |
| +// swap is held back meanwhile. Once applied, nothing more is sent. |
| +func TestAFailedLiveSizeRetriesNextSweep(t *testing.T) { |
| t.Parallel() |
| - for _, refuse := range []bool{false, true} { |
| - t.Run(fmt.Sprintf("refused=%v", refuse), func(t *testing.T) { |
| + for _, tc := range []struct { |
| + name string |
| + fail func(cgroup.Size) (instancectl.SizeReadBack, error) |
| + }{ |
| + {"502", func(cgroup.Size) (instancectl.SizeReadBack, error) { return instancectl.SizeReadBack{}, errSize502 }}, |
| + {"read-back disagrees", func(cgroup.Size) (instancectl.SizeReadBack, error) { |
| + return instancectl.SizeReadBack{SliceMemoryMax: half, CPUQuotaPercent: 100, CPUWeight: 100, IOWeight: 100}, nil |
| + }}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| t.Parallel() |
| f := newSizeFixture(t, "", half) |
| - n := f.incumbent.N |
| - var mu sync.Mutex |
| - slice, unit, failNext := half, half, true |
| - f.b.setSizeHooks(func(uint64) (instancectl.SizeReadBack, error) { |
| - mu.Lock() |
| - defer mu.Unlock() |
| - return instancectl.SizeReadBack{SliceMemoryMax: slice, UnitMemoryMax: unit}, nil |
| - }, func(_ uint64, _ cgroup.Size, mem int64) (instancectl.SizeReadBack, error) { |
| - mu.Lock() |
| - defer mu.Unlock() |
| - if failNext { |
| - // The slice was written; the unit's write failed. |
| - failNext, slice = false, mem |
| - return instancectl.SizeReadBack{}, errSize502 |
| - } |
| - if refuse { |
| - return instancectl.SizeReadBack{}, refusedByRoot(409) |
| + var failing atomic.Bool |
| + failing.Store(true) |
| + f.b.setSizeHook(func(size cgroup.Size) (instancectl.SizeReadBack, error) { |
| + if failing.Load() { |
| + return tc.fail(size) |
| } |
| - slice, unit = mem, mem |
| - return instancectl.SizeReadBack{SliceMemoryMax: slice, UnitMemoryMax: unit}, nil |
| + return sizeApplied(size, half), nil |
| }) |
| f.operatorSets("xlarge") |
| f.sweep(t) |
| - if st := f.state(t); !st.Unsettled { |
| - t.Fatalf("SizeState = %+v after a partial growth, want unsettled", st) |
| + if res := f.a.Swap(context.Background(), f.attempt(ModeOverlap), f.newest); res.Outcome != SwapDone { |
| + t.Fatalf("Swap = %+v after a failed call, want done: only a call in flight holds a swap", res) |
| } |
| - f.operatorSets("standard") |
| + f.sweep(t) // still failing: owed again |
| + failing.Store(false) |
| + f.sweep(t) // applied |
| f.sweep(t) |
| - want := []string{readSizeEv(n), sizeEv("xlarge", two, n), readSizeEv(n), sizeEv("standard", two, n)} |
| + want := []string{sizeEv("xlarge"), sizeEv("xlarge"), sizeEv("xlarge")} |
| if got := f.sizeEvents(); !slices.Equal(got, want) { |
| t.Fatalf("size calls %v, want %v", got, want) |
| } |
| - if refuse { |
| - if st := f.state(t); !st.Unsettled { |
| - t.Fatalf("SizeState = %+v, a refusal must not settle", st) |
| - } |
| - if got := f.tier(); got != half { |
| - t.Fatalf("captured tier %d after a refusal, want %d unchanged", got, half) |
| - } |
| - swapBusy(t, f) |
| - return |
| - } |
| - if st := f.state(t); st.Unsettled || st.Want.Name != "standard" { |
| - t.Fatalf("SizeState = %+v, want settled at standard", st) |
| - } |
| - if got := f.tier(); got != two { |
| - t.Fatalf("captured tier %d, want %d", got, two) |
| - } |
| - res := f.a.Swap(context.Background(), f.attempt(ModeOverlap), f.newest) |
| - if res.Outcome != SwapDone || res.Gen.Tier.MemoryMax != two { |
| - t.Fatalf("Swap = %+v, want done at %d", res, two) |
| - } |
| - ev := f.b.events() |
| - if indexPrefix(ev, fmt.Sprintf("raise:%d+%d", two, two)) < 0 { |
| - t.Fatalf("events %v: want the raise from 2 GiB", ev) |
| - } |
| - for _, e := range ev { |
| - if strings.HasPrefix(e, "restore:") && e != fmt.Sprintf("restore:%d", two) { |
| - t.Fatalf("events %v: a restore below the slice", ev) |
| - } |
| - } |
| }) |
| } |
| } |
| -// A memory shrink sends CPU and IO only: memory is held where it is, and |
| -// the size stays pending until a cold start. |
| -func TestMemoryShrinkSendsOnlyCPUAndIOAndStaysPending(t *testing.T) { |
| +// An owed write is sent even when the column has gone back to the size |
| +// last applied: the failed call may have left the slice elsewhere, so the |
| +// size in force now is sent once more. |
| +func TestAnOwedLiveSizeIsSentAfterTheColumnReturns(t *testing.T) { |
| t.Parallel() |
| - f := newSizeFixture(t, "large", gib) |
| - n := f.incumbent.N |
| - f.operatorSets("small") |
| + f := newSizeFixture(t, "", half) |
| + var failing atomic.Bool |
| + failing.Store(true) |
| + f.b.setSizeHook(func(size cgroup.Size) (instancectl.SizeReadBack, error) { |
| + if failing.Load() { |
| + return instancectl.SizeReadBack{}, errSize502 |
| + } |
| + return sizeApplied(size, half), nil |
| + }) |
| + f.operatorSets("xlarge") |
| + f.sweep(t) |
| + failing.Store(false) |
| + f.operatorSets("") // back to the build's tier, the column the entry started on |
| f.sweep(t) |
| - if got, want := f.sizeEvents(), []string{readSizeEv(n), sizeEv("small", gib, n)}; !slices.Equal(got, want) { |
| + f.sweep(t) |
| + if got, want := f.sizeEvents(), []string{sizeEv("xlarge"), sizeEv("standard")}; !slices.Equal(got, want) { |
| t.Fatalf("size calls %v, want %v", got, want) |
| } |
| - if st := f.state(t); st.Want.Name != "small" || st.Unsettled { |
| - t.Fatalf("SizeState = %+v, want small", st) |
| - } |
| - if got := f.tier(); got != gib { |
| - t.Fatalf("captured tier %d, want %d held", got, gib) |
| - } |
| } |
| // Back to the size in force: nothing is pending any more. |
| func TestSizeBackToTheOneInForceClearsPending(t *testing.T) { |
| t.Parallel() |
| f := newSizeFixture(t, "large", gib) |
| - n := f.incumbent.N |
| f.operatorSets("small") |
| f.sweep(t) |
| f.operatorSets("large") |
| f.sweep(t) |
| - ev := f.sizeEvents() |
| - if len(ev) != 4 || ev[3] != sizeEv("large", gib, n) { |
| - t.Fatalf("size calls %v, want the last %s", ev, sizeEv("large", gib, n)) |
| + if got, want := f.sizeEvents(), []string{sizeEv("small"), sizeEv("large")}; !slices.Equal(got, want) { |
| + t.Fatalf("size calls %v, want %v", got, want) |
| } |
| st := f.state(t) |
| if s, _ := cgroup.SizeOf(cgroup.Limit{MemoryMax: f.tier()}); st.Want.Name != "large" || s.Name != st.Want.Name { |
| @@ -554,7 +471,6 @@ func TestASizeCheckWithNoChangeHoldsNothing(t *testing.T) { |
| func TestTheBackstopCatchesAMissedNoteSize(t *testing.T) { |
| t.Parallel() |
| f := newSizeFixture(t, "", half) |
| - n := f.incumbent.N |
| f.sweep(t) |
| f.routes.setSize(f.host, "large") // no NoteSize |
| before := f.routes.count() |
| @@ -567,7 +483,7 @@ func TestTheBackstopCatchesAMissedNoteSize(t *testing.T) { |
| } |
| f.clk.advance(sizeBackstop) |
| f.sweep(t) |
| - if got, want := f.sizeEvents(), []string{readSizeEv(n), sizeEv("large", gib, n)}; !slices.Equal(got, want) { |
| + if got, want := f.sizeEvents(), []string{sizeEv("large")}; !slices.Equal(got, want) { |
| t.Fatalf("size calls %v, want %v", got, want) |
| } |
| } |
| @@ -578,7 +494,6 @@ func TestTheBackstopCatchesAMissedNoteSize(t *testing.T) { |
| func TestAFailedBackstopLookupRetriesNextSweep(t *testing.T) { |
| t.Parallel() |
| f := newSizeFixture(t, "", half) |
| - n := f.incumbent.N |
| f.sweep(t) |
| f.routes.setSize(f.host, "large") // no NoteSize |
| f.clk.advance(sizeBackstop) |
| @@ -594,14 +509,13 @@ func TestAFailedBackstopLookupRetriesNextSweep(t *testing.T) { |
| t.Fatalf("size calls %v after a failed lookup", ev) |
| } |
| f.sweep(t) // the clock has not moved |
| - if got, want := f.sizeEvents(), []string{readSizeEv(n), sizeEv("large", gib, n)}; !slices.Equal(got, want) { |
| + if got, want := f.sizeEvents(), []string{sizeEv("large")}; !slices.Equal(got, want) { |
| t.Fatalf("size calls %v, want %v on the next sweep", got, want) |
| } |
| } |
| // Nothing is sized live for a host that is asleep or a worker, and a host |
| -// with no live size (flat) is asked once per change, with no unsettled |
| -// mark and no retries. |
| +// with no live size (flat) is asked once per change, with no retries. |
| func TestNoLiveCallForAsleepWorkerOrFlat(t *testing.T) { |
| t.Parallel() |
| t.Run("asleep", func(t *testing.T) { |
| @@ -645,9 +559,7 @@ func TestNoLiveCallForAsleepWorkerOrFlat(t *testing.T) { |
| t.Run("flat", func(t *testing.T) { |
| t.Parallel() |
| f := newSizeFixture(t, "", half) |
| - f.b.setSizeHooks(func(uint64) (instancectl.SizeReadBack, error) { |
| - return instancectl.SizeReadBack{}, fmt.Errorf("flat row: %w", errSizeNotLive) |
| - }, func(uint64, cgroup.Size, int64) (instancectl.SizeReadBack, error) { |
| + f.b.setSizeHook(func(cgroup.Size) (instancectl.SizeReadBack, error) { |
| return instancectl.SizeReadBack{}, fmt.Errorf("flat row: %w", errSizeNotLive) |
| }) |
| f.operatorSets("large") |
| @@ -655,33 +567,31 @@ func TestNoLiveCallForAsleepWorkerOrFlat(t *testing.T) { |
| f.sweep(t) |
| f.clk.advance(sizeBackstop) |
| f.sweep(t) |
| - if got, want := f.sizeEvents(), []string{readSizeEv(f.incumbent.N)}; !slices.Equal(got, want) { |
| + if got, want := f.sizeEvents(), []string{sizeEv("large")}; !slices.Equal(got, want) { |
| t.Fatalf("size calls %v, want only %v", got, want) |
| } |
| - if st := f.state(t); st.Unsettled { |
| - t.Fatalf("SizeState = %+v, want no unsettled mark", st) |
| - } |
| }) |
| } |
| -// Under host claims root answers 503 to the read: nothing is written live, |
| -// the size is recorded, and the next start carries it (spec §5.4 rev 8). |
| +// Under host claims root answers 503: nothing is written live, the call is |
| +// not retried, the size is recorded, and the next start carries it (spec |
| +// §5.4 rev 8). |
| func TestNoLiveChangeUnderClaims(t *testing.T) { |
| t.Parallel() |
| f := newSizeFixture(t, "", half) |
| - refused := func() (instancectl.SizeReadBack, error) { return instancectl.SizeReadBack{}, refusedByRoot(503) } |
| - f.b.setSizeHooks(func(uint64) (instancectl.SizeReadBack, error) { return refused() }, |
| - func(uint64, cgroup.Size, int64) (instancectl.SizeReadBack, error) { return refused() }) |
| + f.b.setSizeHook(func(cgroup.Size) (instancectl.SizeReadBack, error) { |
| + return instancectl.SizeReadBack{}, refusedByRoot(503) |
| + }) |
| f.operatorSets("xlarge") |
| f.sweep(t) |
| f.sweep(t) |
| f.clk.advance(sizeBackstop) |
| f.sweep(t) |
| - if got, want := f.sizeEvents(), []string{readSizeEv(f.incumbent.N)}; !slices.Equal(got, want) { |
| + if got, want := f.sizeEvents(), []string{sizeEv("xlarge")}; !slices.Equal(got, want) { |
| t.Fatalf("size calls %v, want only %v", got, want) |
| } |
| - if st := f.state(t); st.Unsettled || st.Want.Name != "xlarge" { |
| - t.Fatalf("SizeState = %+v, want xlarge pending with no unsettled mark", st) |
| + if st := f.state(t); st.Want.Name != "xlarge" { |
| + t.Fatalf("SizeState = %+v, want xlarge pending", st) |
| } |
| if got := f.tier(); got != half { |
| t.Fatalf("captured tier %d, want %d unchanged", got, half) |
| @@ -705,13 +615,13 @@ func TestJoinOpsWaitsForAResizeInFlight(t *testing.T) { |
| t.Parallel() |
| f := newSizeFixture(t, "", half) |
| entered, gate := make(chan struct{}, 1), make(chan struct{}) |
| - f.b.setSizeHooks(nil, func(_ uint64, _ cgroup.Size, mem int64) (instancectl.SizeReadBack, error) { |
| + f.b.setSizeHook(func(size cgroup.Size) (instancectl.SizeReadBack, error) { |
| select { |
| case entered <- struct{}{}: |
| default: |
| } |
| <-gate |
| - return instancectl.SizeReadBack{SliceMemoryMax: mem, UnitMemoryMax: mem}, nil |
| + return sizeApplied(size, half), nil |
| }) |
| var joined atomic.Bool |
| f.a.mu.Lock() |
| @@ -738,25 +648,20 @@ func TestJoinOpsWaitsForAResizeInFlight(t *testing.T) { |
| } |
| // sizingBackend is the barrier fixture's backend with the live size seam: |
| -// ReadSize answers a 512 MiB slice, and ResizeLive signals entered and |
| -// blocks on gate. |
| +// ResizeLive signals entered and blocks on gate. |
| type sizingBackend struct { |
| *fakeBackend |
| entered chan struct{} |
| gate chan struct{} |
| } |
| -func (s *sizingBackend) ReadSize(context.Context, registry.Route, uint64) (instancectl.SizeReadBack, error) { |
| - return instancectl.SizeReadBack{SliceMemoryMax: half}, nil |
| -} |
| - |
| -func (s *sizingBackend) ResizeLive(_ context.Context, _ registry.Route, _ uint64, _ cgroup.Size, mem int64) (instancectl.SizeReadBack, error) { |
| +func (s *sizingBackend) ResizeLive(_ context.Context, _ registry.Route, size cgroup.Size) (instancectl.SizeReadBack, error) { |
| select { |
| case s.entered <- struct{}{}: |
| default: |
| } |
| <-s.gate |
| - return instancectl.SizeReadBack{SliceMemoryMax: mem}, nil |
| + return sizeApplied(size, half), nil |
| } |
| // Astra plan R8-1: a stop whose barrier gave up on a resize stays pending |
diff --git a/internal/activator/swap.go b/internal/activator/swap.go| index 2827cc05b..21a54f199 100644 |
| --- a/internal/activator/swap.go |
| +++ b/internal/activator/swap.go |
| @@ -466,11 +466,10 @@ func (a *Service) swapOverlap(ctx context.Context, gb SwapBackend, at Attempt, n |
| // failed and awaits the sweep's retry (final review F11): an overlap |
| // raising it again now could have that retry lower it under the |
| // successor. |
| - // A live size change in flight, or one that may have left the |
| - // slice and the unit apart (#329), is refused too: the swap would |
| - // size its parent from a captured tier below what the slice may |
| - // already hold. |
| - if len(e.ops.members) > 0 || e.ops.raised || e.ops.resizing || e.ops.sizeUnsettled { |
| + // A live size change in flight (#329) is refused too: it and the |
| + // swap's raise and restore both write the host's slice, and the |
| + // activator keeps them apart per host (spec §5.4). |
| + if len(e.ops.members) > 0 || e.ops.raised || e.ops.resizing { |
| return errSwapBusy |
| } |
| // A run's unit may be starting against the incumbent right now |
| @@ -507,7 +506,9 @@ func (a *Service) swapOverlap(ctx context.Context, gb SwapBackend, at Attempt, n |
| // effective size and the incumbent's captured tier (spec §5.4 rev 8, |
| // R1-3). That applies when the route has a size now, or when the |
| // incumbent runs at a tier other than its build's own (a size was in |
| - // force at its start, or it was grown live, and has since been cleared). |
| + // force at its start and has since been cleared). Memory never changes |
| + // live (spec §5.4 rev 10), so the captured tier is what the incumbent |
| + // runs at, and a swap is how a growth lands. |
| // The raise and the restore then never lower memory: a shrink waits for |
| // a cold start. It is conditional so that a host with no operator size |
| // keeps each artifact's own tier, byte-identical to main: a release that |
diff --git a/internal/activator/swap_fixture_test.go b/internal/activator/swap_fixture_test.go| index 103358c77..caf99676c 100644 |
| --- a/internal/activator/swap_fixture_test.go |
| +++ b/internal/activator/swap_fixture_test.go |
| @@ -22,9 +22,8 @@ import ( |
| // fakeSwapBackend is fakeBackend plus the swap seam (SwapBackend) and the |
| // live size seam (SizeBackend). Every call is recorded in the shared order |
| // log: raise:<incumbent>+<successor>, startGen:<path>, switch:<n>, |
| -// restore:<tier>, startSidecarGen:<path>, readsize:<gen>, |
| -// size:<name>/<mem>/<gen>. Generation children are fakeProcs labelled |
| -// gen:<n>. |
| +// restore:<tier>, startSidecarGen:<path>, size:<name>. Generation |
| +// children are fakeProcs labelled gen:<n>. |
| type fakeSwapBackend struct { |
| *fakeBackend |
| gmu sync.Mutex |
| @@ -75,67 +74,42 @@ type fakeSwapBackend struct { |
| // and recorded only once it writes. |
| restoreGate chan struct{} |
| restoreEntered chan struct{} |
| - // The live size seam (Task 6). sizeRead and sizeWrite, when set, answer |
| - // ReadSize and ResizeLive after the call is recorded; otherwise the |
| - // fake is a slice and a unit that follow the writes (sliceMem, |
| - // unitMem; 512 MiB until written). Recorded as readsize:<gen> and |
| - // size:<name>/<mem>/<gen>. |
| - sizeRead func(gen uint64) (instancectl.SizeReadBack, error) |
| - sizeWrite func(gen uint64, size cgroup.Size, mem int64) (instancectl.SizeReadBack, error) |
| + // The live size seam (Task 6, ruling 12). sizeWrite, when set, answers |
| + // ResizeLive after the call is recorded; otherwise the fake slice takes |
| + // the size's CPU and IO shares and reads them back with sliceMem, the |
| + // memory it holds (512 MiB until set), which no size call changes. |
| + // Recorded as size:<name>. |
| + sizeWrite func(size cgroup.Size) (instancectl.SizeReadBack, error) |
| sliceMem int64 |
| - unitMem int64 |
| } |
| -// sizeReadBackLocked is what the fake slice and unit hold. g.gmu is held. |
| -func (g *fakeSwapBackend) sizeReadBackLocked(gen uint64) instancectl.SizeReadBack { |
| - if g.sliceMem == 0 { |
| - g.sliceMem = cgroup.TierDefault.MemoryMax |
| - } |
| - if g.unitMem == 0 { |
| - g.unitMem = cgroup.TierDefault.MemoryMax |
| - } |
| - rb := instancectl.SizeReadBack{SliceMemoryMax: g.sliceMem} |
| - if gen != 0 { |
| - rb.UnitMemoryMax = g.unitMem |
| - } |
| - return rb |
| -} |
| - |
| -func (g *fakeSwapBackend) ReadSize(_ context.Context, _ registry.Route, gen uint64) (instancectl.SizeReadBack, error) { |
| - g.record(fmt.Sprintf("readsize:%d", gen)) |
| - g.gmu.Lock() |
| - hook := g.sizeRead |
| - g.gmu.Unlock() |
| - if hook != nil { |
| - return hook(gen) |
| - } |
| - g.gmu.Lock() |
| - defer g.gmu.Unlock() |
| - return g.sizeReadBackLocked(gen), nil |
| -} |
| - |
| -func (g *fakeSwapBackend) ResizeLive(_ context.Context, _ registry.Route, gen uint64, size cgroup.Size, mem int64) (instancectl.SizeReadBack, error) { |
| - g.record(fmt.Sprintf("size:%s/%d/%d", size.Name, mem, gen)) |
| +func (g *fakeSwapBackend) ResizeLive(_ context.Context, _ registry.Route, size cgroup.Size) (instancectl.SizeReadBack, error) { |
| + g.record("size:" + size.Name) |
| g.gmu.Lock() |
| hook := g.sizeWrite |
| g.gmu.Unlock() |
| if hook != nil { |
| - return hook(gen, size, mem) |
| + return hook(size) |
| } |
| g.gmu.Lock() |
| defer g.gmu.Unlock() |
| - g.sizeReadBackLocked(gen) |
| - g.sliceMem = mem |
| - if gen != 0 { |
| - g.unitMem = mem |
| + if g.sliceMem == 0 { |
| + g.sliceMem = cgroup.TierDefault.MemoryMax |
| } |
| - return g.sizeReadBackLocked(gen), nil |
| + return sizeApplied(size, g.sliceMem), nil |
| +} |
| + |
| +// sizeApplied is root's read-back of a slice that took size's CPU and IO |
| +// shares and holds mem. |
| +func sizeApplied(size cgroup.Size, mem int64) instancectl.SizeReadBack { |
| + return instancectl.SizeReadBack{SliceMemoryMax: mem, CPUQuotaPercent: size.Shares.CPUQuotaPercent, |
| + CPUWeight: size.Shares.CPUWeight, IOWeight: size.Shares.IOWeight} |
| } |
| -// setSizeHooks sets the scripted ReadSize and ResizeLive answers. |
| -func (g *fakeSwapBackend) setSizeHooks(read func(uint64) (instancectl.SizeReadBack, error), write func(uint64, cgroup.Size, int64) (instancectl.SizeReadBack, error)) { |
| +// setSizeHook sets the scripted ResizeLive answer. |
| +func (g *fakeSwapBackend) setSizeHook(write func(cgroup.Size) (instancectl.SizeReadBack, error)) { |
| g.gmu.Lock() |
| - g.sizeRead, g.sizeWrite = read, write |
| + g.sizeWrite = write |
| g.gmu.Unlock() |
| } |
diff --git a/internal/instancectl/client.go b/internal/instancectl/client.go| index 6dd5c9fb9..2b3f28fb3 100644 |
| --- a/internal/instancectl/client.go |
| +++ b/internal/instancectl/client.go |
| @@ -320,29 +320,19 @@ 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) |
| +// Size applies a size's CPU and IO shares to host's slice and returns |
| +// root's read-back (#329, spec §5.4 rev 10). It never changes memory: a |
| +// new size's memory lands at the host's next start. A refusal before any |
| +// write (400, 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, size string) (SizeReadBack, error) { |
| + return c.size(ctx, http.MethodPost, url.Values{"host": {host}, "size": {size}}) |
| +} |
| + |
| +// ReadSize reads what host's slice holds now. Refusals wrap |
| +// ErrSizeRefused, as Size's do. |
| +func (c *Client) ReadSize(ctx context.Context, host string) (SizeReadBack, error) { |
| + return c.size(ctx, http.MethodGet, url.Values{"host": {host}}) |
| } |
| func (c *Client) size(ctx context.Context, method string, q url.Values) (SizeReadBack, error) { |
diff --git a/internal/instancectl/client_test.go b/internal/instancectl/client_test.go| index 4fdac118c..c9fede6a5 100644 |
| --- a/internal/instancectl/client_test.go |
| +++ b/internal/instancectl/client_test.go |
| @@ -198,32 +198,28 @@ func TestClientEgressVerbs(t *testing.T) { |
| } |
| } |
| -// 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. |
| +// Size and ReadSize: a refusal before any write (400 shape, 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") |
| + ok := sizeCtl("MemoryMax=536870912\nCPUQuotaPerSecUSec=2s\nCPUWeight=100\nIOWeight=100\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 { |
| + rb, err := c.Size(ctx, sizeHost, "large") |
| + if want := (SizeReadBack{SliceMemoryMax: 536870912, CPUQuotaPercent: 200, CPUWeight: 100, IOWeight: 100}); 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 want := "set-property --runtime " + sizeSlice + " CPUWeight=100 CPUQuota=200% IOWeight=100\n" + sizeReadBack; ok.joined() != want { |
| + t.Errorf("Size calls =\n%s\nwant\n%s", ok.joined(), want) |
| } |
| - if rb, err := c.ReadSize(ctx, sizeHost, 3); err != nil || rb.UnitMemoryMax != 1073741824 { |
| + if rb, err := c.ReadSize(ctx, sizeHost); err != nil || rb.CPUQuotaPercent != 200 { |
| 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) { |
| + _, claimed := newClient(t, sizeCtl(""), func(s *Server) { |
| s.ClaimStop = http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}) |
| }) |
| - failing := sizeCtl("536870912", "", "") |
| + failing := sizeCtl("") |
| failing.fail = map[string]error{"set-property": errSizeWrite, "show -p MemoryMax -p": errSizeWrite} |
| _, cf := newClient(t, failing) |
| @@ -231,14 +227,12 @@ func TestClientSizeMapsRefusalsToErrSizeRefused(t *testing.T) { |
| 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}, |
| + "Size 400": {func() error { _, err := c.Size(ctx, sizeHost, "huge"); return err }, true}, |
| + "ReadSize 400": {func() error { _, err := c.ReadSize(ctx, "../etc"); return err }, true}, |
| + "Size 503": {func() error { _, err := claimed.Size(ctx, sizeHost, "large"); return err }, true}, |
| + "ReadSize 503": {func() error { _, err := claimed.ReadSize(ctx, sizeHost); return err }, true}, |
| + "Size 502": {func() error { _, err := cf.Size(ctx, sizeHost, "large"); return err }, false}, |
| + "ReadSize 502": {func() error { _, err := cf.ReadSize(ctx, sizeHost); return err }, false}, |
| } { |
| err := tc.err() |
| if err == nil { |
diff --git a/internal/instancectl/cmd.go b/internal/instancectl/cmd.go| index a947e3697..3de279d51 100644 |
| --- a/internal/instancectl/cmd.go |
| +++ b/internal/instancectl/cmd.go |
| @@ -50,9 +50,6 @@ func (s *Server) handleCmd(w http.ResponseWriter, r *http.Request) { |
| lock, _ := s.cmdLocks.LoadOrStore(req.host, new(sync.Mutex)) |
| lock.(*sync.Mutex).Lock() |
| defer lock.(*sync.Mutex).Unlock() |
| - // A command's unit runs in the host slice: counted until it has |
| - // started, as every start is (beginSliceStart). |
| - defer s.beginSliceStart(req.host, req.tier)() |
| ctx := r.Context() |
| unit := UnitName(RoleCmd, req.host) |
| switch state := s.showValue(ctx, "ActiveState", unit); state { |
diff --git a/internal/instancectl/gen.go b/internal/instancectl/gen.go| index 2bda24ba2..2df14d281 100644 |
| --- a/internal/instancectl/gen.go |
| +++ b/internal/instancectl/gen.go |
| @@ -198,8 +198,8 @@ 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). |
| + // Tidying: a reused generation number starts with no leftover runtime |
| + // properties of an earlier unit of that name (removeGenControlDropIn). |
| if err := s.removeGenControlDropIn(unit); err != nil { |
| fail(http.StatusBadGateway, "control drop-in: "+err.Error()) |
| return |
| @@ -465,7 +465,7 @@ func (s *Server) handleParent(w http.ResponseWriter, r *http.Request) { |
| return |
| } |
| max := strconv.FormatInt(n, 10) |
| - defer s.lockSliceMemory(host)() |
| + defer s.lockSliceWrites(host)() |
| if out, err := s.Systemctl(r.Context(), "set-property", "--runtime", SliceName(host), |
| "MemoryMax="+max, "MemoryHigh="+strconv.FormatInt(cgroup.HighOf(n), 10), "MemorySwapMax="+max); err != nil { |
| http.Error(w, "set-property: "+strings.TrimSpace(out+" "+err.Error()), http.StatusBadGateway) |
diff --git a/internal/instancectl/server.go b/internal/instancectl/server.go| index e324e9502..eaa417e4c 100644 |
| --- a/internal/instancectl/server.go |
| +++ b/internal/instancectl/server.go |
| @@ -77,8 +77,8 @@ type Server struct { |
| 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). |
| + // file cleanup remove the generation unit's own <unit>.d there, as |
| + // tidying (removeGenControlDropIn). 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 |
| @@ -106,13 +106,11 @@ type Server struct { |
| // ActiveState read to its answer, so two starts for one host cannot both |
| // pass the check. |
| cmdLocks sync.Map |
| - // sliceMems holds one *sliceMem per host slice, keyed by SliceName: |
| - // every legacy write of a slice's memory takes its lock |
| - // (lockSliceMemory), and every legacy start counts itself in it |
| - // (beginSliceStart), so /size's populated-slice pre-check and its |
| - // writes are never interleaved with another write of that memory or |
| - // with a start that is about to populate the slice (#329, R1-3). |
| - sliceMems sync.Map |
| + // sliceLocks holds one *sync.Mutex per host slice, keyed by |
| + // SliceName: /size and /parent, the two verbs that write a running |
| + // slice's properties, take it (lockSliceWrites), so neither runs, nor |
| + // is read back, in the middle of the other (#329). |
| + sliceLocks sync.Map |
| // Run executes one command as root and returns its combined output; |
| // production is exec.CommandContext, tests record. Only |
| @@ -492,79 +490,27 @@ func parseRequest(r *http.Request, v verbShape) (request, error) { |
| // setTier writes the whole tier onto the host slice in one call: the |
| // memory caps, and the CPU and IO shares that follow from the same tier |
| // (#214 item 1). Seed, instance and sidecar share all of it. |
| -// |
| -// It takes no lock: every caller registered its tier with |
| -// beginSliceStart first, and /size never writes memory below a registered |
| -// tier, so a wedged write here holds up no other verb of the host. |
| func (s *Server) setTier(ctx context.Context, host string, tier cgroup.Limit) error { |
| return sliceTier(ctx, s.Systemctl, host, tier) |
| } |
| -// sliceMem is one host slice's memory lock and its in-flight starts. |
| -type sliceMem struct { |
| - mu sync.Mutex |
| - // starting holds the memory tier of each legacy start of the slice's |
| - // units between its beginSliceStart and its handler's return: from |
| - // before the tier step until systemctl start has returned. Guarded by |
| - // mu. |
| - starting []int64 |
| -} |
| - |
| -func (s *Server) sliceMem(host string) *sliceMem { |
| - m, _ := s.sliceMems.LoadOrStore(SliceName(host), new(sliceMem)) |
| - return m.(*sliceMem) |
| -} |
| - |
| -// lockSliceMemory takes host's slice-memory lock and returns its unlock. |
| -// It is held for one host at a time and never across a unit start or a |
| -// wait: /size holds it from its pre-check to its read-back, /parent |
| -// across its one set-property, beginSliceStart and its end across a list |
| -// update. Callers may already hold the host's cmdLocks entry (handleCmd); |
| -// nothing takes cmdLocks, legacyMu, genMu or the egress asserter's lock |
| -// while holding this one. |
| -func (s *Server) lockSliceMemory(host string) func() { |
| - m := s.sliceMem(host) |
| - m.mu.Lock() |
| - return m.mu.Unlock |
| -} |
| - |
| -// beginSliceStart registers a legacy start of one of host's units and |
| -// its tier, before its tier step or populated check, and returns the end |
| -// the handler defers: the registration stays until the handler returns, |
| -// so past its systemctl start, success or failure. While any start is |
| -// registered, /size treats the slice as populated, though its cgroup may |
| -// still be empty, and never writes memory below a registered tier: a |
| -// start that set (or is about to set) its tier is about to run under it |
| -// (R1-3). Registering waits only for a /size of the same host in flight; |
| -// the tier write after it runs unlocked. |
| -func (s *Server) beginSliceStart(host string, tier cgroup.Limit) (end func()) { |
| - m := s.sliceMem(host) |
| - m.mu.Lock() |
| - m.starting = append(m.starting, tier.MemoryMax) |
| - m.mu.Unlock() |
| - return func() { |
| - m.mu.Lock() |
| - defer m.mu.Unlock() |
| - for i, t := range m.starting { |
| - if t == tier.MemoryMax { |
| - m.starting = append(m.starting[:i], m.starting[i+1:]...) |
| - return |
| - } |
| - } |
| - } |
| +// lockSliceWrites takes host's slice lock and returns its unlock. It is |
| +// held for one host at a time and never across a unit start or a wait: |
| +// /size holds it across its write and read-back, /parent across its one |
| +// set-property. Nothing takes cmdLocks, legacyMu, genMu or the egress |
| +// asserter's lock while holding it. |
| +func (s *Server) lockSliceWrites(host string) func() { |
| + m, _ := s.sliceLocks.LoadOrStore(SliceName(host), new(sync.Mutex)) |
| + mu := m.(*sync.Mutex) |
| + mu.Lock() |
| + return mu.Unlock |
| } |
| // 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 { |
| - 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) |
| + max := strconv.FormatInt(tier.MemoryMax, 10) |
| + high := strconv.FormatInt(cgroup.HighOf(tier.MemoryMax), 10) |
| + sh := cgroup.SharesOf(tier) |
| _, err := systemctl(ctx, "set-property", "--runtime", SliceName(host), |
| "MemoryMax="+max, "MemoryHigh="+high, "MemorySwapMax="+max, |
| "CPUWeight="+strconv.Itoa(sh.CPUWeight), "CPUQuota="+strconv.Itoa(sh.CPUQuotaPercent)+"%", |
| @@ -584,9 +530,6 @@ func (s *Server) handleStart(w http.ResponseWriter, r *http.Request) { |
| http.Error(w, err.Error(), http.StatusBadRequest) |
| return |
| } |
| - // Counted from before the tier step until the start has returned, |
| - // generations included (startGen is reached only from here). |
| - defer s.beginSliceStart(req.host, req.tier)() |
| if req.gen != 0 { |
| s.startGen(w, r, req) |
| return |
| @@ -706,7 +649,6 @@ func (s *Server) handleSeed(w http.ResponseWriter, r *http.Request) { |
| http.Error(w, err.Error(), http.StatusBadRequest) |
| return |
| } |
| - defer s.beginSliceStart(req.host, req.tier)() |
| ctx := r.Context() |
| unit := UnitName(RoleSeed, req.host) |
| if s.refuseStagedExe(w, req, unit) { |
diff --git a/internal/instancectl/server_gen_test.go b/internal/instancectl/server_gen_test.go| index 8af380cd0..4a0631c4c 100644 |
| --- a/internal/instancectl/server_gen_test.go |
| +++ b/internal/instancectl/server_gen_test.go |
| @@ -848,19 +848,19 @@ 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) { |
| +// TestStartGenTidiesTheControlDropIn (Ruling C5, corrected by spec rev |
| +// 10): systemd keeps a `set-property --runtime` on a generation unit (plan |
| +// 2's IPAddressAllow nudge) in the control directory's <unit>.d until |
| +// reboot. It never outranks the generation's own drop-in (systemd merges |
| +// by file name and 50-carlos-generation.conf sorts last), so removing it |
| +// is tidying, not a size guard. The start removes the unit's own <unit>.d |
| +// before it writes the drop-in and the stop removes it with the other |
| +// files; a slice's .d (plan 2's allow evidence) is never touched, and a |
| +// <unit>.d that is a symlink is unlinked, never followed. |
| +func TestStartGenTidiesTheControlDropIn(t *testing.T) { |
| ctl := genCtl() |
| control, outside := t.TempDir(), t.TempDir() |
| - stale := filepath.Join(control, genUnit+".d", "50-MemoryMax.conf") |
| + leftover := filepath.Join(control, genUnit+".d", "50-IPAddressAllow.conf") |
| sliceEvidence := filepath.Join(control, SliceName(genHost)+".d", "50-IPAddressAllow.conf") |
| write := func(path, body string) { |
| t.Helper() |
| @@ -871,42 +871,30 @@ func TestStartGenClearsAStaleControlDropIn(t *testing.T) { |
| t.Fatal(err) |
| } |
| } |
| - write(stale, "[Service]\nMemoryMax=1073741824\n") |
| + write(leftover, "[Service]\nIPAddressAllow=10.0.5.20\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 |
| - } |
| + dropins, exe := t.TempDir(), t.TempDir() |
| + s, sock := serveOnSocket(t, ctl, func(s *Server) { |
| + s.DropInDir, s.ExeRoot, s.ControlDropInDir = dropins, exe, control |
| + s.Systemctl = func(ctx context.Context, args ...string) (string, error) { |
| + if line := strings.Join(args, " "); strings.HasPrefix(line, genShow) { |
| + _, leftErr := 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", leftErr == nil, dropErr == nil) |
| } |
| - return ctl.run(ctx, args...) |
| + mu.Unlock() |
| } |
| - }) |
| - } |
| - s, sock := serve(control) |
| + return ctl.run(ctx, args...) |
| + } |
| + }) |
| 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) |
| @@ -916,15 +904,12 @@ func TestStartGenClearsAStaleControlDropIn(t *testing.T) { |
| 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") |
| + write(leftover, "[Service]\nIPAddressAllow=10.0.5.20\n") |
| if err := c.StopGen(context.Background(), genHost, 7, false); err != nil { |
| t.Fatal(err) |
| } |
| @@ -950,14 +935,6 @@ func TestStartGenClearsAStaleControlDropIn(t *testing.T) { |
| 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. |
diff --git a/internal/instancectl/size.go b/internal/instancectl/size.go| index aa0de4f6d..de4b52336 100644 |
| --- a/internal/instancectl/size.go |
| +++ b/internal/instancectl/size.go |
| @@ -4,7 +4,6 @@ import ( |
| "context" |
| "errors" |
| "fmt" |
| - "math" |
| "net/http" |
| "net/url" |
| "os" |
| @@ -16,82 +15,55 @@ import ( |
| "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. |
| +// Live size changes (#329, spec §5.4 rev 10, ruling 12). Memory never |
| +// changes while an instance runs: a new size's memory lands at the host's |
| +// next start or swap. CPU and IO change live: POST /size sets the host |
| +// slice's CPUWeight, CPUQuota and IOWeight to a size's shares and reads |
| +// the slice back; it never writes MemoryMax, MemoryHigh or MemorySwapMax |
| +// and touches no generation unit. 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. |
| +// request before any write: a bad shape (400), 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. |
| +// SizeReadBack is what the host slice holds, as systemd reports it. A |
| +// value systemd reports as unlimited, or in a form this binary does not |
| +// read, is 0. SliceMemoryMax is for information: /size never writes it. |
| 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) |
| +// parseSizeHost validates a /size query's host. memory_max and gen are |
| +// refused: a live size carries no memory and names no generation (ruling |
| +// 12), and the activator that sends it ships in the same binary. It calls |
| +// nothing. |
| +func parseSizeHost(q url.Values) (string, error) { |
| + for _, gone := range []string{"memory_max", "gen"} { |
| + if q.Has(gone) { |
| + return "", fmt.Errorf("%s is not a size parameter: memory changes only at a start", gone) |
| } |
| - 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 |
| + host := q.Get("host") |
| + if !provision.ValidHostShape(host) { |
| + return "", fmt.Errorf("host %q is not a host", host) |
| } |
| - return false |
| + return host, nil |
| } |
| -// 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). |
| +// handleSize applies a size's CPU and IO shares to the host slice and |
| +// reads the slice back (spec §5.4). The shares are hierarchical cgroup |
| +// limits that kill nothing, and the slice has no drop-in of its own that |
| +// a daemon-reload could restore over them. |
| func (s *Server) handleSize(w http.ResponseWriter, r *http.Request) { |
| ctx := r.Context() |
| q := r.URL.Query() |
| - req, err := parseSizeTarget(q) |
| + host, err := parseSizeHost(q) |
| if err != nil { |
| http.Error(w, err.Error(), http.StatusBadRequest) |
| return |
| @@ -101,106 +73,48 @@ func (s *Server) handleSize(w http.ResponseWriter, r *http.Request) { |
| 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 |
| - } |
| - // From the pre-check to the read-back, no other /size or /parent of |
| - // this slice runs and no start registers (R1-3): two requests that |
| - // both passed the check at the old figure could otherwise land a |
| - // shrink after a growth. A start registered before this point may |
| - // still write its tier meanwhile; nothing here goes below that tier. |
| - mem := s.sliceMem(req.host) |
| - mem.mu.Lock() |
| - defer mem.mu.Unlock() |
| - if s.refuseInactiveGen(ctx, w, req) { |
| - return |
| - } |
| - // A start in flight is about to populate the slice under the memory |
| - // its tier step wrote or is about to write (or the memory a populated |
| - // slice holds), so it counts as populated, and its tier is held as |
| - // the slice's is: otherwise a shrink checked against an empty slice |
| - // lands under the unit it just started. |
| - for _, tier := range mem.starting { |
| - if n < tier { |
| - http.Error(w, "memory never shrinks while the slice is populated: a start in flight runs at "+strconv.FormatInt(tier, 10), http.StatusConflict) |
| - return |
| - } |
| - } |
| - if len(mem.starting) > 0 || 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 |
| - } |
| - } |
| - } |
| - if err := sliceSize(ctx, s.Systemctl, req.host, cgroup.Limit{MemoryMax: n}, size.Shares); err != nil { |
| - http.Error(w, "set-property "+SliceName(req.host)+": "+err.Error(), http.StatusBadGateway) |
| + // /parent writes the same slice; the read-back is never taken in the |
| + // middle of another writer's call. |
| + defer s.lockSliceWrites(host)() |
| + sh := size.Shares |
| + if out, err := s.Systemctl(ctx, "set-property", "--runtime", SliceName(host), |
| + "CPUWeight="+strconv.Itoa(sh.CPUWeight), "CPUQuota="+strconv.Itoa(sh.CPUQuotaPercent)+"%", |
| + "IOWeight="+strconv.Itoa(sh.IOWeight)); err != nil { |
| + http.Error(w, "set-property "+SliceName(host)+": "+strings.TrimSpace(out+" "+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) |
| + s.logf("instance-control: %s: size %s cpu and io applied live", host, size.Name) |
| + s.writeSizeReadBack(ctx, w, host) |
| } |
| // 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()) |
| + host, err := parseSizeHost(r.URL.Query()) |
| if err != nil { |
| http.Error(w, err.Error(), http.StatusBadRequest) |
| return |
| } |
| - // The read is taken between writes, never in the middle of a /size. |
| - defer s.lockSliceMemory(req.host)() |
| - if s.refuseInactiveGen(r.Context(), w, req) { |
| - return |
| - } |
| - s.writeSizeReadBack(r.Context(), w, req) |
| + defer s.lockSliceWrites(host)() |
| + s.writeSizeReadBack(r.Context(), w, host) |
| } |
| -// 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)) |
| +// writeSizeReadBack reads the slice's memory, CPU and IO 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, host string) { |
| + slice, err := s.Systemctl(ctx, "show", "-p", "MemoryMax", "-p", "CPUQuotaPerSecUSec", "-p", "CPUWeight", "-p", "IOWeight", SliceName(host)) |
| if err != nil { |
| - http.Error(w, "show "+SliceName(req.host)+": "+strings.TrimSpace(slice+" "+err.Error()), http.StatusBadGateway) |
| + http.Error(w, "show "+SliceName(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)) |
| + writeJSON(w, http.StatusOK, parseSizeShow(slice)) |
| } |
| -// 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 { |
| +// parseSizeShow reads systemctl show's answer for the slice. |
| +// 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 string) SizeReadBack { |
| sl := parseShow(slice) |
| rb := SizeReadBack{ |
| SliceMemoryMax: showBytes(sl["MemoryMax"]), |
| @@ -213,9 +127,6 @@ func parseSizeShow(slice, unit string) SizeReadBack { |
| break |
| } |
| } |
| - if unit != "" { |
| - rb.UnitMemoryMax = showBytes(parseShow(unit)["MemoryMax"]) |
| - } |
| return rb |
| } |
| @@ -237,18 +148,6 @@ func showInt(v string) int { |
| 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 |
| @@ -267,17 +166,19 @@ func genControlDropIn(controlDir, unit string) (string, bool) { |
| 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 |
| +// removeGenControlDropIn removes a generation unit's runtime properties, |
| +// as tidying: systemd keeps a `set-property --runtime` on the unit (plan |
| +// 2's IPAddressAllow nudge) in <unit>.d until reboot, so a box would |
| +// otherwise collect one directory per generation it ever nudged. It is |
| +// not a guard on a reused generation's size: systemd merges drop-ins by |
| +// file name, and the generation's own 50-carlos-generation.conf sorts |
| +// after every 50-<Property>.conf there, so a stale control value never |
| +// outranks it. Removing the nudge for a unit that is not running is |
| +// correct: 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). |
| +// 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 |
diff --git a/internal/instancectl/size_test.go b/internal/instancectl/size_test.go| index 2f3a6b760..ba0cf4890 100644 |
| --- a/internal/instancectl/size_test.go |
| +++ b/internal/instancectl/size_test.go |
| @@ -1,16 +1,11 @@ |
| package instancectl |
| import ( |
| - "context" |
| "encoding/json" |
| "errors" |
| - "fmt" |
| "io" |
| "net/http" |
| - "os" |
| - "path/filepath" |
| "strings" |
| - "sync" |
| "testing" |
| "time" |
| ) |
| @@ -21,35 +16,13 @@ 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 |
| + // sizeReadBack is the read-back's one show. |
| + sizeReadBack = "show -p MemoryMax -p CPUQuotaPerSecUSec -p CPUWeight -p IOWeight " + sizeSlice |
| ) |
| -// 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) |
| - } |
| +// sizeCtl answers the read-back with the given show. |
| +func sizeCtl(show string) *fakeCtl { |
| + return &fakeCtl{answers: map[string]string{sizeReadBack: show}} |
| } |
| func postSize(t *testing.T, c *http.Client, query string) (int, string) { |
| @@ -63,168 +36,60 @@ func postSize(t *testing.T, c *http.Client, query string) (int, string) { |
| 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", |
| +// Ruling 12 (spec §5.4 rev 10): /size writes the slice's CPU and IO |
| +// shares and nothing else, then reads the slice back. Memory stays where |
| +// the slice's start put it. |
| +func TestSizeWritesOnlyCPUAndIO(t *testing.T) { |
| + for _, tc := range []struct { |
| + size, write, show string |
| + want SizeReadBack |
| + }{ |
| + {"small", `set-property --runtime carlos-instances-shop\x2da.example.com.slice CPUWeight=50 CPUQuota=50% IOWeight=50`, |
| + "MemoryMax=536870912\nCPUQuotaPerSecUSec=500ms\nCPUWeight=50\nIOWeight=50\n", |
| + SizeReadBack{SliceMemoryMax: 536870912, CPUQuotaPercent: 50, CPUWeight: 50, IOWeight: 50}}, |
| + {"xlarge", `set-property --runtime carlos-instances-shop\x2da.example.com.slice CPUWeight=200 CPUQuota=400% IOWeight=200`, |
| + "MemoryMax=536870912\nCPUQuotaPerSecUSec=4s\nCPUWeight=200\nIOWeight=200\n", |
| + SizeReadBack{SliceMemoryMax: 536870912, CPUQuotaPercent: 400, CPUWeight: 200, IOWeight: 200}}, |
| } { |
| - 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) |
| + ctl := sizeCtl(tc.show) |
| + _, c := newServer(t, ctl) |
| + status, body := postSize(t, c, "host="+sizeHost+"&size="+tc.size) |
| + if status != http.StatusOK { |
| + t.Fatalf("%s: status %d: %s", tc.size, status, body) |
| } |
| - if got := ctl.joined(); countSetProperty(got) != 0 { |
| - t.Errorf("%s: a refused shrink wrote:\n%s", q, got) |
| + if got, want := ctl.joined(), tc.write+"\n"+sizeReadBack; got != want { |
| + t.Errorf("%s: calls =\n%s\nwant\n%s", tc.size, got, want) |
| } |
| - } |
| - // 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) |
| + for _, line := range strings.Split(ctl.joined(), "\n") { |
| + if strings.HasPrefix(line, "set-property") && strings.Contains(line, "Memory") { |
| + t.Errorf("%s: /size wrote a memory property: %s", tc.size, line) |
| + } |
| } |
| - if got := ctl.joined(); got != "show -p ActiveState --value "+sizeUnit { |
| - t.Errorf("ActiveState %q: calls =\n%s\nwant the state read only", state, got) |
| + var rb SizeReadBack |
| + if err := json.Unmarshal([]byte(body), &rb); err != nil { |
| + t.Fatal(err) |
| + } |
| + if rb != tc.want { |
| + t.Errorf("%s: read-back = %+v, want %+v", tc.size, rb, tc.want) |
| } |
| - } |
| - // 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) |
| } |
| } |
| +// memory_max and gen no longer exist: a request carrying either is a |
| +// caller from before ruling 12, refused before any systemctl call. |
| 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", |
| + "host=" + sizeHost + "&size=huge", |
| + "host=" + sizeHost + "&size=Large", |
| + "host=" + sizeHost, |
| + "host=" + sizeHost + "&size=large&memory_max=1073741824", |
| + "host=" + sizeHost + "&size=large&memory_max=", |
| + "host=" + sizeHost + "&size=large&gen=3", |
| + "host=" + sizeHost + "&size=large&gen=", |
| + "host=../etc&size=large", |
| + "host=&size=large", |
| } { |
| - ctl := sizeCtl("536870912", "", "") |
| + ctl := sizeCtl("") |
| _, 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) |
| @@ -233,8 +98,8 @@ func TestSizeRefusesBadInputs(t *testing.T) { |
| 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", "", "") |
| + for _, q := range []string{"host=../etc", "host=" + sizeHost + "&gen=3", "host=" + sizeHost + "&memory_max=536870912"} { |
| + ctl := sizeCtl("") |
| _, c := newServer(t, ctl) |
| resp, err := c.Get("http://control/size?" + q) |
| if err != nil { |
| @@ -250,41 +115,30 @@ func TestSizeRefusesBadInputs(t *testing.T) { |
| } |
| } |
| -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 { |
| +func TestSizeWriteFailureIs502(t *testing.T) { |
| + ctl := sizeCtl("MemoryMax=536870912\n") |
| + ctl.fail = map[string]error{"set-property --runtime " + sizeSlice: errSizeWrite} |
| + _, c := newServer(t, ctl) |
| + if status, body := postSize(t, c, "host="+sizeHost+"&size=large"); 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) { |
| + if got := ctl.joined(); strings.Contains(got, sizeReadBack) { |
| 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) |
| + // A read-back that fails after the write is a 502 too: the caller |
| + // cannot tell what is in force. |
| + ctl = sizeCtl("") |
| + ctl.fail = map[string]error{sizeReadBack: errSizeWrite} |
| + _, c = newServer(t, ctl) |
| + if status, body := postSize(t, c, "host="+sizeHost+"&size=large"); status != http.StatusBadGateway { |
| + t.Fatalf("read-back failure: status %d: %s, want 502", status, body) |
| } |
| } |
| -func TestSizeReadBackServesTheSliceAndUnit(t *testing.T) { |
| - ctl := sizeCtl("536870912", |
| - "CPUWeight=100\nIOWeight=100\nMemoryMax=536870912\nCPUQuotaPerSecUSec=1s\n", |
| - "MemoryMax=536870912\n") |
| +func TestSizeReadBackServesTheSlice(t *testing.T) { |
| + ctl := sizeCtl("CPUWeight=100\nIOWeight=100\nMemoryMax=536870912\nCPUQuotaPerSecUSec=1s\n") |
| _, c := newServer(t, ctl) |
| - resp, err := c.Get("http://control/size?host=" + sizeHost + "&gen=3") |
| + resp, err := c.Get("http://control/size?host=" + sizeHost) |
| if err != nil { |
| t.Fatal(err) |
| } |
| @@ -293,112 +147,56 @@ func TestSizeReadBackServesTheSliceAndUnit(t *testing.T) { |
| 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 { |
| + if want := (SizeReadBack{SliceMemoryMax: 536870912, CPUQuotaPercent: 100, CPUWeight: 100, IOWeight: 100}); 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) |
| + if got := ctl.joined(); got != sizeReadBack { |
| + t.Errorf("GET /size calls =\n%s\nwant the read-back only", got) |
| } |
| } |
| func TestSizeReadBackParsesSystemd(t *testing.T) { |
| for _, tc := range []struct { |
| - slice, unit string |
| - want SizeReadBack |
| + slice string |
| + want SizeReadBack |
| }{ |
| - {"MemoryMax=268435456\nCPUQuotaPerSecUSec=500ms\nCPUWeight=50\nIOWeight=50\n", "", |
| + {"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", |
| + {"MemoryMax=536870912\nCPUQuotaPerSecUSec=1s\nCPUWeight=100\nIOWeight=100\n", |
| + SizeReadBack{SliceMemoryMax: 536870912, CPUQuotaPercent: 100, CPUWeight: 100, IOWeight: 100}}, |
| + {"MemoryMax=1073741824\nCPUQuotaPerSecUSec=2s\nCPUWeight=100\nIOWeight=100\n", |
| SizeReadBack{SliceMemoryMax: 1073741824, CPUQuotaPercent: 200, CPUWeight: 100, IOWeight: 100}}, |
| - {"MemoryMax=2147483648\nCPUQuotaPerSecUSec=4s\nCPUWeight=200\nIOWeight=200\n", "", |
| + {"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", "", |
| + {"MemoryMax=infinity\nCPUQuotaPerSecUSec=infinity\nCPUWeight=[not set]\nIOWeight=[not set]\n", |
| SizeReadBack{}}, |
| - {"MemoryMax=805306368\nCPUQuotaPerSecUSec=1.500000s\nCPUWeight=100\nIOWeight=100\n", "", |
| + {"MemoryMax=805306368\nCPUQuotaPerSecUSec=1.500000s\nCPUWeight=100\nIOWeight=100\n", |
| SizeReadBack{SliceMemoryMax: 805306368, CPUWeight: 100, IOWeight: 100}}, |
| - {"MemoryMax=x\nCPUQuotaPerSecUSec=3s\n", "", SizeReadBack{}}, |
| + {"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) |
| + if got := parseSizeShow(tc.slice); got != tc.want { |
| + t.Errorf("parseSizeShow(%q) = %+v, want %+v", tc.slice, got, tc.want) |
| } |
| } |
| } |
| -// sliceMemory is a systemd whose slice MemoryMax follows its writes. The |
| -// first slice write blocks until released, and every pre-check read or |
| -// slice write that arrives while it is blocked is recorded: under the |
| -// per-host lock there is none. |
| -type sliceMemory struct { |
| - ctl *fakeCtl |
| - mu sync.Mutex |
| - max string |
| - blocked bool |
| - entered chan struct{} // closed when the first slice write blocks |
| - release chan struct{} |
| - arrived chan string // a call that arrived while the first write blocked |
| - duringIt []string |
| -} |
| - |
| -func newSliceMemory(max string) *sliceMemory { |
| - return &sliceMemory{ctl: &fakeCtl{}, max: max, entered: make(chan struct{}), release: make(chan struct{}), arrived: make(chan string, 8)} |
| -} |
| - |
| -func (m *sliceMemory) run(ctx context.Context, args ...string) (string, error) { |
| - line := strings.Join(args, " ") |
| - m.ctl.run(ctx, args...) // records the call |
| - m.mu.Lock() |
| - if m.blocked && (line == "show -p MemoryMax --value "+sizeSlice || strings.HasPrefix(line, "set-property --runtime "+sizeSlice)) { |
| - m.duringIt = append(m.duringIt, line) |
| - m.arrived <- line |
| - } |
| - switch { |
| - case line == "show -p MemoryMax --value "+sizeSlice: |
| - defer m.mu.Unlock() |
| - return m.max + "\n", nil |
| - case strings.HasPrefix(line, "set-property --runtime "+sizeSlice): |
| - first := m.entered != nil && !m.blocked |
| - if first { |
| - m.blocked = true |
| - close(m.entered) |
| - m.entered = nil |
| - m.mu.Unlock() |
| - <-m.release |
| - m.mu.Lock() |
| - m.blocked = false |
| - } |
| - for _, a := range args { |
| - if v, ok := strings.CutPrefix(a, "MemoryMax="); ok { |
| - m.max = v |
| - } |
| - } |
| - m.mu.Unlock() |
| - return "", nil |
| - case strings.HasPrefix(line, sizeReadBackSlice): |
| - defer m.mu.Unlock() |
| - return "MemoryMax=" + m.max + "\n", nil |
| - } |
| - m.mu.Unlock() |
| - return "", nil |
| -} |
| - |
| -// Review fix (R1-3): a growth and a shrink sent together for one populated |
| -// host. Without a per-host lock both pass the pre-check at 512 MiB, and |
| -// the shrink's write lands after the growth: memory shrinks while the |
| -// slice is populated. With it, the second request reads the first's write |
| -// and is refused. /parent, which also writes the slice's memory, waits on |
| -// the same lock. |
| -func TestSizeSerializesConcurrentSliceMemoryWrites(t *testing.T) { |
| +// /size and /parent both write the slice: one per-host lock keeps either |
| +// from running, or being read back, in the middle of the other. The first |
| +// /size is held inside its set-property; a second /size or a /parent of |
| +// the same host makes no systemctl call until it is released. |
| +func TestSizeSerializesWithOtherSliceWrites(t *testing.T) { |
| for _, second := range []string{"size", "parent"} { |
| t.Run(second, func(t *testing.T) { |
| - m := newSliceMemory("536870912") |
| - s, c := newServer(t, m.ctl, func(s *Server) { s.Systemctl = m.run }) |
| - sizePopulated(t, s) |
| - entered := m.entered |
| + ctl := sizeCtl("MemoryMax=536870912\nCPUQuotaPerSecUSec=4s\nCPUWeight=200\nIOWeight=200\n") |
| + entered, release := make(chan struct{}), make(chan struct{}) |
| + // The hold runs before the call is recorded, so nothing is |
| + // recorded while the first write is held, unless another |
| + // request ran. |
| + ctl.before = map[string]func(){"set-property": func() { close(entered); <-release }} |
| + _, c := newServer(t, ctl) |
| first := make(chan int, 1) |
| go func() { |
| - status, _ := postSize(t, c, "host="+sizeHost+"&size=large&memory_max=1073741824") |
| + status, _ := postSize(t, c, "host="+sizeHost+"&size=xlarge") |
| first <- status |
| }() |
| select { |
| @@ -406,195 +204,40 @@ func TestSizeSerializesConcurrentSliceMemoryWrites(t *testing.T) { |
| case <-time.After(10 * time.Second): |
| t.Fatal("the first request never wrote the slice") |
| } |
| - type answer struct { |
| - status int |
| - body string |
| - } |
| - done := make(chan answer, 1) |
| + done := make(chan int, 1) |
| go func() { |
| - var a answer |
| if second == "size" { |
| - a.status, a.body = postSize(t, c, "host="+sizeHost+"&size=standard&memory_max=536870912") |
| - } else { |
| - resp, err := c.Post("http://control/parent?host="+sizeHost+"&memory_max=536870912", "", nil) |
| - if err == nil { |
| - a.status = resp.StatusCode |
| - resp.Body.Close() |
| - } |
| + status, _ := postSize(t, c, "host="+sizeHost+"&size=small") |
| + done <- status |
| + return |
| } |
| - done <- a |
| + resp, err := c.Post("http://control/parent?host="+sizeHost+"&memory_max=1073741824", "", nil) |
| + if err != nil { |
| + done <- 0 |
| + return |
| + } |
| + resp.Body.Close() |
| + done <- resp.StatusCode |
| }() |
| - // The second request reaches its pre-check or its write at once |
| - // unless the lock holds it; a quarter second without either, |
| - // while the first write is in flight, is the lock at work. |
| - select { |
| - case line := <-m.arrived: |
| - t.Errorf("while the first write was in flight, the second request ran %q", line) |
| - case <-time.After(250 * time.Millisecond): |
| + time.Sleep(250 * time.Millisecond) |
| + if got := ctl.joined(); got != "" { |
| + t.Errorf("while the first write was held, the second request ran:\n%s", got) |
| } |
| - close(m.release) |
| + close(release) |
| if status := <-first; status != http.StatusOK { |
| - t.Fatalf("the growth answered %d", status) |
| + t.Fatalf("the first /size answered %d", status) |
| } |
| - a := <-done |
| - m.mu.Lock() |
| - final, during := m.max, m.duringIt |
| - m.mu.Unlock() |
| - if len(during) != 0 { |
| - t.Errorf("calls during the first write: %v", during) |
| + want := http.StatusOK |
| + if second == "parent" { |
| + want = http.StatusNoContent |
| } |
| - if second == "size" { |
| - if a.status != http.StatusConflict || !strings.Contains(a.body, "memory never shrinks") { |
| - t.Errorf("the shrink answered %d %s, want 409", a.status, a.body) |
| - } |
| - if final != "1073741824" { |
| - t.Errorf("slice MemoryMax = %s after both, want 1073741824 (no shrink while populated)", final) |
| - } |
| - } else if a.status != http.StatusNoContent || final != "536870912" { |
| - // /parent is the swap owner's restore and may lower; it |
| - // only has to wait its turn. |
| - t.Errorf("/parent answered %d, slice %s; want 204 after the growth", a.status, final) |
| + if status := <-done; status != want { |
| + t.Fatalf("the second request answered %d, want %d", status, want) |
| + } |
| + calls := strings.Split(ctl.joined(), "\n") |
| + if len(calls) < 3 || !strings.Contains(calls[0], "CPUWeight=200") || calls[1] != sizeReadBack || !strings.HasPrefix(calls[2], "set-property") { |
| + t.Errorf("calls =\n%s\nwant the first write and read-back before the second's write", ctl.joined()) |
| } |
| }) |
| } |
| } |
| - |
| -// startInFlight is a start path held inside its `systemctl start`, after |
| -// its tier step wrote the slice's memory, on genHost's slice, which has |
| -// no cgroup.events yet: nothing runs in it. |
| -type startInFlight struct { |
| - name string |
| - path string // the verb's query |
| - start string // the start call's prefix |
| -} |
| - |
| -var startsInFlight = []startInFlight{ |
| - {"run", "/start?host=" + genHost + "&role=run&memory_max=536870912", "start " + UnitName(RoleRun, genHost)}, |
| - {"sidecar", "/start?host=" + genHost + "&role=sidecar&memory_max=536870912", "start " + UnitName(RoleSidecar, genHost)}, |
| - {"seed", "/seed?host=" + genHost + "&memory_max=536870912", "start " + UnitName(RoleSeed, genHost)}, |
| - {"cmd", "/cmd?host=" + genHost + "&memory_max=536870912", "start --no-block " + UnitName(RoleCmd, genHost)}, |
| - {"generation", "/start?host=" + genHost + "&role=run&memory_max=536870912&gen=7", "start " + genUnit}, |
| -} |
| - |
| -// Review fix round 2 (R1-3): a start sets its tier (512 MiB) and is held |
| -// in its systemctl start; the slice's cgroup is still empty. A /size |
| -// shrink to 256 MiB arriving then must see the start as populating the |
| -// slice and refuse with no write; a growth is still applied. Once the |
| -// start returns, success or failure, the count is back to 0, and a |
| -// shrink of the empty slice goes through. |
| -func TestSizeTreatsAStartInFlightAsPopulated(t *testing.T) { |
| - for _, tc := range startsInFlight { |
| - for _, fail := range []bool{false, true} { |
| - t.Run(fmt.Sprintf("%s/fail=%v", tc.name, fail), func(t *testing.T) { |
| - ctl := genCtl() |
| - ctl.answers["show -p MemoryMax --value "+SliceName(genHost)] = "536870912\n" |
| - ctl.answers["show -p MemoryMax -p CPUQuotaPerSecUSec"] = "MemoryMax=536870912\n" |
| - entered, release := make(chan struct{}), make(chan struct{}) |
| - // The start is held, then makes a new invocation as systemd |
| - // would, so every path can tell its start went through |
| - // (genCtl alone always answers the same one). |
| - ctl.before = map[string]func(){"start": func() { |
| - close(entered) |
| - <-release |
| - ctl.mu.Lock() |
| - ctl.answers["show -p InvocationID --value"] = "inv-after-start\n" |
| - ctl.mu.Unlock() |
| - }} |
| - if fail { |
| - ctl.fail = map[string]error{tc.start: errSizeWrite} |
| - } |
| - s, c := newServer(t, ctl, func(s *Server) { |
| - s.DropInDir, s.ExeRoot = t.TempDir(), t.TempDir() |
| - s.cmdStartBound, s.cmdPollEvery = 20*time.Millisecond, 5*time.Millisecond |
| - }) |
| - started := make(chan int, 1) |
| - go func() { |
| - resp, err := c.Post("http://control"+tc.path, "", nil) |
| - if err != nil { |
| - started <- 0 |
| - return |
| - } |
| - resp.Body.Close() |
| - started <- resp.StatusCode |
| - }() |
| - select { |
| - case <-entered: |
| - case <-time.After(10 * time.Second): |
| - t.Fatal("the start never reached systemctl start") |
| - } |
| - tier := `set-property --runtime ` + SliceName(genHost) + ` MemoryMax=536870912 ` |
| - if got := ctl.joined(); !strings.Contains(got, tier) { |
| - t.Fatalf("the start did not set its tier before starting:\n%s", got) |
| - } |
| - writes := countSetProperty(ctl.joined()) |
| - status, body := postSize(t, c, "host="+genHost+"&size=small&memory_max=268435456") |
| - if status != http.StatusConflict || !strings.Contains(body, "memory never shrinks") { |
| - t.Errorf("a shrink during the start answered %d %s, want 409", status, body) |
| - } |
| - if got := countSetProperty(ctl.joined()); got != writes { |
| - t.Errorf("the refused shrink wrote:\n%s", ctl.joined()) |
| - } |
| - if status, body := postSize(t, c, "host="+genHost+"&size=large&memory_max=1073741824"); status != http.StatusOK { |
| - t.Errorf("a growth during the start answered %d %s, want 200", status, body) |
| - } |
| - close(release) |
| - want := http.StatusOK |
| - if fail { |
| - want = http.StatusBadGateway |
| - } |
| - if got := <-started; got != want { |
| - t.Errorf("the start answered %d, want %d", got, want) |
| - } |
| - m := s.sliceMem(genHost) |
| - m.mu.Lock() |
| - n := len(m.starting) |
| - m.mu.Unlock() |
| - if n != 0 { |
| - t.Errorf("in-flight starts after the start returned = %d, want 0", n) |
| - } |
| - if fail { |
| - // The failed start left nothing running: the slice is |
| - // empty, so memory may go down. |
| - if status, body := postSize(t, c, "host="+genHost+"&size=small&memory_max=268435456"); status != http.StatusOK { |
| - t.Errorf("a shrink after the failed start answered %d %s, want 200", status, body) |
| - } |
| - } |
| - }) |
| - } |
| - } |
| -} |
| - |
| -// The tier write itself takes no lock, so a start can be registered and |
| -// still before its tier step while the slice holds less than its tier. A |
| -// /size then may not write memory below the start's tier, or the start's |
| -// write and the /size write could land in either order around the unit's |
| -// start. |
| -func TestSizeHoldsAStartsTierBeforeItIsWritten(t *testing.T) { |
| - ctl := genCtl() |
| - ctl.answers["show -p MemoryMax --value "+SliceName(genHost)] = "268435456\n" |
| - entered, release := make(chan struct{}), make(chan struct{}) |
| - ctl.before = map[string]func(){"set-property": func() { close(entered); <-release }} |
| - _, c := newServer(t, ctl) |
| - started := make(chan struct{}) |
| - go func() { |
| - defer close(started) |
| - if resp, err := c.Post("http://control/start?host="+genHost+"&role=run&memory_max=536870912", "", nil); err == nil { |
| - resp.Body.Close() |
| - } |
| - }() |
| - select { |
| - case <-entered: |
| - case <-time.After(10 * time.Second): |
| - t.Fatal("the start never reached its tier step") |
| - } |
| - status, body := postSize(t, c, "host="+genHost+"&size=small&memory_max=268435456") |
| - if status != http.StatusConflict || !strings.Contains(body, "a start in flight runs at 536870912") { |
| - t.Errorf("a write below the in-flight start's tier answered %d %s, want 409", status, body) |
| - } |
| - // The start's own write is held before it is recorded: none at all. |
| - if got := countSetProperty(ctl.joined()); got != 0 { |
| - t.Errorf("set-property calls = %d, want none while the start's is held:\n%s", got, ctl.joined()) |
| - } |
| - close(release) |
| - <-started |
| -} |