Merge pull request 'Design 47 H2: the node-engine takes a compose ask once, answers composition-diff and drains its tool runner' (#248) from feat/47-H2 into main
This commit was merged in pull request #248.
This commit is contained in:
@@ -15,7 +15,7 @@ import (
|
||||
// command exits zero having ignored what it was asked. Here that would mean `--dry-run` ignored on
|
||||
// a program whose whole job is to change a machine.
|
||||
|
||||
func TestBootstrapIsWhatItDoesWithNoCommand(t *testing.T) {
|
||||
func testBootstrapIsWhatItDoesWithNoCommand(t *testing.T) {
|
||||
// Running the installer with nothing but flags must install, not print usage: the command is
|
||||
// the reason the binary exists, and making somebody type its name twice buys nothing.
|
||||
command, opts, _, err := parseArgs([]string{"--dry-run"})
|
||||
@@ -30,7 +30,7 @@ func TestBootstrapIsWhatItDoesWithNoCommand(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestFlagsAreReadWhereverTheySit(t *testing.T) {
|
||||
func testFlagsAreReadWhereverTheySit(t *testing.T) {
|
||||
for _, args := range [][]string{
|
||||
{"bootstrap", "--dry-run", "--bundle", "s.lock", "--json"},
|
||||
{"bootstrap", "--json", "--bundle=s.lock", "--dry-run"},
|
||||
@@ -48,7 +48,7 @@ func TestFlagsAreReadWhereverTheySit(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAMistypedFlagIsRefusedNotIgnored(t *testing.T) {
|
||||
func testAMistypedFlagIsRefusedNotIgnored(t *testing.T) {
|
||||
// Asymmetric cost: an error is a moment's annoyance, and a silently dropped --dry-run is a
|
||||
// machine changed by somebody who asked for it not to be.
|
||||
if _, _, _, err := parseArgs([]string{"bootstrap", "--dry-runn"}); err == nil {
|
||||
@@ -56,13 +56,13 @@ func TestAMistypedFlagIsRefusedNotIgnored(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnUnexpectedArgumentIsRefused(t *testing.T) {
|
||||
func testAnUnexpectedArgumentIsRefused(t *testing.T) {
|
||||
if _, _, _, err := parseArgs([]string{"bootstrap", "foundation.lock"}); err == nil {
|
||||
t.Fatal("a stray argument was ignored rather than refused — the bundle is --bundle")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheDefaultsAreTheDocumentedOnes(t *testing.T) {
|
||||
func testTheDefaultsAreTheDocumentedOnes(t *testing.T) {
|
||||
// The usage text is a promise. A default that drifts from what is printed is a small lie that
|
||||
// costs somebody an afternoon in front of a machine that will not come up.
|
||||
_, opts, jsonOut, err := parseArgs(nil)
|
||||
@@ -92,7 +92,7 @@ func TestTheDefaultsAreTheDocumentedOnes(t *testing.T) {
|
||||
// Every flag the usage text promises must exist, and every flag that exists must be in the usage
|
||||
// text. The two drifting apart is how a program acquires a feature nobody can find and a
|
||||
// documented option that does nothing.
|
||||
func TestTheUsageTextAndTheFlagsAgree(t *testing.T) {
|
||||
func testTheUsageTextAndTheFlagsAgree(t *testing.T) {
|
||||
var opts bootstrap.Options
|
||||
var jsonOut bool
|
||||
set := newFlagSet(&opts, &jsonOut)
|
||||
@@ -119,7 +119,7 @@ func TestTheUsageTextAndTheFlagsAgree(t *testing.T) {
|
||||
|
||||
// The pivot's defaults are the documented ones too, and the one that has no default is the one
|
||||
// that decides whether the pivot happens at all.
|
||||
func TestThePivotsDefaultsAreTheDocumentedOnes(t *testing.T) {
|
||||
func testThePivotsDefaultsAreTheDocumentedOnes(t *testing.T) {
|
||||
_, opts, _, err := parseArgs(nil)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
@@ -152,7 +152,7 @@ func TestThePivotsDefaultsAreTheDocumentedOnes(t *testing.T) {
|
||||
|
||||
// --node overrides the machine's own name rather than being ignored because a default was already
|
||||
// computed. The name is what the mesh's records, tokens, assignments and pushes all name.
|
||||
func TestTheNodeNameCanBeSaid(t *testing.T) {
|
||||
func testTheNodeNameCanBeSaid(t *testing.T) {
|
||||
_, opts, _, err := parseArgs([]string{"--node", "anchor", "--catalog", "/somewhere"})
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
@@ -167,7 +167,7 @@ func TestTheNodeNameCanBeSaid(t *testing.T) {
|
||||
|
||||
// Defends novox/hq ADR 0100: the foundation's ports are inputs to genesis, and the registry's port
|
||||
// and the address nodes pull from say one port.
|
||||
func TestTheFoundationsPortsAreGiven(t *testing.T) {
|
||||
func testTheFoundationsPortsAreGiven(t *testing.T) {
|
||||
_, opts, _, err := parseArgs([]string{"--store-port", "5433", "--hub-port", "51821", "--overlay-range", "10.77.0.0/16"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -177,7 +177,7 @@ func TestTheFoundationsPortsAreGiven(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheRegistrysPortAndAddressAgree(t *testing.T) {
|
||||
func testTheRegistrysPortAndAddressAgree(t *testing.T) {
|
||||
_, opts, _, err := parseArgs([]string{"--registry-port", "5100"})
|
||||
if err != nil || opts.Registry != "127.0.0.1:5100" {
|
||||
t.Errorf("--registry-port alone: %s %v", opts.Registry, err)
|
||||
@@ -191,7 +191,7 @@ func TestTheRegistrysPortAndAddressAgree(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestARegistryGivenAsAHostAloneTakesTheRegistrysPort(t *testing.T) {
|
||||
func testARegistryGivenAsAHostAloneTakesTheRegistrysPort(t *testing.T) {
|
||||
_, opts, _, err := parseArgs([]string{"--registry", "192.0.2.10"})
|
||||
if err != nil || opts.Registry != "192.0.2.10:5000" || opts.Ports.Registry != 5000 {
|
||||
t.Errorf("--registry host alone: %s %d %v", opts.Registry, opts.Ports.Registry, err)
|
||||
@@ -204,3 +204,18 @@ func TestARegistryGivenAsAHostAloneTakesTheRegistrysPort(t *testing.T) {
|
||||
t.Error("a registry with a port that is not a number was accepted")
|
||||
}
|
||||
}
|
||||
|
||||
// TestMain runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestMain(t *testing.T) {
|
||||
t.Run("BootstrapIsWhatItDoesWithNoCommand", testBootstrapIsWhatItDoesWithNoCommand)
|
||||
t.Run("FlagsAreReadWhereverTheySit", testFlagsAreReadWhereverTheySit)
|
||||
t.Run("AMistypedFlagIsRefusedNotIgnored", testAMistypedFlagIsRefusedNotIgnored)
|
||||
t.Run("AnUnexpectedArgumentIsRefused", testAnUnexpectedArgumentIsRefused)
|
||||
t.Run("TheDefaultsAreTheDocumentedOnes", testTheDefaultsAreTheDocumentedOnes)
|
||||
t.Run("TheUsageTextAndTheFlagsAgree", testTheUsageTextAndTheFlagsAgree)
|
||||
t.Run("ThePivotsDefaultsAreTheDocumentedOnes", testThePivotsDefaultsAreTheDocumentedOnes)
|
||||
t.Run("TheNodeNameCanBeSaid", testTheNodeNameCanBeSaid)
|
||||
t.Run("TheFoundationsPortsAreGiven", testTheFoundationsPortsAreGiven)
|
||||
t.Run("TheRegistrysPortAndAddressAgree", testTheRegistrysPortAndAddressAgree)
|
||||
t.Run("ARegistryGivenAsAHostAloneTakesTheRegistrysPort", testARegistryGivenAsAHostAloneTakesTheRegistrysPort)
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ import (
|
||||
// because of the apply itself (it replaces the bus's own container), which then must finish (issue 1945, live on
|
||||
// 2026-10-25 at 11:23: novox's node-engine removed the bus container, its link's context ended, and the docker run that
|
||||
// would have made the new one was never made).
|
||||
func TestAnApplyOutlivesTheLinksContext(t *testing.T) {
|
||||
func testAnApplyOutlivesTheLinksContext(t *testing.T) {
|
||||
type key struct{}
|
||||
link, cancel := context.WithCancel(context.WithValue(context.Background(), key{}, "v"))
|
||||
ctx, done := applyContext(link)
|
||||
@@ -26,7 +26,7 @@ func TestAnApplyOutlivesTheLinksContext(t *testing.T) {
|
||||
|
||||
// An apply is bounded all the same: a step that hangs (a docker call that never returns) cannot hold the node agent for
|
||||
// ever (the review of issue 1945).
|
||||
func TestAnApplyIsBounded(t *testing.T) {
|
||||
func testAnApplyIsBounded(t *testing.T) {
|
||||
t.Run("the marks of the haves never hold the pass", marksOfTheHavesNeverHoldThePass)
|
||||
ctx, done := applyContext(context.Background())
|
||||
defer done()
|
||||
@@ -38,3 +38,9 @@ func TestAnApplyIsBounded(t *testing.T) {
|
||||
t.Fatalf("the bound is %s away, want about %s", left, applyBound)
|
||||
}
|
||||
}
|
||||
|
||||
// TestApplyContext runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestApplyContext(t *testing.T) {
|
||||
t.Run("AnApplyOutlivesTheLinksContext", testAnApplyOutlivesTheLinksContext)
|
||||
t.Run("AnApplyIsBounded", testAnApplyIsBounded)
|
||||
}
|
||||
|
||||
@@ -319,6 +319,20 @@ func compositionFrom(current *agentNow, withheld func(ctx context.Context, modul
|
||||
}
|
||||
}
|
||||
|
||||
// compositionDiffFrom answers the verb composition-diff from the node agent that runs now (design 47 H2 §813 (3)); refused in
|
||||
// words while none does.
|
||||
func compositionDiffFrom(current *agentNow) func(module string, revision int64, digest string) (any, error) {
|
||||
return func(module string, revision int64, digest string) (any, error) {
|
||||
ag := current.get()
|
||||
if ag == nil {
|
||||
return nil, errors.New("this engine's node agent has not started, so it holds no composition yet")
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), compositionReadFor)
|
||||
defer cancel()
|
||||
return ag.CompositionDiff(ctx, module, revision, digest)
|
||||
}
|
||||
}
|
||||
|
||||
// withheldPartsOf is, of the composer that runs now, each part its last pass kept for module because its read did not answer.
|
||||
func withheldPartsOf(composer *atomic.Pointer[selfcompose.Composer]) func(module string) map[string]string {
|
||||
return func(module string) map[string]string {
|
||||
@@ -414,8 +428,9 @@ func packagesFrom(node string, session *link.Session, composer *atomic.Pointer[s
|
||||
// nec.AnswerBound, selfcompose candidateWithin). The answer is
|
||||
// the seat's shape (nodeengine.ComposeCandidateAnswer), checked as it is encoded; a node whose shadow does not run yet
|
||||
// answers unready, which the checker takes as no answer.
|
||||
func composeCandidateFrom(node string, shadow *atomic.Pointer[selfcompose.Shadow]) func(candidate string, input bool, call string, line buscalls.ChunkLine) (any, error) {
|
||||
return func(candidate string, input bool, call string, line buscalls.ChunkLine) (any, error) {
|
||||
// An ask carrying an id is taken once by it (design 47 H2 §775, H-A-364).
|
||||
func composeCandidateFrom(node string, shadow *atomic.Pointer[selfcompose.Shadow]) func(candidate string, input bool, call, askID string, line buscalls.ChunkLine) (any, error) {
|
||||
return func(candidate string, input bool, call, askID string, line buscalls.ChunkLine) (any, error) {
|
||||
ask := nodeengine.ComposeCandidateInput{Candidate: candidate, Input: input, Call: call}
|
||||
if _, err := nec.EncodeAsk(ask); err != nil {
|
||||
return nil, err
|
||||
@@ -428,7 +443,7 @@ func composeCandidateFrom(node string, shadow *atomic.Pointer[selfcompose.Shadow
|
||||
} else {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), nec.AnswerBound)
|
||||
defer cancel()
|
||||
a = s.ComposeCandidate(ctx, ask)
|
||||
a = s.ComposeCandidate(ctx, ask, askID)
|
||||
}
|
||||
return answerComposeCandidate(a, candidate, input, call, line)
|
||||
}
|
||||
|
||||
@@ -39,7 +39,7 @@ func referenceDeclaration(path string, body []byte) []byte {
|
||||
|
||||
// 1695/AC1 and AC2, through the whole apply: a reference is fetched, verified and written; a differing object
|
||||
// refuses the declaration whole and writes nothing.
|
||||
func TestADeclarationWithAFileByDigestAppliesFromTheObject(t *testing.T) {
|
||||
func testADeclarationWithAFileByDigestAppliesFromTheObject(t *testing.T) {
|
||||
unansweringPacman(t)
|
||||
body := []byte(strings.Repeat("a line of a big file\n", 4000))
|
||||
name, _ := declaration.ObjectName(declaration.DigestOf(body))
|
||||
@@ -159,7 +159,7 @@ func TestADeclarationWithAFileByDigestAppliesFromTheObject(t *testing.T) {
|
||||
|
||||
// 1695/AC8: the hand-run `apply <file>` and `reconcile` have no bus: a reference whose file here verifies is applied
|
||||
// as it is, any other refuses and writes nothing — never an empty file.
|
||||
func TestTheHandApplyNeverWritesAReferenceEmpty(t *testing.T) {
|
||||
func testTheHandApplyNeverWritesAReferenceEmpty(t *testing.T) {
|
||||
unansweringPacman(t)
|
||||
body := []byte(strings.Repeat("a line of a big file\n", 4000))
|
||||
dir := t.TempDir()
|
||||
@@ -187,3 +187,9 @@ func TestTheHandApplyNeverWritesAReferenceEmpty(t *testing.T) {
|
||||
t.Errorf("1695/AC8: the file holds %d bytes, want %d", len(got), len(body))
|
||||
}
|
||||
}
|
||||
|
||||
// TestFileReferences runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestFileReferences(t *testing.T) {
|
||||
t.Run("ADeclarationWithAFileByDigestAppliesFromTheObject", testADeclarationWithAFileByDigestAppliesFromTheObject)
|
||||
t.Run("TheHandApplyNeverWritesAReferenceEmpty", testTheHandApplyNeverWritesAReferenceEmpty)
|
||||
}
|
||||
|
||||
@@ -16,7 +16,7 @@ import (
|
||||
// Every directory used as found is its module's resource of kind directory, unhealthy, naming its owner, on
|
||||
// every statement (novox/hq issue 339): the controller raises that as the module's condition. The way out it
|
||||
// names is the node seat's hand-over, with this node's name (novox/hq ADR 0563 §5).
|
||||
func TestAFoundDirectoryIsStatedUnhealthy(t *testing.T) {
|
||||
func testAFoundDirectoryIsStatedUnhealthy(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
known := store.State{Resources: []store.Applied{
|
||||
{ID: "notes.data", Type: "directory", Target: dir, AsFound: true, Declared: "root, mode 755", AppliedAt: time.Now()},
|
||||
@@ -61,7 +61,7 @@ func realDir(t *testing.T) string {
|
||||
|
||||
// A hand-over records a directory used as found, and refuses one that is not — through the engine's own
|
||||
// subcommand and through the controller's ask alike, which are one judgement.
|
||||
func TestHandOverRecordsOnlyAFoundDirectory(t *testing.T) {
|
||||
func testHandOverRecordsOnlyAFoundDirectory(t *testing.T) {
|
||||
dir := realDir(t)
|
||||
statePath := filepath.Join(dir, "state.json")
|
||||
found := filepath.Join(dir, "found")
|
||||
@@ -111,7 +111,7 @@ func TestHandOverRecordsOnlyAFoundDirectory(t *testing.T) {
|
||||
// Every value of a hand-over is judged before anything is recorded, and each refusal records nothing: a relative
|
||||
// path, a path that is not the engine's statement of the directory (`..`, a doubled or trailing separator), one
|
||||
// not used as found, a link at the path, a link in the path, a file, a directory that is gone.
|
||||
func TestAHandOverIsRefusedForEveryPathThatIsNotTheFoundDirectory(t *testing.T) {
|
||||
func testAHandOverIsRefusedForEveryPathThatIsNotTheFoundDirectory(t *testing.T) {
|
||||
dir := realDir(t)
|
||||
statePath := filepath.Join(dir, "state.json")
|
||||
found := filepath.Join(dir, "found")
|
||||
@@ -176,3 +176,10 @@ func TestAHandOverIsRefusedForEveryPathThatIsNotTheFoundDirectory(t *testing.T)
|
||||
t.Fatalf("recorded: %+v", all)
|
||||
}
|
||||
}
|
||||
|
||||
// TestFound runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestFound(t *testing.T) {
|
||||
t.Run("AFoundDirectoryIsStatedUnhealthy", testAFoundDirectoryIsStatedUnhealthy)
|
||||
t.Run("HandOverRecordsOnlyAFoundDirectory", testHandOverRecordsOnlyAFoundDirectory)
|
||||
t.Run("AHandOverIsRefusedForEveryPathThatIsNotTheFoundDirectory", testAHandOverIsRefusedForEveryPathThatIsNotTheFoundDirectory)
|
||||
}
|
||||
|
||||
@@ -14,7 +14,7 @@ import (
|
||||
|
||||
// `key` makes the tunnel key once and prints its public half; asked again it prints the same one,
|
||||
// because a token may already have been issued for it (novox/hq ADR 0169).
|
||||
func TestKeyMakesTheTunnelKeyOnceAndKeepsIt(t *testing.T) {
|
||||
func testKeyMakesTheTunnelKeyOnceAndKeepsIt(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
opts := options{state: filepath.Join(dir, "state.json")}
|
||||
first := captureStdout(t, func() {
|
||||
@@ -41,7 +41,7 @@ func TestKeyMakesTheTunnelKeyOnceAndKeepsIt(t *testing.T) {
|
||||
|
||||
// A token through the tunnel takes the key it was issued for, and says so when this machine has none
|
||||
// or another.
|
||||
func TestATokenThroughTheTunnelTakesItsOwnKey(t *testing.T) {
|
||||
func testATokenThroughTheTunnelTakesItsOwnKey(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
state := filepath.Join(dir, "state.json")
|
||||
tt := &identity.TokenTunnel{Key: "x", Address: "10.42.0.9/32", Range: "10.42.0.0/16", HubKey: "h", HubEndpoint: "198.51.100.1:51820"}
|
||||
@@ -61,7 +61,7 @@ func TestATokenThroughTheTunnelTakesItsOwnKey(t *testing.T) {
|
||||
|
||||
// The first tunnel is the mesh's interface and unit, with the hub as its one peer and no secret in
|
||||
// the file — the same shape the mesh's declaration replaces it with.
|
||||
func TestTheFirstTunnelIsTheMeshsInterfaceWithTheHubAsItsPeer(t *testing.T) {
|
||||
func testTheFirstTunnelIsTheMeshsInterfaceWithTheHubAsItsPeer(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
tunnelConfigPath = filepath.Join(dir, "wireguard", "mesh0.conf")
|
||||
lookPath = func(string) (string, error) { return "/usr/bin/wg-quick", nil }
|
||||
@@ -117,7 +117,7 @@ func captureStdout(t *testing.T, fn func()) string {
|
||||
|
||||
// The bus is dialled only once the hub has answered the tunnel, and a hub that never does is said
|
||||
// as the tunnel's fault rather than the bus's.
|
||||
func TestTheBusWaitsForTheHubToAnswer(t *testing.T) {
|
||||
func testTheBusWaitsForTheHubToAnswer(t *testing.T) {
|
||||
asked := 0
|
||||
answersOnThird := func(_ context.Context, name string, args ...string) (string, error) {
|
||||
asked++
|
||||
@@ -137,3 +137,11 @@ func TestTheBusWaitsForTheHubToAnswer(t *testing.T) {
|
||||
t.Fatalf("a hub that never answered was not said: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestJoinTunnel runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestJoinTunnel(t *testing.T) {
|
||||
t.Run("KeyMakesTheTunnelKeyOnceAndKeepsIt", testKeyMakesTheTunnelKeyOnceAndKeepsIt)
|
||||
t.Run("ATokenThroughTheTunnelTakesItsOwnKey", testATokenThroughTheTunnelTakesItsOwnKey)
|
||||
t.Run("TheFirstTunnelIsTheMeshsInterfaceWithTheHubAsItsPeer", testTheFirstTunnelIsTheMeshsInterfaceWithTheHubAsItsPeer)
|
||||
t.Run("TheBusWaitsForTheHubToAnswer", testTheBusWaitsForTheHubToAnswer)
|
||||
}
|
||||
|
||||
@@ -1028,6 +1028,7 @@ func runLink(ctx context.Context, opts options) error {
|
||||
go reconcileActs(ctx, queue.Acts)
|
||||
current := &agentNow{}
|
||||
queue.Acts.Composition = compositionFrom(current, queue.WithheldOf, withheldPartsOf(&composerNow))
|
||||
queue.Acts.CompositionDiff = compositionDiffFrom(current)
|
||||
queue.Acts.Compose = composeFrom(current, &composerNow)
|
||||
queue.Acts.ApplyOrder = applyOrderFrom(current)
|
||||
queue.Acts.Packages = packagesFrom(mine.Node, queue, &composerNow)
|
||||
|
||||
+34
-15
@@ -27,7 +27,7 @@ import (
|
||||
// Silently doing something other than what was asked, and reporting success, is the fault this
|
||||
// project exists to name — so it gets defended here rather than remembered.
|
||||
|
||||
func TestAFlagAfterTheCommandIsRead(t *testing.T) {
|
||||
func testAFlagAfterTheCommandIsRead(t *testing.T) {
|
||||
command, opts, err := parseArgs([]string{"inventory", "--json"})
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
@@ -40,7 +40,7 @@ func TestAFlagAfterTheCommandIsRead(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestFlagsAreReadInEitherPosition(t *testing.T) {
|
||||
func testFlagsAreReadInEitherPosition(t *testing.T) {
|
||||
for _, args := range [][]string{
|
||||
{"profile", "--json", "--timeout", "3s"},
|
||||
{"profile", "--timeout=3s", "--json"},
|
||||
@@ -55,7 +55,7 @@ func TestFlagsAreReadInEitherPosition(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAMistypedFlagIsRefusedNotIgnored(t *testing.T) {
|
||||
func testAMistypedFlagIsRefusedNotIgnored(t *testing.T) {
|
||||
// The cost of getting this wrong is asymmetric: an error is a moment's annoyance, and a
|
||||
// silently dropped flag is a report that answers a question nobody asked.
|
||||
if _, _, err := parseArgs([]string{"profile", "--jsom"}); err == nil {
|
||||
@@ -63,13 +63,13 @@ func TestAMistypedFlagIsRefusedNotIgnored(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnUnexpectedArgumentIsRefused(t *testing.T) {
|
||||
func testAnUnexpectedArgumentIsRefused(t *testing.T) {
|
||||
if _, _, err := parseArgs([]string{"profile", "extra"}); err == nil {
|
||||
t.Fatal("a stray argument was ignored rather than refused")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheDefaultsAreTheDocumentedOnes(t *testing.T) {
|
||||
func testTheDefaultsAreTheDocumentedOnes(t *testing.T) {
|
||||
// The usage text promises 10s. A default that drifts from what is printed is a small lie
|
||||
// that costs someone an afternoon.
|
||||
_, opts, err := parseArgs([]string{"profile"})
|
||||
@@ -84,7 +84,7 @@ func TestTheDefaultsAreTheDocumentedOnes(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestNoCommandIsNotAnError(t *testing.T) {
|
||||
func testNoCommandIsNotAnError(t *testing.T) {
|
||||
// Running the binary with no arguments prints usage and exits 0. A host that returns
|
||||
// failure for "tell me what you do" is noise in every script that probes it.
|
||||
command, _, err := parseArgs(nil)
|
||||
@@ -96,7 +96,7 @@ func TestNoCommandIsNotAnError(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheStateHasADocumentedDefault(t *testing.T) {
|
||||
func testTheStateHasADocumentedDefault(t *testing.T) {
|
||||
// A host that wrote its state somewhere unexpected would forget what it owns on the next
|
||||
// run, and then leave everything it had applied behind forever.
|
||||
_, opts, err := parseArgs([]string{"owned"})
|
||||
@@ -108,7 +108,7 @@ func TestTheStateHasADocumentedDefault(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAFlagAfterAPositionalIsRead(t *testing.T) {
|
||||
func testAFlagAfterAPositionalIsRead(t *testing.T) {
|
||||
// The same fault as TestAFlagAfterTheCommandIsRead, one level down. Taking the subcommand
|
||||
// off the front fixed the flag after the COMMAND and not the flag after its ARGUMENT: the
|
||||
// standard library stops at the first non-flag argument wherever that argument is.
|
||||
@@ -132,7 +132,7 @@ func TestAFlagAfterAPositionalIsRead(t *testing.T) {
|
||||
// Defends the node's own record: the link and the reconcile loop both apply, and each reads the
|
||||
// state, acts, and writes it back — so they must not run at the same time, or the last save loses
|
||||
// what the other recorded.
|
||||
func TestOnlyOneApplyRunsAtATime(t *testing.T) {
|
||||
func testOnlyOneApplyRunsAtATime(t *testing.T) {
|
||||
// Issue 1585: the engine's stop waits for the apply in flight to end and save, and then lets no save start; before,
|
||||
// the process ended under it and a save cut before its rename left its temporary file and the state before it.
|
||||
t.Run("the stop waits for the apply in flight and its save", func(t *testing.T) {
|
||||
@@ -242,7 +242,7 @@ func stateWithMode(t *testing.T, mode string) options {
|
||||
return opts
|
||||
}
|
||||
|
||||
func TestAConvergedDeclarationIsRefusedOnAnAdoptedNode(t *testing.T) {
|
||||
func testAConvergedDeclarationIsRefusedOnAnAdoptedNode(t *testing.T) {
|
||||
opts := stateWithMode(t, store.ModeAdopted)
|
||||
path := filepath.Join(filepath.Dir(opts.state), "filter.conf")
|
||||
raw := []byte(`{"declaration":1,"resources":[{"id":"filter","type":"file","path":"` + path +
|
||||
@@ -266,7 +266,7 @@ func TestAConvergedDeclarationIsRefusedOnAnAdoptedNode(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheKeptDeclarationRepairsARecordThatDisagrees(t *testing.T) {
|
||||
func testTheKeptDeclarationRepairsARecordThatDisagrees(t *testing.T) {
|
||||
// What a node kept is signed by the mesh and verified on load; the state's note of the mode is
|
||||
// the host's own. A genesis re-run after `converge`, or a state saved when the kept declaration
|
||||
// could not be, leaves them apart — and a loop that refused every five minutes would hold the
|
||||
@@ -286,7 +286,7 @@ func TestTheKeptDeclarationRepairsARecordThatDisagrees(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheMeshItselfMayChangeTheMode(t *testing.T) {
|
||||
func testTheMeshItselfMayChangeTheMode(t *testing.T) {
|
||||
// The flip is a declaration: `converge` on the controller records the mode and sends the
|
||||
// first converged declaration. Delivered by the link, signed, it is not held to the record —
|
||||
// it becomes it. (With no system linked in, the apply is refused later for that; what this
|
||||
@@ -304,7 +304,7 @@ func TestTheMeshItselfMayChangeTheMode(t *testing.T) {
|
||||
// both — and `apply FILE` is refused altogether once the mesh has spoken, the last declaration
|
||||
// itself included: from a file it is applied as the bundle is, which would record the mesh's
|
||||
// resources as this machine's own and remove the foundation as undeclared.
|
||||
func TestAnOlderDeclarationIsRefused(t *testing.T) {
|
||||
func testAnOlderDeclarationIsRefused(t *testing.T) {
|
||||
opts := stateWithMode(t, "")
|
||||
genesis := []byte(`{"declaration":1,"resources":[{"id":"g","type":"file","path":"/tmp/g","content":"genesis\n"}]}`)
|
||||
since := []byte(`{"declaration":1,"resources":[{"id":"g","type":"file","path":"/tmp/g","content":"since\n"}]}`)
|
||||
@@ -364,7 +364,7 @@ func TestAnOlderDeclarationIsRefused(t *testing.T) {
|
||||
|
||||
// Defends novox/hq issue 104: what an apply would change is said before anything is, and
|
||||
// `--dry-run` is that and nothing else — an action listed as the action it is.
|
||||
func TestADryRunChangesNothingAndListsTheActions(t *testing.T) {
|
||||
func testADryRunChangesNothingAndListsTheActions(t *testing.T) {
|
||||
opts := stateWithMode(t, "")
|
||||
opts.dryRun = true
|
||||
out := &bytes.Buffer{}
|
||||
@@ -420,7 +420,7 @@ func TestADryRunChangesNothingAndListsTheActions(t *testing.T) {
|
||||
// **It cannot catch the fault it was written for** — a call site passing nil directly — because that is
|
||||
// wiring, and wiring is only proved by running the thing. That proof is a deployed host whose journal
|
||||
// carries the apply's detail, which is how this fix was verified.
|
||||
func TestTheApplysLogIsNeverNil(t *testing.T) {
|
||||
func testTheApplysLogIsNeverNil(t *testing.T) {
|
||||
if announceOr(nil) == nil {
|
||||
t.Fatal("a host with nowhere to say things got a nil log, which the apply will call")
|
||||
}
|
||||
@@ -432,3 +432,22 @@ func TestTheApplysLogIsNeverNil(t *testing.T) {
|
||||
t.Fatalf("the apply's detail did not reach the caller's announce: %v", said)
|
||||
}
|
||||
}
|
||||
|
||||
// TestMain runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestMain(t *testing.T) {
|
||||
t.Run("AFlagAfterTheCommandIsRead", testAFlagAfterTheCommandIsRead)
|
||||
t.Run("FlagsAreReadInEitherPosition", testFlagsAreReadInEitherPosition)
|
||||
t.Run("AMistypedFlagIsRefusedNotIgnored", testAMistypedFlagIsRefusedNotIgnored)
|
||||
t.Run("AnUnexpectedArgumentIsRefused", testAnUnexpectedArgumentIsRefused)
|
||||
t.Run("TheDefaultsAreTheDocumentedOnes", testTheDefaultsAreTheDocumentedOnes)
|
||||
t.Run("NoCommandIsNotAnError", testNoCommandIsNotAnError)
|
||||
t.Run("TheStateHasADocumentedDefault", testTheStateHasADocumentedDefault)
|
||||
t.Run("AFlagAfterAPositionalIsRead", testAFlagAfterAPositionalIsRead)
|
||||
t.Run("OnlyOneApplyRunsAtATime", testOnlyOneApplyRunsAtATime)
|
||||
t.Run("AConvergedDeclarationIsRefusedOnAnAdoptedNode", testAConvergedDeclarationIsRefusedOnAnAdoptedNode)
|
||||
t.Run("TheKeptDeclarationRepairsARecordThatDisagrees", testTheKeptDeclarationRepairsARecordThatDisagrees)
|
||||
t.Run("TheMeshItselfMayChangeTheMode", testTheMeshItselfMayChangeTheMode)
|
||||
t.Run("AnOlderDeclarationIsRefused", testAnOlderDeclarationIsRefused)
|
||||
t.Run("ADryRunChangesNothingAndListsTheActions", testADryRunChangesNothingAndListsTheActions)
|
||||
t.Run("TheApplysLogIsNeverNil", testTheApplysLogIsNeverNil)
|
||||
}
|
||||
|
||||
@@ -82,7 +82,7 @@ func aMoveOf(t *testing.T, key identity.SealingKey) link.MoveSecret {
|
||||
|
||||
// The engine opens what was sealed to its machine, hands it to the vault sealed to the call's key — never in the
|
||||
// clear — and answers what the vault kept only once the read-back opens to the same value.
|
||||
func TestTheEngineMovesAValueSealedToItAndChecksTheReadBack(t *testing.T) {
|
||||
func testTheEngineMovesAValueSealedToItAndChecksTheReadBack(t *testing.T) {
|
||||
key, err := identity.GenerateSealingKey()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -107,7 +107,7 @@ func TestTheEngineMovesAValueSealedToItAndChecksTheReadBack(t *testing.T) {
|
||||
|
||||
// A read-back that is not the value handed in is a failed move, said; so is a value this machine cannot open, and
|
||||
// the vault's refusal.
|
||||
func TestTheEngineSaysAMoveThatDidNotHold(t *testing.T) {
|
||||
func testTheEngineSaysAMoveThatDidNotHold(t *testing.T) {
|
||||
key, _ := identity.GenerateSealingKey()
|
||||
vault := &standInVault{t: t, lie: "something-else"}
|
||||
if _, err := moveIntoTheVault(vault.ask, key, aMoveOf(t, key)); err == nil ||
|
||||
@@ -159,3 +159,9 @@ func TestTheEngineSaysAMoveThatDidNotHold(t *testing.T) {
|
||||
t.Errorf("the pair's first step named %v", ends.opened)
|
||||
}
|
||||
}
|
||||
|
||||
// TestMovesecret runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestMovesecret(t *testing.T) {
|
||||
t.Run("TheEngineMovesAValueSealedToItAndChecksTheReadBack", testTheEngineMovesAValueSealedToItAndChecksTheReadBack)
|
||||
t.Run("TheEngineSaysAMoveThatDidNotHold", testTheEngineSaysAMoveThatDidNotHold)
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ import (
|
||||
// The machine's networking in the engine's statement (novox/hq ADR 0241): the file judged is the one the
|
||||
// uplink holder declares whole, the mesh name asked is the bus's, and the statement carries the parts.
|
||||
|
||||
func TestTheResolverFileJudgedIsTheOneAModuleDeclaresWhole(t *testing.T) {
|
||||
func testTheResolverFileJudgedIsTheOneAModuleDeclaresWhole(t *testing.T) {
|
||||
d := &declaration.Declaration{Resources: []declaration.Resource{
|
||||
&declaration.File{ID: "hosts.file", Type: "file", Path: "/etc/hosts", Content: "x"},
|
||||
&declaration.File{ID: "networkmanager.resolv", Type: "file", Path: network.ResolvConf, Content: "nameserver 10.10.0.1\n"},
|
||||
@@ -30,7 +30,7 @@ func TestTheResolverFileJudgedIsTheOneAModuleDeclaresWhole(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheMeshNameAskedIsTheBuses(t *testing.T) {
|
||||
func testTheMeshNameAskedIsTheBuses(t *testing.T) {
|
||||
for broker, want := range map[string]string{"anchor.internal:4222": "anchor.internal", "192.0.2.10:5671": "",
|
||||
"anchor.internal": "anchor.internal", "[2001:db8::1]:4222": ""} {
|
||||
if got := hostOf(broker); got != want {
|
||||
@@ -39,7 +39,7 @@ func TestTheMeshNameAskedIsTheBuses(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheStatementCarriesTheNetwork(t *testing.T) {
|
||||
func testTheStatementCarriesTheNetwork(t *testing.T) {
|
||||
at := time.Date(2026, 10, 7, 12, 0, 0, 0, time.UTC)
|
||||
h := healthAsReported(liveness.Statement{At: at}, &network.Statement{State: network.Unhealthy, Since: at,
|
||||
Parts: []network.Part{{Part: network.PartResolvConf, State: network.Unhealthy, Writer: "FortiClient",
|
||||
@@ -52,3 +52,10 @@ func TestTheStatementCarriesTheNetwork(t *testing.T) {
|
||||
t.Fatal("an engine with no network judge said a network")
|
||||
}
|
||||
}
|
||||
|
||||
// TestNetwork runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestNetwork(t *testing.T) {
|
||||
t.Run("TheResolverFileJudgedIsTheOneAModuleDeclaresWhole", testTheResolverFileJudgedIsTheOneAModuleDeclaresWhole)
|
||||
t.Run("TheMeshNameAskedIsTheBuses", testTheMeshNameAskedIsTheBuses)
|
||||
t.Run("TheStatementCarriesTheNetwork", testTheStatementCarriesTheNetwork)
|
||||
}
|
||||
|
||||
@@ -109,7 +109,7 @@ func (h sessionHaves) ReadErr(ctx context.Context, module string) (agent.Have, b
|
||||
return agent.Have{}, false, err
|
||||
}
|
||||
return agent.Have{Module: module, FP: got.Fp, Composed: got.Composed, Phase: string(got.Phase), Detail: got.Detail,
|
||||
Sealed: got.SealedAt, Wait: got.Wait}, true, nil
|
||||
Sealed: got.SealedAt, Wait: got.Wait, Run: got.Run, Pipeline: got.Pipeline}, true, nil
|
||||
}
|
||||
|
||||
func (h sessionHaves) Write(ctx context.Context, x agent.Have) {
|
||||
@@ -126,7 +126,7 @@ func (h sessionHaves) Write(ctx context.Context, x agent.Have) {
|
||||
}
|
||||
h.session.NoteModule(ctx, link.ModuleFact{Module: x.Module, FP: x.FP, Composed: x.Composed, Phase: phase,
|
||||
Failed: phase == string(nodeengineclient.PhaseFailed), Detail: shorten(x.Detail), Judgement: x.Judgement, Waits: x.Waits,
|
||||
BuildAlone: x.BuildAlone, Kept: x.Kept, Sealed: x.Sealed, PullWait: x.PullWait, Wait: x.Wait})
|
||||
BuildAlone: x.BuildAlone, Kept: x.Kept, Sealed: x.Sealed, PullWait: x.PullWait, Wait: x.Wait, Run: x.Run, Pipeline: x.Pipeline})
|
||||
}
|
||||
|
||||
func (h sessionHaves) Removed(ctx context.Context, module string) {
|
||||
@@ -253,6 +253,21 @@ func awaitBackup(ctx context.Context, events <-chan []byte, node, module string,
|
||||
}
|
||||
}
|
||||
|
||||
// convergeDirectories gives each directory entry of runs that this node's record holds, drifted on disk, its declared
|
||||
// owner and mode (apply.ConvergeDirectories, H-A-374, H-A-392): one line per directory, and one when the record or the
|
||||
// composition does not read.
|
||||
func convergeDirectories(statePath string, runs compositions.Composed) []string {
|
||||
d, err := declarationOf(runs)
|
||||
if err != nil {
|
||||
return []string{fmt.Sprintf("the directories of %s are not judged at this start: its composition does not read: %v", runs.Module, err)}
|
||||
}
|
||||
known, err := store.Load(statePath)
|
||||
if err != nil {
|
||||
return []string{fmt.Sprintf("the directories of %s are not judged at this start: %v", runs.Module, err)}
|
||||
}
|
||||
return apply.ConvergeDirectories(d, known)
|
||||
}
|
||||
|
||||
// declarationOf is the declaration the compositions make together: their resources, and the node's own parts when the
|
||||
// node's composition is among them. It is what the node judges and says its health by, and what one module's apply is
|
||||
// made of (with a single composition).
|
||||
@@ -536,6 +551,28 @@ func nodeAgent(ctx context.Context, opts options, signer ed25519.PublicKey, trus
|
||||
Backup: backupNode(session),
|
||||
// What the filling refused before this apply may be named now: the provisioner's client is told to fill
|
||||
// again (ace, 2026-10-25 21:17).
|
||||
// A module taken as running at this start has each record-held directory entry of it given its owner and mode
|
||||
// where they drifted on disk, one line each (H-A-374, H-A-392).
|
||||
TakenAtStart: func(module string, runs compositions.Composed) {
|
||||
for _, line := range convergeDirectories(opts.state, runs) {
|
||||
say(line)
|
||||
}
|
||||
},
|
||||
DirectoryDrift: func(runs compositions.Composed) []nodeengine.CompositionAnswerDriftItem {
|
||||
d, err := declarationOf(runs)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
known, err := store.Load(opts.state)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
var out []nodeengine.CompositionAnswerDriftItem
|
||||
for _, x := range apply.DirectoryDrifts(d, known) {
|
||||
out = append(out, nodeengine.CompositionAnswerDriftItem{ID: x.ID, Path: x.Path, Drift: x.Drift})
|
||||
}
|
||||
return out
|
||||
},
|
||||
Settled: func(module string) {
|
||||
knockFilling(module+" settled", say)
|
||||
judgeWhatRunsNow(opts.state, signer)
|
||||
@@ -1241,6 +1278,8 @@ func composerEnv(session *link.Session, node string, say func(string), hooks com
|
||||
return session.AskSeat(ctx, nodepacketfilter.Seat, nodepacketfilter.VerbAllowed, nodepacketfilter.AllowedInput{}, within)
|
||||
}
|
||||
env.ComposeAskBound = composeAskBound()
|
||||
// And the state taken, where an ask of the seat's verbs is taken once by its id (design 47 H2 §775, H-A-364).
|
||||
env.Taken = session.TakeOnce
|
||||
return env
|
||||
}
|
||||
|
||||
|
||||
@@ -866,7 +866,7 @@ func h8candidate(t *testing.T, b *itBed, fp, running string) {
|
||||
before, _ := b.composed.Status()
|
||||
// A-237c: asked with input and no call token (the checker's, until G removes it, G-6 §321) an input past what one answer carries
|
||||
// is refused; asked with a token it is sent in chunks through the engine's call, whatever its size (A-237b).
|
||||
if over, err := composeCandidateFrom(itNode, &shadowNow)(key, true, "", nil); err != nil {
|
||||
if over, err := composeCandidateFrom(itNode, &shadowNow)(key, true, "", "", nil); err != nil {
|
||||
t.Fatal(err)
|
||||
} else if a, err := nec.DecodeAnswer(over.(json.RawMessage)); err != nil || a.Verdict != nec.Refused || !strings.Contains(a.Refused, "an answer on the bus carries") || a.Input != nil {
|
||||
t.Errorf("an input over the inline bound asked with no token answered %+v (%v)", a, err)
|
||||
@@ -900,7 +900,7 @@ func h8candidate(t *testing.T, b *itBed, fp, running string) {
|
||||
if len(file) <= 900<<10 || !json.Valid(file) {
|
||||
t.Errorf("the chunks held %d bytes, want a JSON input over 900 KiB", len(file))
|
||||
}
|
||||
got, err := composeCandidateFrom(itNode, &shadowNow)(key, false, "", nil)
|
||||
got, err := composeCandidateFrom(itNode, &shadowNow)(key, false, "", "", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -64,7 +64,7 @@ func waitFor(t *testing.T, what string, ok func() bool) {
|
||||
t.Fatalf("timed out: %s", what)
|
||||
}
|
||||
|
||||
func TestTheEngineStatesItsSealingKeyToTheVaultAtStartRetriesAndRestatesAChange(t *testing.T) {
|
||||
func testTheEngineStatesItsSealingKeyToTheVaultAtStartRetriesAndRestatesAChange(t *testing.T) {
|
||||
first, _ := identity.GenerateSealingKey()
|
||||
second, _ := identity.GenerateSealingKey()
|
||||
var mu sync.Mutex
|
||||
@@ -164,7 +164,7 @@ func asksAgainUntilItHearsTheVaultsKey(t *testing.T) {
|
||||
// The statement a host makes names this contract (issue 786), one above the vault's box. And the vault's key its
|
||||
// answer gives is kept; an answer without one (an older vault) or with no public key changes nothing (ADR 0547 clause
|
||||
// 9).
|
||||
func TestTheNodeKeyContractIsThirteen(t *testing.T) {
|
||||
func testTheNodeKeyContractIsThirteen(t *testing.T) {
|
||||
if link.NodeKeyContract != 13 {
|
||||
t.Errorf("NodeKeyContract %d", link.NodeKeyContract)
|
||||
}
|
||||
@@ -181,3 +181,9 @@ func TestTheNodeKeyContractIsThirteen(t *testing.T) {
|
||||
t.Fatalf("key %q, want the key", h.get())
|
||||
}
|
||||
}
|
||||
|
||||
// TestNodekey runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestNodekey(t *testing.T) {
|
||||
t.Run("TheEngineStatesItsSealingKeyToTheVaultAtStartRetriesAndRestatesAChange", testTheEngineStatesItsSealingKeyToTheVaultAtStartRetriesAndRestatesAChange)
|
||||
t.Run("TheNodeKeyContractIsThirteen", testTheNodeKeyContractIsThirteen)
|
||||
}
|
||||
|
||||
@@ -20,7 +20,7 @@ import (
|
||||
// Design 47 G §527, §634, A-149: the node-engine's own module is the module of its applied record at its own fingerprint,
|
||||
// and its finding writer is made, observing as that module, once the name is known: at once from the record, else when the
|
||||
// first composing names it. No name is fixed in code.
|
||||
func TestTheEnginesOwnNameIsReadFromItsAppliedRecordOrItsFirstComposing(t *testing.T) {
|
||||
func testTheEnginesOwnNameIsReadFromItsAppliedRecordOrItsFirstComposing(t *testing.T) {
|
||||
fp := "src2:" + strings.Repeat("a", 64)
|
||||
applied := appliedStoreFor(filepath.Join(t.TempDir(), "state", "state.json"))
|
||||
for module, f := range map[string]string{"node": "", "the-engine": fp, "other": "src2:" + strings.Repeat("b", 64)} {
|
||||
@@ -105,7 +105,7 @@ func TestTheEnginesOwnNameIsReadFromItsAppliedRecordOrItsFirstComposing(t *testi
|
||||
|
||||
// Design 47 H, H-A-60: how often an entry whose ask failed is asked again is the file the manifest's `entry-asks` feeds, five when it
|
||||
// holds nothing usable.
|
||||
func TestTheEntryAsksAreTheManifestsSetting(t *testing.T) {
|
||||
func testTheEntryAsksAreTheManifestsSetting(t *testing.T) {
|
||||
was := entryAsksFile
|
||||
defer func() { entryAsksFile = was }()
|
||||
for content, want := range map[string]int{"2\n": 2, "": 5, "0": 5, "x": 5} {
|
||||
@@ -125,7 +125,7 @@ func TestTheEntryAsksAreTheManifestsSetting(t *testing.T) {
|
||||
|
||||
// §633: the engine's bound for the first seat list is the file the manifest's `view-waits-minutes` feeds, five minutes
|
||||
// when it holds nothing usable.
|
||||
func TestTheViewWaitsBoundIsTheManifestsSetting(t *testing.T) {
|
||||
func testTheViewWaitsBoundIsTheManifestsSetting(t *testing.T) {
|
||||
was := viewWaitsFile
|
||||
defer func() { viewWaitsFile = was }()
|
||||
for content, want := range map[string]time.Duration{"2\n": 2 * time.Minute, "": 5 * time.Minute, "0": 5 * time.Minute, "x": 5 * time.Minute} {
|
||||
@@ -176,3 +176,10 @@ func TestTheViewWaitsBoundIsTheManifestsSetting(t *testing.T) {
|
||||
t.Errorf("no file gives %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestOwnname runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestOwnname(t *testing.T) {
|
||||
t.Run("TheEnginesOwnNameIsReadFromItsAppliedRecordOrItsFirstComposing", testTheEnginesOwnNameIsReadFromItsAppliedRecordOrItsFirstComposing)
|
||||
t.Run("TheEntryAsksAreTheManifestsSetting", testTheEntryAsksAreTheManifestsSetting)
|
||||
t.Run("TheViewWaitsBoundIsTheManifestsSetting", testTheViewWaitsBoundIsTheManifestsSetting)
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ import (
|
||||
// Defends novox/hq issue 233: a package manager that does not answer is said even when nothing declared
|
||||
// needs it — the apply is partial, never "applied" — and the report names it under one key, so the mesh
|
||||
// counts it as one failure that goes on.
|
||||
func TestAPackageManagerThatDoesNotAnswerIsSaidWithNoPackageDeclared(t *testing.T) {
|
||||
func testAPackageManagerThatDoesNotAnswerIsSaidWithNoPackageDeclared(t *testing.T) {
|
||||
unansweringPacman(t)
|
||||
dir := t.TempDir()
|
||||
opts := options{state: filepath.Join(dir, "state.json"), out: &strings.Builder{}}
|
||||
@@ -46,7 +46,7 @@ func TestAPackageManagerThatDoesNotAnswerIsSaidWithNoPackageDeclared(t *testing.
|
||||
|
||||
// A system whose probe asks the system itself, not a tool a resource needs, still refuses whole: nothing
|
||||
// the mesh declares can remove it, and nothing else stands between that host and the wrong machine.
|
||||
func TestASystemWithNoPackageManagerStillRefusesWhole(t *testing.T) {
|
||||
func testASystemWithNoPackageManagerStillRefusesWhole(t *testing.T) {
|
||||
t.Setenv("PATH", t.TempDir())
|
||||
sys, err := system.For("android")
|
||||
if err != nil {
|
||||
@@ -83,7 +83,7 @@ func pacmanAnsweringOnce(t *testing.T, conf string) {
|
||||
// installs its packages too**. The probe is asked again once the partial apply wrote something, and when it
|
||||
// answers the declaration is applied again over what the first pass left — the packages in this apply, not five
|
||||
// minutes later, and the report clean.
|
||||
func TestThePackagesGoInWhenTheApplyThatRestoresThePackageManagerWroteIt(t *testing.T) {
|
||||
func testThePackagesGoInWhenTheApplyThatRestoresThePackageManagerWroteIt(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
conf := filepath.Join(dir, "pacman.conf")
|
||||
pacmanAnsweringOnce(t, conf)
|
||||
@@ -108,7 +108,7 @@ func TestThePackagesGoInWhenTheApplyThatRestoresThePackageManagerWroteIt(t *test
|
||||
|
||||
// Defends decision (1) of the review of novox/hq issue 233: **a package manager that is not there at all still
|
||||
// refuses whole**. That is the host installed on the wrong machine, which the probe exists to catch.
|
||||
func TestAPackageManagerThatIsNotThereRefusesWhole(t *testing.T) {
|
||||
func testAPackageManagerThatIsNotThereRefusesWhole(t *testing.T) {
|
||||
t.Setenv("PATH", t.TempDir())
|
||||
was := builtFor
|
||||
builtFor = "arch"
|
||||
@@ -127,3 +127,11 @@ func TestAPackageManagerThatIsNotThereRefusesWhole(t *testing.T) {
|
||||
t.Error("the refused declaration touched the machine")
|
||||
}
|
||||
}
|
||||
|
||||
// TestProbe runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestProbe(t *testing.T) {
|
||||
t.Run("APackageManagerThatDoesNotAnswerIsSaidWithNoPackageDeclared", testAPackageManagerThatDoesNotAnswerIsSaidWithNoPackageDeclared)
|
||||
t.Run("ASystemWithNoPackageManagerStillRefusesWhole", testASystemWithNoPackageManagerStillRefusesWhole)
|
||||
t.Run("ThePackagesGoInWhenTheApplyThatRestoresThePackageManagerWroteIt", testThePackagesGoInWhenTheApplyThatRestoresThePackageManagerWroteIt)
|
||||
t.Run("APackageManagerThatIsNotThereRefusesWhole", testAPackageManagerThatIsNotThereRefusesWhole)
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ import (
|
||||
|
||||
// The record check reads the engine's applied state: a composition one of whose resources has no record there is not
|
||||
// recorded (issue 1945).
|
||||
func TestACompositionIsRecordedOnlyWhenEveryResourceIs(t *testing.T) {
|
||||
func testACompositionIsRecordedOnlyWhenEveryResourceIs(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "state.json")
|
||||
var s store.State
|
||||
s.Record(store.Applied{ID: "ca-trust.trust", Type: "file", Target: "/etc/ca"})
|
||||
@@ -34,7 +34,7 @@ func TestACompositionIsRecordedOnlyWhenEveryResourceIs(t *testing.T) {
|
||||
}
|
||||
|
||||
// The modules applied again are those with a missing resource, each once; one down but there is not among them.
|
||||
func TestTheModulesAppliedAgainAreThoseWithAMissingResource(t *testing.T) {
|
||||
func testTheModulesAppliedAgainAreThoseWithAMissingResource(t *testing.T) {
|
||||
t.Run("1957: the machine shows a resource not active", testTheMachineShowsAResourceNotActive)
|
||||
st := liveness.Statement{Resources: []liveness.State{
|
||||
{Resource: liveness.Resource{Module: "matrix", ID: "matrix.homeserver"}, State: liveness.Unhealthy, Missing: true},
|
||||
@@ -50,7 +50,7 @@ func TestTheModulesAppliedAgainAreThoseWithAMissingResource(t *testing.T) {
|
||||
// A module is applied again only for a resource newly missing: one still missing at the next change of the statement is
|
||||
// not acted on again, so a resource that cannot be made is not applied (and backed up) at every unrelated change. One
|
||||
// that comes back and goes again is newly missing again (the review of issue 1945).
|
||||
func TestOnlyANewlyMissingResourceAppliesItsModuleAgain(t *testing.T) {
|
||||
func testOnlyANewlyMissingResourceAppliesItsModuleAgain(t *testing.T) {
|
||||
t.Run("1957: a resource newly down is an edge", testOnlyAResourceNewlyDownIsAnEdge)
|
||||
missing := func(ids ...string) liveness.Statement {
|
||||
var st liveness.Statement
|
||||
@@ -79,7 +79,7 @@ func TestOnlyANewlyMissingResourceAppliesItsModuleAgain(t *testing.T) {
|
||||
|
||||
// A file the provisioner client fills is left to it by the apply and has no record until the client writes it: it does
|
||||
// not make its composition unrecorded (the review of issue 1945).
|
||||
func TestAFilledFileDoesNotMakeItsCompositionUnrecorded(t *testing.T) {
|
||||
func testAFilledFileDoesNotMakeItsCompositionUnrecorded(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "state.json")
|
||||
var s store.State
|
||||
s.Record(store.Applied{ID: "ca-trust.trust", Type: "file", Target: "/etc/ca"})
|
||||
@@ -93,3 +93,11 @@ func TestAFilledFileDoesNotMakeItsCompositionUnrecorded(t *testing.T) {
|
||||
t.Fatal("a filled file the client has not written made its composition unrecorded")
|
||||
}
|
||||
}
|
||||
|
||||
// TestRecorded runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestRecorded(t *testing.T) {
|
||||
t.Run("ACompositionIsRecordedOnlyWhenEveryResourceIs", testACompositionIsRecordedOnlyWhenEveryResourceIs)
|
||||
t.Run("TheModulesAppliedAgainAreThoseWithAMissingResource", testTheModulesAppliedAgainAreThoseWithAMissingResource)
|
||||
t.Run("OnlyANewlyMissingResourceAppliesItsModuleAgain", testOnlyANewlyMissingResourceAppliesItsModuleAgain)
|
||||
t.Run("AFilledFileDoesNotMakeItsCompositionUnrecorded", testAFilledFileDoesNotMakeItsCompositionUnrecorded)
|
||||
}
|
||||
|
||||
@@ -36,9 +36,9 @@ import (
|
||||
// says the events; the grants part composes the node's subjects from the manifest, so the test adds them to the node's grant.
|
||||
func TestNatsTheRecoveryStepAsksHearsBoundsAndCatchesUpOverTheBus(t *testing.T) {
|
||||
perms := nodegrant.For(itNode)
|
||||
perms.Publish = append(perms.Publish, "$JS.API.>", "$KV.mesh-host_bounds.>", "mesh.seat.mesh-recovery.call.*.node~"+itNode,
|
||||
perms.Publish = append(perms.Publish, "$JS.API.>", "$KV.mesh-host_bounds.>", "$KV."+link.TakenBucket+".>", "mesh.seat.mesh-recovery.call.*.node~"+itNode,
|
||||
"mesh.mod.db.tool.rebuild."+itNode)
|
||||
perms.Subscribe = append(perms.Subscribe, "mesh.seat.mesh-recovery.event.>", "$KV.mesh-host_bounds.>", "_INBOX.>", "$JS.ACK.>", "$JS.FC.>")
|
||||
perms.Subscribe = append(perms.Subscribe, "mesh.seat.mesh-recovery.event.>", "$KV.mesh-host_bounds.>", "$KV."+link.TakenBucket+".>", "_INBOX.>", "$JS.ACK.>", "$JS.FC.>")
|
||||
b := newItBedAs(t, perms)
|
||||
ctx := context.Background()
|
||||
|
||||
@@ -52,8 +52,10 @@ func TestNatsTheRecoveryStepAsksHearsBoundsAndCatchesUpOverTheBus(t *testing.T)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := js.CreateKeyValue(ctx, jetstream.KeyValueConfig{Bucket: link.BoundsBucket, History: 1, LimitMarkerTTL: time.Second}); err != nil {
|
||||
t.Fatal(err)
|
||||
for _, bucket := range []string{link.BoundsBucket, link.TakenBucket} {
|
||||
if _, err := js.CreateKeyValue(ctx, jetstream.KeyValueConfig{Bucket: bucket, History: 1, LimitMarkerTTL: time.Second}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
say := func(act, outcome string) {
|
||||
raw, _ := json.Marshal(meshrecovery.RestoredEvent{Act: act, Module: "db", Kept: "cache", Outcome: outcome, At: time.Now().UTC()})
|
||||
@@ -133,6 +135,23 @@ func TestNatsTheRecoveryStepAsksHearsBoundsAndCatchesUpOverTheBus(t *testing.T)
|
||||
say("old", meshrecovery.RestoredEventOutcomeFailed) // said before anyone listens: the last message of the subject
|
||||
session := b.startSession()
|
||||
r := recoveryEnv(session, nil)
|
||||
// Design 47 H2 §775, H-A-364: over the same session, an ask of the seat is taken once in the state taken: the first time,
|
||||
// and never again within its bound.
|
||||
for i, want := range []bool{true, false} {
|
||||
if took, err := session.TakeOnce(ctx, nodeengine.Seat, "ask-1", time.Minute); err != nil || took != want {
|
||||
t.Fatalf("take %d of ask-1: %v, %v; want %v", i+1, took, err, want)
|
||||
}
|
||||
}
|
||||
// H-A-458 (3): the write is bound by the ask's own context: an ask whose context ended keeps nothing, so the same id is
|
||||
// taken the first time once asked again within a live one.
|
||||
gone, end := context.WithCancel(ctx)
|
||||
end()
|
||||
if took, err := session.TakeOnce(gone, nodeengine.Seat, "ask-2", time.Minute); err == nil || took {
|
||||
t.Fatalf("a take of ask-2 whose context ended: %v, %v; want refused", took, err)
|
||||
}
|
||||
if took, err := session.TakeOnce(ctx, nodeengine.Seat, "ask-2", time.Minute); err != nil || !took {
|
||||
t.Fatalf("ask-2 asked again within a live context: %v, %v; want taken the first time", took, err)
|
||||
}
|
||||
|
||||
events, stop, err := r.Hear(ctx, "restored", "db", "cache")
|
||||
if err != nil {
|
||||
|
||||
@@ -35,7 +35,7 @@ func unansweringPacman(t *testing.T) {
|
||||
// Held to: a declaration that restores the file is applied while pacman does not answer. Only what needs
|
||||
// pacman fails, with the probe's words; the file is written and recorded. Written only with what the
|
||||
// node-engine had before the fix, so it lays over the commit before it, where it fails.
|
||||
func TestReplay233(t *testing.T) {
|
||||
func testReplay233(t *testing.T) {
|
||||
unansweringPacman(t)
|
||||
dir := t.TempDir()
|
||||
opts := options{state: filepath.Join(dir, "state.json")}
|
||||
@@ -78,7 +78,7 @@ func failedWords(failed map[string]string) []string {
|
||||
|
||||
// Defends novox/hq issue 233 at the machine: `mesh-host apply` applies what does not need the package
|
||||
// manager, and says the apply was partial with the probe's words — a non-zero exit, never "applied".
|
||||
func TestApplyByHandAppliesWhatDoesNotNeedAPackageManagerThatDoesNotAnswer(t *testing.T) {
|
||||
func testApplyByHandAppliesWhatDoesNotNeedAPackageManagerThatDoesNotAnswer(t *testing.T) {
|
||||
unansweringPacman(t)
|
||||
dir := t.TempDir()
|
||||
out := &bytes.Buffer{}
|
||||
@@ -107,3 +107,9 @@ func TestApplyByHandAppliesWhatDoesNotNeedAPackageManagerThatDoesNotAnswer(t *te
|
||||
t.Errorf("what was said before applying does not say the package manager does not answer:\n%s", out.String())
|
||||
}
|
||||
}
|
||||
|
||||
// TestReplay233File runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestReplay233File(t *testing.T) {
|
||||
t.Run("Replay233", testReplay233)
|
||||
t.Run("ApplyByHandAppliesWhatDoesNotNeedAPackageManagerThatDoesNotAnswer", testApplyByHandAppliesWhatDoesNotNeedAPackageManagerThatDoesNotAnswer)
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ import (
|
||||
|
||||
// The subject the engine hears for a store settling is the event its manifest consumes: the grants part grants an account
|
||||
// what its manifest consumes and nothing named in code (novox/hq ADR 0625 §4).
|
||||
func TestTheSettledEventIsTheManifestsConsume(t *testing.T) {
|
||||
func testTheSettledEventIsTheManifestsConsume(t *testing.T) {
|
||||
raw, err := os.ReadFile("../../module.json")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -29,7 +29,7 @@ func TestTheSettledEventIsTheManifestsConsume(t *testing.T) {
|
||||
|
||||
// The manifest claims the seat node-engine, says its findings on its own stream and hears the keeper's ask and the
|
||||
// node-engine seat's running (design 47 G §364, §387, §199).
|
||||
func TestTheManifestClaimsItsSeatAndSaysItsFindings(t *testing.T) {
|
||||
func testTheManifestClaimsItsSeatAndSaysItsFindings(t *testing.T) {
|
||||
raw, err := os.ReadFile("../../module.json")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -65,3 +65,9 @@ func TestTheManifestClaimsItsSeatAndSaysItsFindings(t *testing.T) {
|
||||
t.Errorf("version = %q, want MAJOR.MINOR 0.1 (§368, §411)", m.Version)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSettledManifest runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestSettledManifest(t *testing.T) {
|
||||
t.Run("TheSettledEventIsTheManifestsConsume", testTheSettledEventIsTheManifestsConsume)
|
||||
t.Run("TheManifestClaimsItsSeatAndSaysItsFindings", testTheManifestClaimsItsSeatAndSaysItsFindings)
|
||||
}
|
||||
|
||||
@@ -19,7 +19,7 @@ import (
|
||||
// The machine's failed units in the engine's statement (novox/hq issue 315): a module's is among the
|
||||
// resources, unhealthy, as that module's unit, naming it; the machine's own beside them; and an engine
|
||||
// not reading them says nothing of them.
|
||||
func TestTheStatementCarriesTheFailedUnits(t *testing.T) {
|
||||
func testTheStatementCarriesTheFailedUnits(t *testing.T) {
|
||||
at := time.Date(2026, 10, 8, 12, 0, 0, 0, time.UTC)
|
||||
us := &units.Statement{At: at, State: units.Degraded, Failed: []units.Failed{
|
||||
{Unit: "openrazer-daemon.service", Scope: units.ScopeUser, Load: "loaded", Result: "exit-code",
|
||||
@@ -55,7 +55,7 @@ func TestTheStatementCarriesTheFailedUnits(t *testing.T) {
|
||||
// Every resource that runs in an account's own service manager names the account, and so does the account
|
||||
// a module put in a group (novox/hq ADR 0254): the controller reads a unit that cannot run before a new login
|
||||
// by the two together. What the machine's own manager runs names none.
|
||||
func TestTheStatementNamesTheAccountsManager(t *testing.T) {
|
||||
func testTheStatementNamesTheAccountsManager(t *testing.T) {
|
||||
at := time.Date(2026, 10, 8, 12, 0, 0, 0, time.UTC)
|
||||
st := liveness.Statement{At: at, Resources: []liveness.State{
|
||||
{Resource: liveness.Resource{Module: "openrazer", ID: "openrazer.daemon", Kind: "service",
|
||||
@@ -82,7 +82,7 @@ func TestTheStatementNamesTheAccountsManager(t *testing.T) {
|
||||
|
||||
// An account declared never to become root (novox/hq ADR 0266) is said with root never, under the contract
|
||||
// that tells the controller this engine judges it; an account judged for its groups alone is not.
|
||||
func TestTheStatementSaysAnAccountJudgedForRoot(t *testing.T) {
|
||||
func testTheStatementSaysAnAccountJudgedForRoot(t *testing.T) {
|
||||
at := time.Date(2026, 10, 8, 12, 0, 0, 0, time.UTC)
|
||||
as := &accounts.Statement{At: at, Accounts: []accounts.Verdict{
|
||||
{Account: accounts.Account{Module: "claude-code", ID: "claude-code.agent", Name: "agent", Root: true},
|
||||
@@ -166,7 +166,7 @@ func TestTheStatementSaysAnAccountJudgedForRoot(t *testing.T) {
|
||||
|
||||
// A verdict waiting for the setuid search says how far it got, in the reason the root-free verb repeats and as
|
||||
// fields (novox/hq issue 361); a mount point, never a path the walk visited or found.
|
||||
func TestTheStatementSaysHowFarTheSetuidSearchGot(t *testing.T) {
|
||||
func testTheStatementSaysHowFarTheSetuidSearchGot(t *testing.T) {
|
||||
at := time.Date(2026, 10, 10, 1, 40, 0, 0, time.UTC)
|
||||
sp := &accounts.SearchProgress{Started: at, Filesystems: 3, Done: 1, Walking: "/home", Visited: 42, Found: 2,
|
||||
Kept: at, Finished: []accounts.SearchedFilesystem{{Mount: "/", Took: 90 * time.Second}}}
|
||||
@@ -185,3 +185,11 @@ func TestTheStatementSaysHowFarTheSetuidSearchGot(t *testing.T) {
|
||||
t.Fatalf("the fields: %+v", s)
|
||||
}
|
||||
}
|
||||
|
||||
// TestUnits runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestUnits(t *testing.T) {
|
||||
t.Run("TheStatementCarriesTheFailedUnits", testTheStatementCarriesTheFailedUnits)
|
||||
t.Run("TheStatementNamesTheAccountsManager", testTheStatementNamesTheAccountsManager)
|
||||
t.Run("TheStatementSaysAnAccountJudgedForRoot", testTheStatementSaysAnAccountJudgedForRoot)
|
||||
t.Run("TheStatementSaysHowFarTheSetuidSearchGot", testTheStatementSaysHowFarTheSetuidSearchGot)
|
||||
}
|
||||
|
||||
@@ -28,7 +28,7 @@ import (
|
||||
|
||||
const coreCredential = "the-provisioner-clients-bus-password-2025"
|
||||
|
||||
func TestNatsTheEngineFillsACoreCredentialFromTheVaultsBoxWithNoValueInTheClear(t *testing.T) {
|
||||
func testNatsTheEngineFillsACoreCredentialFromTheVaultsBoxWithNoValueInTheClear(t *testing.T) {
|
||||
url := os.Getenv("MESH_TEST_NATS")
|
||||
if url == "" {
|
||||
t.Skip("MESH_TEST_NATS unset")
|
||||
@@ -133,7 +133,7 @@ func TestNatsTheEngineFillsACoreCredentialFromTheVaultsBoxWithNoValueInTheClear(
|
||||
}
|
||||
|
||||
// The engine opens a value the controller sealed (the NaCl box) as before, and the vault's box, with one key.
|
||||
func TestTheEnginesOpenerOpensBothBoxes(t *testing.T) {
|
||||
func testTheEnginesOpenerOpensBothBoxes(t *testing.T) {
|
||||
state := filepath.Join(t.TempDir(), "state.json")
|
||||
key, _ := identity.GenerateSealingKey()
|
||||
if err := os.WriteFile(identity.SealingKeyPath(state), []byte(key.Private), 0o600); err != nil {
|
||||
@@ -151,3 +151,9 @@ func TestTheEnginesOpenerOpensBothBoxes(t *testing.T) {
|
||||
t.Errorf("the vault's box opened to %q, %v", got, err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestVaultboxNats runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestVaultboxNats(t *testing.T) {
|
||||
t.Run("NatsTheEngineFillsACoreCredentialFromTheVaultsBoxWithNoValueInTheClear", testNatsTheEngineFillsACoreCredentialFromTheVaultsBoxWithNoValueInTheClear)
|
||||
t.Run("TheEnginesOpenerOpensBothBoxes", testTheEnginesOpenerOpensBothBoxes)
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ import (
|
||||
// toolchain stamps no version — a build does not know what it will be called — so a delivered host
|
||||
// read as "development build" and the mesh could not tell which host a machine ran (04-ISSUES/161).
|
||||
|
||||
func TestADeliveredHostReadsItsVersionFromItsPath(t *testing.T) {
|
||||
func testADeliveredHostReadsItsVersionFromItsPath(t *testing.T) {
|
||||
// A delivered host lives at <libexec>/versions/<version>/<binary>.
|
||||
dir := t.TempDir()
|
||||
versioned := filepath.Join(dir, "versions", "637f65559d16")
|
||||
@@ -26,7 +26,7 @@ func TestADeliveredHostReadsItsVersionFromItsPath(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAHostPlacedByHandKeepsItsStamp(t *testing.T) {
|
||||
func testAHostPlacedByHandKeepsItsStamp(t *testing.T) {
|
||||
// The honest answer for one the mesh did not deliver — and every machine is in that state until
|
||||
// a delivery reaches it.
|
||||
if got := versionAt("/usr/bin/nox-mesh-host", "04a27ca"); got != "04a27ca" {
|
||||
@@ -34,7 +34,7 @@ func TestAHostPlacedByHandKeepsItsStamp(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestADirectoryThatIsNotAVersionIsNotReadAsOne(t *testing.T) {
|
||||
func testADirectoryThatIsNotAVersionIsNotReadAsOne(t *testing.T) {
|
||||
// A binary sitting anywhere else must not have its parent directory's name read as a version.
|
||||
for _, path := range []string{
|
||||
"/opt/somewhere/nox-mesh-host",
|
||||
@@ -46,3 +46,10 @@ func TestADirectoryThatIsNotAVersionIsNotReadAsOne(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestVersionFromPath runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestVersionFromPath(t *testing.T) {
|
||||
t.Run("ADeliveredHostReadsItsVersionFromItsPath", testADeliveredHostReadsItsVersionFromItsPath)
|
||||
t.Run("AHostPlacedByHandKeepsItsStamp", testAHostPlacedByHandKeepsItsStamp)
|
||||
t.Run("ADirectoryThatIsNotAVersionIsNotReadAsOne", testADirectoryThatIsNotAVersionIsNotReadAsOne)
|
||||
}
|
||||
|
||||
@@ -34,7 +34,7 @@ func aFileOf(module, id string) json.RawMessage {
|
||||
// What runs is the agent's compositions and the kept declaration's resources for each module the agent does not hold;
|
||||
// the node's own parts are the kept declaration's until the agent holds the node's composition (ADR 0539 §9). One module
|
||||
// under the agent must not make the rest invisible to the liveness, units, accounts, libraries, filling and the take act.
|
||||
func TestWhatRunsIsTheAgentsCompositionsAndTheKeptRest(t *testing.T) {
|
||||
func testWhatRunsIsTheAgentsCompositionsAndTheKeptRest(t *testing.T) {
|
||||
kept := &declaration.Declaration{Identities: []declaration.Identity{{Module: "db", Name: "mesh-db"}},
|
||||
Libraries: []declaration.Library{{Library: "media"}}}
|
||||
everything := []engcomp.Composed{
|
||||
@@ -62,7 +62,7 @@ func TestWhatRunsIsTheAgentsCompositionsAndTheKeptRest(t *testing.T) {
|
||||
}
|
||||
|
||||
// What the take act, the judgement of directories and the filling read is what runs, not the frozen kept declaration.
|
||||
func TestDeclaredNowReadsWhatRunsWhenTheAgentIsRunning(t *testing.T) {
|
||||
func testDeclaredNowReadsWhatRunsWhenTheAgentIsRunning(t *testing.T) {
|
||||
t.Run("a fill while the agent restarts", aFillWhileTheAgentRestartsIsWrittenAfterwards)
|
||||
setRunsHere(func(string, ed25519.PublicKey) (*declaration.Declaration, error) {
|
||||
return &declaration.Declaration{Version: 1, Resources: nil, Provisioner: "from-agent"}, nil
|
||||
@@ -167,7 +167,7 @@ func TestDeclaredNowReadsWhatRunsWhenTheAgentIsRunning(t *testing.T) {
|
||||
// 1945/AC17 (unit): a resource the node's own composition shares with a running module's composition is declared once,
|
||||
// the module's: the declaration joined of both names each file once, so the filling writes it; the node's own resources
|
||||
// no module declares stay. (Live from 2026-10-25 12:43: "2 resources declare X" on every node.)
|
||||
func TestTheNodesOwnCopyOfAModulesResourceIsLeftOut(t *testing.T) {
|
||||
func testTheNodesOwnCopyOfAModulesResourceIsLeftOut(t *testing.T) {
|
||||
own := engcomp.Composed{Node: "n1", Resources: []json.RawMessage{aFileOf("zsh", "rc"), aFileOf("mesh-wireguard", "conf")},
|
||||
Filled: []string{"/tmp/r6/zsh/rc"}}
|
||||
zsh := engcomp.Composed{Node: "n1", Module: "zsh", FP: "src2:aa", Resources: []json.RawMessage{aFileOf("zsh", "rc")},
|
||||
@@ -203,7 +203,7 @@ func TestTheNodesOwnCopyOfAModulesResourceIsLeftOut(t *testing.T) {
|
||||
|
||||
// 1945/AC18 (unit): the kept declaration's filled paths go to the module whose file is at each path, the node's own to
|
||||
// the node's; and what runs from it, joined with the node's composition, names them filled.
|
||||
func TestTheKeptDeclarationsFilledPathsGoToTheirModules(t *testing.T) {
|
||||
func testTheKeptDeclarationsFilledPathsGoToTheirModules(t *testing.T) {
|
||||
raw := []byte(`{"resources":[
|
||||
{"id":"claude-code.settings","type":"file","module":"claude-code","path":"/etc/cc.json"},
|
||||
{"id":"screen-lock.conf","type":"file","module":"screen-lock","path":"/etc/lock.conf"},
|
||||
@@ -231,7 +231,7 @@ func TestTheKeptDeclarationsFilledPathsGoToTheirModules(t *testing.T) {
|
||||
|
||||
// 1945/AC17 (unit, review): a resource of the node's own that shares only its target with a module's (another id: a
|
||||
// unit or a container of the same name) is not the module's, and is neither dropped nor left to be removed.
|
||||
func TestASharedTargetWithAnotherIDIsNotDropped(t *testing.T) {
|
||||
func testASharedTargetWithAnotherIDIsNotDropped(t *testing.T) {
|
||||
ownFile, _ := json.Marshal(map[string]any{"id": "host.zshrc", "type": "file", "path": "/tmp/r6/zsh/rc", "content": "x"})
|
||||
own := engcomp.Composed{Node: "n1", Resources: []json.RawMessage{ownFile}}
|
||||
zsh := engcomp.Composed{Node: "n1", Module: "zsh", FP: "src2:aa", Resources: []json.RawMessage{aFileOf("zsh", "rc")}}
|
||||
@@ -303,3 +303,12 @@ func aFillWhileTheAgentRestartsIsWrittenAfterwards(t *testing.T) {
|
||||
t.Fatalf("the kept view stays after the new agent holds the node: %v, %v", err, current.lastView())
|
||||
}
|
||||
}
|
||||
|
||||
// TestWhatruns runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestWhatruns(t *testing.T) {
|
||||
t.Run("WhatRunsIsTheAgentsCompositionsAndTheKeptRest", testWhatRunsIsTheAgentsCompositionsAndTheKeptRest)
|
||||
t.Run("DeclaredNowReadsWhatRunsWhenTheAgentIsRunning", testDeclaredNowReadsWhatRunsWhenTheAgentIsRunning)
|
||||
t.Run("TheNodesOwnCopyOfAModulesResourceIsLeftOut", testTheNodesOwnCopyOfAModulesResourceIsLeftOut)
|
||||
t.Run("TheKeptDeclarationsFilledPathsGoToTheirModules", testTheKeptDeclarationsFilledPathsGoToTheirModules)
|
||||
t.Run("ASharedTargetWithAnotherIDIsNotDropped", testASharedTargetWithAnotherIDIsNotDropped)
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ import (
|
||||
|
||||
// The first have this build writes proves it to the launcher; nothing else does — not a report about a declaration, not
|
||||
// a facts event, not the haves of another build (novox/hq ADR 0539 §9, ADR 0227 §8). R6-A AC7.
|
||||
func TestOnlyAHaveUnderThisBuildProvesIt(t *testing.T) {
|
||||
func testOnlyAHaveUnderThisBuildProvesIt(t *testing.T) {
|
||||
state := filepath.Join(t.TempDir(), "state.json")
|
||||
t.Setenv("MESH_HOST_LIBEXEC", t.TempDir())
|
||||
// Never the machine's own engine placed by hand: proving renews it (issue 356).
|
||||
@@ -65,7 +65,7 @@ func TestOnlyAHaveUnderThisBuildProvesIt(t *testing.T) {
|
||||
}
|
||||
|
||||
// Every verdict that stands is said, and a reconcile that has one says it unasked.
|
||||
func TestAStandingRollbackIsSaidOnEveryReport(t *testing.T) {
|
||||
func testAStandingRollbackIsSaidOnEveryReport(t *testing.T) {
|
||||
state := filepath.Join(t.TempDir(), "state.json")
|
||||
line := "2.0\t1.0\t1759744800\trolled-back\tit did not report within 600s of starting\n"
|
||||
if err := os.WriteFile(upgrade.RolledBackPath(state), []byte(line), 0o644); err != nil {
|
||||
@@ -80,7 +80,7 @@ func TestAStandingRollbackIsSaidOnEveryReport(t *testing.T) {
|
||||
|
||||
// The launcher running this host is known to have been replaced only when it certainly was: a shell
|
||||
// reading the launcher, from a file renamed over. Asked of a real process, not a model of one.
|
||||
func TestAReplacedLauncherIsSeen(t *testing.T) {
|
||||
func testAReplacedLauncherIsSeen(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "launch")
|
||||
if err := os.WriteFile(path, []byte("#!/bin/sh\nsleep 5\necho done\n"), 0o755); err != nil {
|
||||
@@ -110,3 +110,10 @@ func TestAReplacedLauncherIsSeen(t *testing.T) {
|
||||
t.Fatal("a process reading another script reads as this launcher")
|
||||
}
|
||||
}
|
||||
|
||||
// TestWitnessing runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestWitnessing(t *testing.T) {
|
||||
t.Run("OnlyAHaveUnderThisBuildProvesIt", testOnlyAHaveUnderThisBuildProvesIt)
|
||||
t.Run("AStandingRollbackIsSaidOnEveryReport", testAStandingRollbackIsSaidOnEveryReport)
|
||||
t.Run("AReplacedLauncherIsSeen", testAReplacedLauncherIsSeen)
|
||||
}
|
||||
|
||||
+12
-4
@@ -33,7 +33,7 @@ func bundle(t *testing.T) *declaration.Declaration {
|
||||
// The object store was foundation for months on the strength of "it cannot grant itself a bucket",
|
||||
// which answers half the test. The control plane never needed one, and nothing noticed because
|
||||
// nothing counted what the bundle holds.
|
||||
func TestTheBundleCarriesTheFoundationAndTheControlPlaneAndNothingElse(t *testing.T) {
|
||||
func testTheBundleCarriesTheFoundationAndTheControlPlaneAndNothingElse(t *testing.T) {
|
||||
var images []string
|
||||
for _, r := range bundle(t).Resources {
|
||||
c, ok := r.(*declaration.Container)
|
||||
@@ -59,7 +59,7 @@ func TestTheBundleCarriesTheFoundationAndTheControlPlaneAndNothingElse(t *testin
|
||||
|
||||
// The control plane is in the bundle, and the design overlooked it once by reasoning about
|
||||
// foundation services rather than counting containers (novox/hq 03-DESIGN/01-to-be/07).
|
||||
func TestTheControlPlaneIsCarriedToo(t *testing.T) {
|
||||
func testTheControlPlaneIsCarriedToo(t *testing.T) {
|
||||
for _, r := range bundle(t).Resources {
|
||||
if c, ok := r.(*declaration.Container); ok && strings.Contains(c.Image, "mesh-controller") {
|
||||
return
|
||||
@@ -71,7 +71,7 @@ func TestTheControlPlaneIsCarriedToo(t *testing.T) {
|
||||
|
||||
// One genesis bundle, on the bus the mesh runs on (novox/hq ADR 0331 §2). Two bundles let every bed
|
||||
// and README name the one that could not raise a mesh, for weeks (issue 146).
|
||||
func TestThereIsOneGenesisBundle(t *testing.T) {
|
||||
func testThereIsOneGenesisBundle(t *testing.T) {
|
||||
bundles, err := filepath.Glob("*.lock")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -83,7 +83,7 @@ func TestThereIsOneGenesisBundle(t *testing.T) {
|
||||
|
||||
// The control plane the bundle raises is given the bus, with the account the installer fills and
|
||||
// the certificate it pins (ADR 0331 §4); without it, it crash-loops for ever (issue 146).
|
||||
func TestTheControlPlaneIsGivenTheBus(t *testing.T) {
|
||||
func testTheControlPlaneIsGivenTheBus(t *testing.T) {
|
||||
for _, r := range bundle(t).Resources {
|
||||
c, ok := r.(*declaration.Container)
|
||||
if !ok || !strings.Contains(c.Image, "mesh-controller") {
|
||||
@@ -97,3 +97,11 @@ func TestTheControlPlaneIsGivenTheBus(t *testing.T) {
|
||||
}
|
||||
t.Fatal("nothing in the bundle starts the control plane")
|
||||
}
|
||||
|
||||
// TestBundle runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestBundle(t *testing.T) {
|
||||
t.Run("TheBundleCarriesTheFoundationAndTheControlPlaneAndNothingElse", testTheBundleCarriesTheFoundationAndTheControlPlaneAndNothingElse)
|
||||
t.Run("TheControlPlaneIsCarriedToo", testTheControlPlaneIsCarriedToo)
|
||||
t.Run("ThereIsOneGenesisBundle", testThereIsOneGenesisBundle)
|
||||
t.Run("TheControlPlaneIsGivenTheBus", testTheControlPlaneIsGivenTheBus)
|
||||
}
|
||||
|
||||
@@ -82,7 +82,7 @@ func look(t *testing.T, m *machine) Verdict {
|
||||
return st.Accounts[0]
|
||||
}
|
||||
|
||||
func TestAGroupTheRunningSessionLacksSaysReloginNeeded(t *testing.T) {
|
||||
func testAGroupTheRunningSessionLacksSaysReloginNeeded(t *testing.T) {
|
||||
m := &machine{t: t, proc: t.TempDir(), inDB: "operator wheel openrazer", pid: "4242", held: "998"}
|
||||
v := look(t, m)
|
||||
if v.State != Unhealthy || !strings.HasPrefix(v.Reason, ReasonRelogin) || !strings.Contains(v.Reason, "openrazer") ||
|
||||
@@ -101,21 +101,21 @@ func TestAGroupTheRunningSessionLacksSaysReloginNeeded(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestASessionThatHasTheGroupIsHealthy(t *testing.T) {
|
||||
func testASessionThatHasTheGroupIsHealthy(t *testing.T) {
|
||||
m := &machine{t: t, proc: t.TempDir(), inDB: "operator wheel openrazer", pid: "4242", held: "998 964"}
|
||||
if v := look(t, m); v.State != Healthy || v.Reason != "" {
|
||||
t.Fatalf("a session with the group: %+v", v)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNoSessionIsHealthyTheNextLoginTakesTheGroup(t *testing.T) {
|
||||
func testNoSessionIsHealthyTheNextLoginTakesTheGroup(t *testing.T) {
|
||||
m := &machine{t: t, proc: t.TempDir(), inDB: "operator openrazer", pid: "0"}
|
||||
if v := look(t, m); v.State != Healthy {
|
||||
t.Fatalf("no session: %+v", v)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnAccountTheDatabaseDoesNotListIsUnhealthySayingSo(t *testing.T) {
|
||||
func testAnAccountTheDatabaseDoesNotListIsUnhealthySayingSo(t *testing.T) {
|
||||
m := &machine{t: t, proc: t.TempDir(), inDB: "operator wheel", pid: "4242", held: "998"}
|
||||
v := look(t, m)
|
||||
if v.State != Unhealthy || !strings.HasPrefix(v.Reason, "not in the group openrazer") {
|
||||
@@ -123,14 +123,14 @@ func TestAnAccountTheDatabaseDoesNotListIsUnhealthySayingSo(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestADatabaseThatDoesNotAnswerIsUnknownNeverHealthy(t *testing.T) {
|
||||
func testADatabaseThatDoesNotAnswerIsUnknownNeverHealthy(t *testing.T) {
|
||||
m := &machine{t: t, proc: t.TempDir(), failsID: true}
|
||||
if v := look(t, m); v.State != Unknown {
|
||||
t.Fatalf("an unread database: %+v", v)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOnlyAModulesAccountWithGroupsIsJudged(t *testing.T) {
|
||||
func testOnlyAModulesAccountWithGroupsIsJudged(t *testing.T) {
|
||||
d, err := declaration.ParseTrusted([]byte(`{"declaration":1,"resources":[
|
||||
{"id":"zsh.login","type":"user","name":"operator","shell":"/bin/zsh"},
|
||||
{"id":"openrazer.account","type":"user","name":"operator","groups":["openrazer"]},
|
||||
@@ -146,7 +146,7 @@ func TestOnlyAModulesAccountWithGroupsIsJudged(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAVerdictThatHoldsCountsItsStreakAndAChangeIsSaid(t *testing.T) {
|
||||
func testAVerdictThatHoldsCountsItsStreakAndAChangeIsSaid(t *testing.T) {
|
||||
m := &machine{t: t, proc: t.TempDir(), inDB: "operator openrazer", pid: "4242", held: "998"}
|
||||
m.status()
|
||||
j := New(Exec{Run: m.run, Proc: m.proc})
|
||||
@@ -163,3 +163,14 @@ func TestAVerdictThatHoldsCountsItsStreakAndAChangeIsSaid(t *testing.T) {
|
||||
t.Fatalf("after the new login: changed %v, %+v", changed, st.Accounts[0])
|
||||
}
|
||||
}
|
||||
|
||||
// TestAccounts runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestAccounts(t *testing.T) {
|
||||
t.Run("AGroupTheRunningSessionLacksSaysReloginNeeded", testAGroupTheRunningSessionLacksSaysReloginNeeded)
|
||||
t.Run("ASessionThatHasTheGroupIsHealthy", testASessionThatHasTheGroupIsHealthy)
|
||||
t.Run("NoSessionIsHealthyTheNextLoginTakesTheGroup", testNoSessionIsHealthyTheNextLoginTakesTheGroup)
|
||||
t.Run("AnAccountTheDatabaseDoesNotListIsUnhealthySayingSo", testAnAccountTheDatabaseDoesNotListIsUnhealthySayingSo)
|
||||
t.Run("ADatabaseThatDoesNotAnswerIsUnknownNeverHealthy", testADatabaseThatDoesNotAnswerIsUnknownNeverHealthy)
|
||||
t.Run("OnlyAModulesAccountWithGroupsIsJudged", testOnlyAModulesAccountWithGroupsIsJudged)
|
||||
t.Run("AVerdictThatHoldsCountsItsStreakAndAChangeIsSaid", testAVerdictThatHoldsCountsItsStreakAndAChangeIsSaid)
|
||||
}
|
||||
|
||||
@@ -185,13 +185,13 @@ func lookAgent(t *testing.T, m *agentMachine) Verdict {
|
||||
return st.Accounts[0]
|
||||
}
|
||||
|
||||
func TestAnAgentAccountWithNoWayToRootIsHealthyWithNobodyLoggedIn(t *testing.T) {
|
||||
func testAnAgentAccountWithNoWayToRootIsHealthyWithNobodyLoggedIn(t *testing.T) {
|
||||
if v := lookAgent(t, clean()); v.State != Healthy || v.Reason != "" || !v.Root {
|
||||
t.Fatalf("no way to root: %+v", v)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEachWayToRootIsSaid(t *testing.T) {
|
||||
func testEachWayToRootIsSaid(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
set func(*agentMachine)
|
||||
@@ -222,7 +222,7 @@ func TestEachWayToRootIsSaid(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestEveryWayIsSaidAtOnce(t *testing.T) {
|
||||
func testEveryWayIsSaidAtOnce(t *testing.T) {
|
||||
m := clean()
|
||||
m.groups = "agent docker"
|
||||
m.sudo = "User agent may run the following commands on box:\n (ALL) ALL\n"
|
||||
@@ -232,7 +232,7 @@ func TestEveryWayIsSaidAtOnce(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnUnansweredQuestionIsUnknownNeverHealthy(t *testing.T) {
|
||||
func testAnUnansweredQuestionIsUnknownNeverHealthy(t *testing.T) {
|
||||
m := clean()
|
||||
m.failsID = true
|
||||
if v := lookAgent(t, m); v.State != Unknown {
|
||||
@@ -245,7 +245,7 @@ func TestAnUnansweredQuestionIsUnknownNeverHealthy(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestASecretNotThereYetIsNoWay(t *testing.T) {
|
||||
func testASecretNotThereYetIsNoWay(t *testing.T) {
|
||||
m := clean()
|
||||
delete(m.files, "/var/lib/mesh/node-tools/broker")
|
||||
if v := lookAgent(t, m); v.State != Healthy {
|
||||
@@ -253,7 +253,7 @@ func TestASecretNotThereYetIsNoWay(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSudoRules(t *testing.T) {
|
||||
func testSudoRules(t *testing.T) {
|
||||
none := []struct {
|
||||
out string
|
||||
err error
|
||||
@@ -276,14 +276,14 @@ func TestSudoRules(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadable(t *testing.T) {
|
||||
func testReadable(t *testing.T) {
|
||||
m := FileMode{UID: 1500, GID: 1500, Perm: 0o600}
|
||||
if Readable(m, 1600, map[int]bool{1600: true}) || !Readable(m, 1500, nil) || !Readable(m, 0, nil) {
|
||||
t.Fatal("owner bits")
|
||||
}
|
||||
}
|
||||
|
||||
func TestOfJudgesARootNeverAccountWithNoGroupsAndItsSecrets(t *testing.T) {
|
||||
func testOfJudgesARootNeverAccountWithNoGroupsAndItsSecrets(t *testing.T) {
|
||||
d, err := declaration.ParseTrusted([]byte(`{"declaration":1,"resources":[
|
||||
{"id":"claude-code.agent","type":"user","name":"agent","root":"never"},
|
||||
{"id":"zsh.login","type":"user","name":"operator","shell":"/bin/zsh"},
|
||||
@@ -300,3 +300,15 @@ func TestOfJudgesARootNeverAccountWithNoGroupsAndItsSecrets(t *testing.T) {
|
||||
t.Fatalf("judged: %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRoot runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestRoot(t *testing.T) {
|
||||
t.Run("AnAgentAccountWithNoWayToRootIsHealthyWithNobodyLoggedIn", testAnAgentAccountWithNoWayToRootIsHealthyWithNobodyLoggedIn)
|
||||
t.Run("EachWayToRootIsSaid", testEachWayToRootIsSaid)
|
||||
t.Run("EveryWayIsSaidAtOnce", testEveryWayIsSaidAtOnce)
|
||||
t.Run("AnUnansweredQuestionIsUnknownNeverHealthy", testAnUnansweredQuestionIsUnknownNeverHealthy)
|
||||
t.Run("ASecretNotThereYetIsNoWay", testASecretNotThereYetIsNoWay)
|
||||
t.Run("SudoRules", testSudoRules)
|
||||
t.Run("Readable", testReadable)
|
||||
t.Run("OfJudgesARootNeverAccountWithNoGroupsAndItsSecrets", testOfJudgesARootNeverAccountWithNoGroupsAndItsSecrets)
|
||||
}
|
||||
|
||||
@@ -66,7 +66,7 @@ func notJudged(t *testing.T, err error, pending bool) *SetuidNotJudged {
|
||||
return nj
|
||||
}
|
||||
|
||||
func TestTheSearchRunsToCompletionWithNoBound(t *testing.T) {
|
||||
func testTheSearchRunsToCompletionWithNoBound(t *testing.T) {
|
||||
c := &SetuidCache{}
|
||||
g := newGate()
|
||||
if _, _, err := c.Look(at, root, g.search); err == nil {
|
||||
@@ -90,7 +90,7 @@ func TestTheSearchRunsToCompletionWithNoBound(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAFreshCompleteSearchJudgesUntilItIsDue(t *testing.T) {
|
||||
func testAFreshCompleteSearchJudgesUntilItIsDue(t *testing.T) {
|
||||
c := &SetuidCache{}
|
||||
g := newGate()
|
||||
c.Look(at, root, g.search)
|
||||
@@ -111,7 +111,7 @@ func TestAFreshCompleteSearchJudgesUntilItIsDue(t *testing.T) {
|
||||
g.finish(c)
|
||||
}
|
||||
|
||||
func TestAStaleSearchIsNotJudgedNeverFree(t *testing.T) {
|
||||
func testAStaleSearchIsNotJudgedNeverFree(t *testing.T) {
|
||||
c := &SetuidCache{}
|
||||
g := newGate()
|
||||
c.Look(at, root, g.search)
|
||||
@@ -128,7 +128,7 @@ func TestAStaleSearchIsNotJudgedNeverFree(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnIncompleteSearchIsNeverFree(t *testing.T) {
|
||||
func testAnIncompleteSearchIsNeverFree(t *testing.T) {
|
||||
c := &SetuidCache{}
|
||||
g := newGate()
|
||||
g.err = errors.New("the search for setuid programs did not complete its walk")
|
||||
@@ -162,7 +162,7 @@ func TestAnIncompleteSearchIsNeverFree(t *testing.T) {
|
||||
g.finish(c)
|
||||
}
|
||||
|
||||
func TestAnApplyThatMovedRootSearchesAgain(t *testing.T) {
|
||||
func testAnApplyThatMovedRootSearchesAgain(t *testing.T) {
|
||||
c := &SetuidCache{}
|
||||
g := newGate()
|
||||
c.Look(at, root, g.search)
|
||||
@@ -198,7 +198,7 @@ func TestAnApplyThatMovedRootSearchesAgain(t *testing.T) {
|
||||
}
|
||||
|
||||
// A filesystem the last complete search did not walk is not judged by it: not judged yet, and a search starts.
|
||||
func TestAFilesystemTheSearchDidNotWalkIsNotJudgedByIt(t *testing.T) {
|
||||
func testAFilesystemTheSearchDidNotWalkIsNotJudgedByIt(t *testing.T) {
|
||||
c := &SetuidCache{}
|
||||
g := newGate()
|
||||
c.Look(at, root, g.search)
|
||||
@@ -216,7 +216,7 @@ func TestAFilesystemTheSearchDidNotWalkIsNotJudgedByIt(t *testing.T) {
|
||||
|
||||
// An ask to search again forgets the walk under way, so an engine restarted before the next search does not
|
||||
// carry on a walk that started before root acted.
|
||||
func TestAnAskToSearchAgainIsNotLostToARestart(t *testing.T) {
|
||||
func testAnAskToSearchAgainIsNotLostToARestart(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
paths := func() *SetuidCache {
|
||||
return &SetuidCache{Path: filepath.Join(dir, SetuidSearchFile), ProgressPath: filepath.Join(dir, SetuidProgressFile)}
|
||||
@@ -240,7 +240,7 @@ func TestAnAskToSearchAgainIsNotLostToARestart(t *testing.T) {
|
||||
|
||||
// A cursor whose name is not UTF-8 is kept as its bytes: JSON strings would change it, and the resumed walk
|
||||
// would skip what it stood before.
|
||||
func TestACursorOfAnyBytesIsKeptExactly(t *testing.T) {
|
||||
func testACursorOfAnyBytesIsKeptExactly(t *testing.T) {
|
||||
p := &SetuidProgress{Started: at, Mounts: Paths{"/"}, Cursor: Cursors{"/": "/home/agent/\x80/x"},
|
||||
Found: Paths{"/opt/\xff"}}
|
||||
var back SetuidProgress
|
||||
@@ -250,7 +250,7 @@ func TestACursorOfAnyBytesIsKeptExactly(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheCompleteSearchIsKeptAndReadAfterARestart(t *testing.T) {
|
||||
func testTheCompleteSearchIsKeptAndReadAfterARestart(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, SetuidSearchFile)
|
||||
c := &SetuidCache{Path: path}
|
||||
@@ -277,7 +277,7 @@ func TestTheCompleteSearchIsKeptAndReadAfterARestart(t *testing.T) {
|
||||
g2.finish(again)
|
||||
}
|
||||
|
||||
func TestAKeptSearchNotRootsAloneIsNotRead(t *testing.T) {
|
||||
func testAKeptSearchNotRootsAloneIsNotRead(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, SetuidSearchFile)
|
||||
c := &SetuidCache{Path: path}
|
||||
@@ -318,7 +318,7 @@ func TestAKeptSearchNotRootsAloneIsNotRead(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAKeptSearchFromTheFutureIsNotFresh(t *testing.T) {
|
||||
func testAKeptSearchFromTheFutureIsNotFresh(t *testing.T) {
|
||||
c := &SetuidCache{}
|
||||
g := newGate()
|
||||
c.Look(at, root, g.search)
|
||||
@@ -329,7 +329,7 @@ func TestAKeptSearchFromTheFutureIsNotFresh(t *testing.T) {
|
||||
g.finish(c)
|
||||
}
|
||||
|
||||
func TestTheIdleRunnerLowersItsCommand(t *testing.T) {
|
||||
func testTheIdleRunnerLowersItsCommand(t *testing.T) {
|
||||
if _, err := exec.LookPath("nice"); err != nil {
|
||||
t.Skip("no nice here")
|
||||
}
|
||||
@@ -373,7 +373,7 @@ func interrupted(seen chan<- *SetuidProgress) SetuidSearch {
|
||||
}
|
||||
}
|
||||
|
||||
func TestASearchInterruptedByARestartCarriesOnAndIsDatedByItsStart(t *testing.T) {
|
||||
func testASearchInterruptedByARestartCarriesOnAndIsDatedByItsStart(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
paths := func() *SetuidCache {
|
||||
return &SetuidCache{Path: filepath.Join(dir, SetuidSearchFile), ProgressPath: filepath.Join(dir, SetuidProgressFile)}
|
||||
@@ -406,7 +406,7 @@ func TestASearchInterruptedByARestartCarriesOnAndIsDatedByItsStart(t *testing.T)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAWalkTooOldOrAskedAgainStartsOver(t *testing.T) {
|
||||
func testAWalkTooOldOrAskedAgainStartsOver(t *testing.T) {
|
||||
for name, c := range map[string]struct {
|
||||
after time.Duration
|
||||
again bool
|
||||
@@ -434,7 +434,7 @@ func TestAWalkTooOldOrAskedAgainStartsOver(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestASearchWhosePriorityCannotBeLoweredDoesNotWalk(t *testing.T) {
|
||||
func testASearchWhosePriorityCannotBeLoweredDoesNotWalk(t *testing.T) {
|
||||
c := &SetuidCache{Lower: func() error { return errors.New("not permitted") }}
|
||||
walked := false
|
||||
c.Look(at, root, func(context.Context, *SetuidProgress, func()) ([]string, error) { walked = true; return nil, nil })
|
||||
@@ -445,3 +445,22 @@ func TestASearchWhosePriorityCannotBeLoweredDoesNotWalk(t *testing.T) {
|
||||
t.Fatal("it walked at full priority")
|
||||
}
|
||||
}
|
||||
|
||||
// TestSetuidCache runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestSetuidCache(t *testing.T) {
|
||||
t.Run("TheSearchRunsToCompletionWithNoBound", testTheSearchRunsToCompletionWithNoBound)
|
||||
t.Run("AFreshCompleteSearchJudgesUntilItIsDue", testAFreshCompleteSearchJudgesUntilItIsDue)
|
||||
t.Run("AStaleSearchIsNotJudgedNeverFree", testAStaleSearchIsNotJudgedNeverFree)
|
||||
t.Run("AnIncompleteSearchIsNeverFree", testAnIncompleteSearchIsNeverFree)
|
||||
t.Run("AnApplyThatMovedRootSearchesAgain", testAnApplyThatMovedRootSearchesAgain)
|
||||
t.Run("AFilesystemTheSearchDidNotWalkIsNotJudgedByIt", testAFilesystemTheSearchDidNotWalkIsNotJudgedByIt)
|
||||
t.Run("AnAskToSearchAgainIsNotLostToARestart", testAnAskToSearchAgainIsNotLostToARestart)
|
||||
t.Run("ACursorOfAnyBytesIsKeptExactly", testACursorOfAnyBytesIsKeptExactly)
|
||||
t.Run("TheCompleteSearchIsKeptAndReadAfterARestart", testTheCompleteSearchIsKeptAndReadAfterARestart)
|
||||
t.Run("AKeptSearchNotRootsAloneIsNotRead", testAKeptSearchNotRootsAloneIsNotRead)
|
||||
t.Run("AKeptSearchFromTheFutureIsNotFresh", testAKeptSearchFromTheFutureIsNotFresh)
|
||||
t.Run("TheIdleRunnerLowersItsCommand", testTheIdleRunnerLowersItsCommand)
|
||||
t.Run("ASearchInterruptedByARestartCarriesOnAndIsDatedByItsStart", testASearchInterruptedByARestartCarriesOnAndIsDatedByItsStart)
|
||||
t.Run("AWalkTooOldOrAskedAgainStartsOver", testAWalkTooOldOrAskedAgainStartsOver)
|
||||
t.Run("ASearchWhosePriorityCannotBeLoweredDoesNotWalk", testASearchWhosePriorityCannotBeLoweredDoesNotWalk)
|
||||
}
|
||||
|
||||
@@ -76,7 +76,7 @@ func (f *fakePace) paused() time.Duration {
|
||||
return total
|
||||
}
|
||||
|
||||
func TestTheWalkPausesWhileTheDiskIsUnderPressureAndGoesOnWhenItEases(t *testing.T) {
|
||||
func testTheWalkPausesWhileTheDiskIsUnderPressureAndGoesOnWhenItEases(t *testing.T) {
|
||||
f := newFake(60, 40, 3)
|
||||
pc := f.pacer()
|
||||
if err := pc.yield(t.Context()); err != nil { // the first look sets where the counter counts from
|
||||
@@ -92,7 +92,7 @@ func TestTheWalkPausesWhileTheDiskIsUnderPressureAndGoesOnWhenItEases(t *testing
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheFirstLookOnlySetsWhereTheNextCountsFrom(t *testing.T) {
|
||||
func testTheFirstLookOnlySetsWhereTheNextCountsFrom(t *testing.T) {
|
||||
f := newFake(99)
|
||||
if err := f.pacer().yield(t.Context()); err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -102,7 +102,7 @@ func TestTheFirstLookOnlySetsWhereTheNextCountsFrom(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheWalkDoesNotPauseOnAQuietDisk(t *testing.T) {
|
||||
func testTheWalkDoesNotPauseOnAQuietDisk(t *testing.T) {
|
||||
f := newFake(0.4)
|
||||
pc := f.pacer()
|
||||
for range 10 {
|
||||
@@ -117,7 +117,7 @@ func TestTheWalkDoesNotPauseOnAQuietDisk(t *testing.T) {
|
||||
}
|
||||
|
||||
// The control-node's own load sits near the bound with no walk running: the walk must still end (issue 361).
|
||||
func TestTheWalkKeepsATenthOfTheTimeWhateverThePressure(t *testing.T) {
|
||||
func testTheWalkKeepsATenthOfTheTimeWhateverThePressure(t *testing.T) {
|
||||
f := newFake(100)
|
||||
pc := f.pacer()
|
||||
var read time.Duration
|
||||
@@ -140,7 +140,7 @@ func TestTheWalkKeepsATenthOfTheTimeWhateverThePressure(t *testing.T) {
|
||||
// control-node on 2026-10-11, slowed to its worst, still completes well inside the time the controller stays quiet
|
||||
// while it waits for a search. A guard on the constants only: that the code keeps to the ratio is proven by
|
||||
// TestTheWalkKeepsATenthOfTheTimeWhateverThePressure.
|
||||
func TestTheSlowestPacedWalkStillJudgesInTime(t *testing.T) {
|
||||
func testTheSlowestPacedWalkStillJudgesInTime(t *testing.T) {
|
||||
const unpaced = 16*time.Minute + 31*time.Second
|
||||
worst := (1 + PaceRatio) * unpaced
|
||||
if worst >= rootsearch.Quiet {
|
||||
@@ -149,7 +149,7 @@ func TestTheSlowestPacedWalkStillJudgesInTime(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestARunOfPausesIsAtMostPaceAtMost(t *testing.T) {
|
||||
func testARunOfPausesIsAtMostPaceAtMost(t *testing.T) {
|
||||
f := newFake(100)
|
||||
pc := f.pacer()
|
||||
if err := pc.yield(t.Context()); err != nil {
|
||||
@@ -164,7 +164,7 @@ func TestARunOfPausesIsAtMostPaceAtMost(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheWalkLooksAtThePressureAtMostEveryPaceLook(t *testing.T) {
|
||||
func testTheWalkLooksAtThePressureAtMostEveryPaceLook(t *testing.T) {
|
||||
f := newFake(1)
|
||||
pc := f.pacer()
|
||||
for range 5 {
|
||||
@@ -186,7 +186,7 @@ func TestTheWalkLooksAtThePressureAtMostEveryPaceLook(t *testing.T) {
|
||||
}
|
||||
|
||||
// Pressure that cannot be read pauses nothing, and is said once, with what it means, rather than at every look.
|
||||
func TestAPressureThatCannotBeReadIsSaidOnce(t *testing.T) {
|
||||
func testAPressureThatCannotBeReadIsSaidOnce(t *testing.T) {
|
||||
f := newFake(0)
|
||||
f.fail = errors.New("no such file")
|
||||
pc := f.pacer()
|
||||
@@ -205,7 +205,7 @@ func TestAPressureThatCannotBeReadIsSaidOnce(t *testing.T) {
|
||||
}
|
||||
|
||||
// The engine's own walk is paced by the machine's pressure, and says through the search's own channel.
|
||||
func TestTheEnginesWalkIsPacedByTheMachinesPressure(t *testing.T) {
|
||||
func testTheEnginesWalkIsPacedByTheMachinesPressure(t *testing.T) {
|
||||
var said []string
|
||||
w := engineWalker(nil, func(s string) { said = append(said, s) })
|
||||
if w.pace == nil || w.pace.path != ioPressureFile || w.pace.stalled == nil {
|
||||
@@ -227,7 +227,7 @@ func many(t *testing.T) string {
|
||||
}
|
||||
|
||||
// A walk ended while it pauses is an incomplete walk, never one that found nothing.
|
||||
func TestAWalkEndedWhileItPausesIsIncomplete(t *testing.T) {
|
||||
func testAWalkEndedWhileItPausesIsIncomplete(t *testing.T) {
|
||||
top := many(t)
|
||||
f := newFake(80)
|
||||
f.tick = 100 * time.Millisecond
|
||||
@@ -252,7 +252,7 @@ func TestAWalkEndedWhileItPausesIsIncomplete(t *testing.T) {
|
||||
}
|
||||
|
||||
// Paced, the walk finds what it finds unpaced: pausing changes when, never what.
|
||||
func TestAPacedWalkFindsWhatAnUnpacedWalkFinds(t *testing.T) {
|
||||
func testAPacedWalkFindsWhatAnUnpacedWalkFinds(t *testing.T) {
|
||||
top := many(t)
|
||||
plain := walkAll(t, mine(), top)
|
||||
|
||||
@@ -269,7 +269,7 @@ func TestAPacedWalkFindsWhatAnUnpacedWalkFinds(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheIOPressureIsReadAsTheKernelWritesIt(t *testing.T) {
|
||||
func testTheIOPressureIsReadAsTheKernelWritesIt(t *testing.T) {
|
||||
got, err := parseIOStalled([]byte("some avg10=26.24 avg60=20.07 avg300=27.47 total=123456789\n" +
|
||||
"full avg10=21.90 avg60=15.77 avg300=22.47 total=98765432\n"))
|
||||
if err != nil || got != 123456789*time.Microsecond {
|
||||
@@ -284,7 +284,7 @@ func TestTheIOPressureIsReadAsTheKernelWritesIt(t *testing.T) {
|
||||
|
||||
// One directory of many files is paced as it is read, not only between directories: a file's own details may be
|
||||
// read from the disk too.
|
||||
func TestADirectoryOfManyFilesIsPacedAsItIsRead(t *testing.T) {
|
||||
func testADirectoryOfManyFilesIsPacedAsItIsRead(t *testing.T) {
|
||||
names := []string{"bin/"}
|
||||
for i := range 20 {
|
||||
names = append(names, "bin/f"+strings.Repeat("x", i+1))
|
||||
@@ -300,3 +300,20 @@ func TestADirectoryOfManyFilesIsPacedAsItIsRead(t *testing.T) {
|
||||
t.Fatal("a directory of twenty files was read without a pause under pressure")
|
||||
}
|
||||
}
|
||||
|
||||
// TestSetuidPace runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestSetuidPace(t *testing.T) {
|
||||
t.Run("TheWalkPausesWhileTheDiskIsUnderPressureAndGoesOnWhenItEases", testTheWalkPausesWhileTheDiskIsUnderPressureAndGoesOnWhenItEases)
|
||||
t.Run("TheFirstLookOnlySetsWhereTheNextCountsFrom", testTheFirstLookOnlySetsWhereTheNextCountsFrom)
|
||||
t.Run("TheWalkDoesNotPauseOnAQuietDisk", testTheWalkDoesNotPauseOnAQuietDisk)
|
||||
t.Run("TheWalkKeepsATenthOfTheTimeWhateverThePressure", testTheWalkKeepsATenthOfTheTimeWhateverThePressure)
|
||||
t.Run("TheSlowestPacedWalkStillJudgesInTime", testTheSlowestPacedWalkStillJudgesInTime)
|
||||
t.Run("ARunOfPausesIsAtMostPaceAtMost", testARunOfPausesIsAtMostPaceAtMost)
|
||||
t.Run("TheWalkLooksAtThePressureAtMostEveryPaceLook", testTheWalkLooksAtThePressureAtMostEveryPaceLook)
|
||||
t.Run("APressureThatCannotBeReadIsSaidOnce", testAPressureThatCannotBeReadIsSaidOnce)
|
||||
t.Run("TheEnginesWalkIsPacedByTheMachinesPressure", testTheEnginesWalkIsPacedByTheMachinesPressure)
|
||||
t.Run("AWalkEndedWhileItPausesIsIncomplete", testAWalkEndedWhileItPausesIsIncomplete)
|
||||
t.Run("APacedWalkFindsWhatAnUnpacedWalkFinds", testAPacedWalkFindsWhatAnUnpacedWalkFinds)
|
||||
t.Run("TheIOPressureIsReadAsTheKernelWritesIt", testTheIOPressureIsReadAsTheKernelWritesIt)
|
||||
t.Run("ADirectoryOfManyFilesIsPacedAsItIsRead", testADirectoryOfManyFilesIsPacedAsItIsRead)
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ import (
|
||||
|
||||
// A walk stopped midway and resumed counts every entry once, as the walk that was never stopped does, and says
|
||||
// how long each filesystem took.
|
||||
func TestTheProgressCountsEachEntryOnceAcrossAResume(t *testing.T) {
|
||||
func testTheProgressCountsEachEntryOnceAcrossAResume(t *testing.T) {
|
||||
top := tree(t, "a/1!", "a/2", "a-b/3!", "b/c/4!", "b/c/5", "b/d!", "c/6!", "d/7!")
|
||||
other := tree(t, "x/1", "y!")
|
||||
whole := &SetuidProgress{Mounts: []string{top, other}}
|
||||
@@ -57,7 +57,7 @@ func TestTheProgressCountsEachEntryOnceAcrossAResume(t *testing.T) {
|
||||
|
||||
// A walk kept before the times were counted has them not known, never shifted onto the next filesystem, and
|
||||
// its entries visited are a lower bound; the filesystem it was part-way through took a time not known.
|
||||
func TestAWalkKeptWithoutTimesSaysThemNotKnown(t *testing.T) {
|
||||
func testAWalkKeptWithoutTimesSaysThemNotKnown(t *testing.T) {
|
||||
top, other := tree(t, "a"), tree(t, "b")
|
||||
p := &SetuidProgress{Mounts: []string{top, other}, Done: Paths{top}}
|
||||
if err := mine().walk(t.Context(), p, func() {}); err != nil {
|
||||
@@ -73,7 +73,7 @@ func TestAWalkKeptWithoutTimesSaysThemNotKnown(t *testing.T) {
|
||||
}
|
||||
|
||||
// A look while the search runs says how far it got at its last checkpoint, with no path it visited or found.
|
||||
func TestALookSaysHowFarTheRunningSearchGotAndNoPath(t *testing.T) {
|
||||
func testALookSaysHowFarTheRunningSearchGotAndNoPath(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
c := &SetuidCache{ProgressPath: filepath.Join(dir, SetuidProgressFile)}
|
||||
secret := "/home/someone/private/rootshell"
|
||||
@@ -133,7 +133,7 @@ func (w *waiting) Escalation(context.Context, string, []string) ([]string, error
|
||||
return nil, &SetuidNotJudged{Pending: true, Since: at, Progress: w.progress}
|
||||
}
|
||||
|
||||
func TestTheProgressMovesWithoutChangingTheVerdict(t *testing.T) {
|
||||
func testTheProgressMovesWithoutChangingTheVerdict(t *testing.T) {
|
||||
r := &waiting{progress: &SearchProgress{Filesystems: 2, Visited: 10}}
|
||||
j := New(r)
|
||||
j.Set([]Account{{Module: "claude-code", ID: "claude-code.agent", Name: "agent", Root: true}})
|
||||
@@ -150,7 +150,7 @@ func TestTheProgressMovesWithoutChangingTheVerdict(t *testing.T) {
|
||||
|
||||
// Asked at the terminal, a search starts afresh at the next look: the last complete one is thrown away, kept or
|
||||
// in memory, and a running one is ended and neither judges nor is carried on.
|
||||
func TestSearchNowThrowsAwayTheLastSearchAndStartsAFullOne(t *testing.T) {
|
||||
func testSearchNowThrowsAwayTheLastSearchAndStartsAFullOne(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
c := &SetuidCache{Path: filepath.Join(dir, SetuidSearchFile), ProgressPath: filepath.Join(dir, SetuidProgressFile)}
|
||||
g := newGate()
|
||||
@@ -206,7 +206,7 @@ func TestSearchNowThrowsAwayTheLastSearchAndStartsAFullOne(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAFilesystemPartWalkedByAnEngineThatDidNotCountTookATimeNotKnown(t *testing.T) {
|
||||
func testAFilesystemPartWalkedByAnEngineThatDidNotCountTookATimeNotKnown(t *testing.T) {
|
||||
top := tree(t, "a", "b")
|
||||
p := &SetuidProgress{Mounts: []string{top}, Cursor: Cursors{top: filepath.Join(top, "a")}}
|
||||
if err := mine().walk(t.Context(), p, func() {}); err != nil {
|
||||
@@ -216,3 +216,13 @@ func TestAFilesystemPartWalkedByAnEngineThatDidNotCountTookATimeNotKnown(t *test
|
||||
t.Fatalf("took %v", p.Took)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSetuidProgress runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestSetuidProgress(t *testing.T) {
|
||||
t.Run("TheProgressCountsEachEntryOnceAcrossAResume", testTheProgressCountsEachEntryOnceAcrossAResume)
|
||||
t.Run("AWalkKeptWithoutTimesSaysThemNotKnown", testAWalkKeptWithoutTimesSaysThemNotKnown)
|
||||
t.Run("ALookSaysHowFarTheRunningSearchGotAndNoPath", testALookSaysHowFarTheRunningSearchGotAndNoPath)
|
||||
t.Run("TheProgressMovesWithoutChangingTheVerdict", testTheProgressMovesWithoutChangingTheVerdict)
|
||||
t.Run("SearchNowThrowsAwayTheLastSearchAndStartsAFullOne", testSearchNowThrowsAwayTheLastSearchAndStartsAFullOne)
|
||||
t.Run("AFilesystemPartWalkedByAnEngineThatDidNotCountTookATimeNotKnown", testAFilesystemPartWalkedByAnEngineThatDidNotCountTookATimeNotKnown)
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ func homeMachine(home FileMode) *agentMachine {
|
||||
return m
|
||||
}
|
||||
|
||||
func TestReachabilityDecidesWhetherAFindCounts(t *testing.T) {
|
||||
func testReachabilityDecidesWhetherAFindCounts(t *testing.T) {
|
||||
op := func(perm fs.FileMode) FileMode { return FileMode{UID: 1500, GID: 1500, Perm: fs.ModeDir | perm} }
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
@@ -64,7 +64,7 @@ func TestReachabilityDecidesWhetherAFindCounts(t *testing.T) {
|
||||
}
|
||||
|
||||
// The search keeps every find; whether one counts is read again at every look.
|
||||
func TestAHomeOpenedAfterTheSearchCountsWithoutANewSearch(t *testing.T) {
|
||||
func testAHomeOpenedAfterTheSearchCountsWithoutANewSearch(t *testing.T) {
|
||||
m := homeMachine(FileMode{UID: 1500, GID: 1500, Perm: fs.ModeDir | 0o700})
|
||||
c := &SetuidCache{}
|
||||
j := New(Exec{Run: m.run, Walk: m.walk, Stat: m.stat, ReadFile: m.readFile, ReadDir: m.readDir, ACL: m.acl,
|
||||
@@ -88,7 +88,7 @@ func TestAHomeOpenedAfterTheSearchCountsWithoutANewSearch(t *testing.T) {
|
||||
|
||||
// On the machine's own modes, as their owner (the directories above a test's are its own): a directory without
|
||||
// its owner's search bit hides what is in it.
|
||||
func TestExecutableReadsTheMachinesModes(t *testing.T) {
|
||||
func testExecutableReadsTheMachinesModes(t *testing.T) {
|
||||
if os.Getuid() == 0 {
|
||||
t.Skip("root searches every directory")
|
||||
}
|
||||
@@ -113,3 +113,10 @@ func TestExecutableReadsTheMachinesModes(t *testing.T) {
|
||||
t.Fatal("a file gone was executable")
|
||||
}
|
||||
}
|
||||
|
||||
// TestSetuidReach runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestSetuidReach(t *testing.T) {
|
||||
t.Run("ReachabilityDecidesWhetherAFindCounts", testReachabilityDecidesWhetherAFindCounts)
|
||||
t.Run("AHomeOpenedAfterTheSearchCountsWithoutANewSearch", testAHomeOpenedAfterTheSearchCountsWithoutANewSearch)
|
||||
t.Run("ExecutableReadsTheMachinesModes", testExecutableReadsTheMachinesModes)
|
||||
}
|
||||
|
||||
@@ -68,7 +68,7 @@ func rel(top string, paths []string) []string {
|
||||
return out
|
||||
}
|
||||
|
||||
func TestTheWalkFindsSetuidAndSetgidRootFilesAndFollowsNoLink(t *testing.T) {
|
||||
func testTheWalkFindsSetuidAndSetgidRootFilesAndFollowsNoLink(t *testing.T) {
|
||||
top := tree(t, "bin/plain", "bin/rootshell!", "sbin/group%", "deep/a/b/c/x!")
|
||||
if err := os.Symlink(filepath.Join(top, "bin/rootshell"), filepath.Join(top, "link")); err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -85,7 +85,7 @@ func TestTheWalkFindsSetuidAndSetgidRootFilesAndFollowsNoLink(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAWalkThatCannotReadADirectoryIsIncomplete(t *testing.T) {
|
||||
func testAWalkThatCannotReadADirectoryIsIncomplete(t *testing.T) {
|
||||
if os.Geteuid() == 0 {
|
||||
t.Skip("root reads every directory")
|
||||
}
|
||||
@@ -100,7 +100,7 @@ func TestAWalkThatCannotReadADirectoryIsIncomplete(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestWalkOrderIsNameByName(t *testing.T) {
|
||||
func testWalkOrderIsNameByName(t *testing.T) {
|
||||
// "/a/b" is walked before "/a-c" although '-' sorts before '/': the walk goes name by name.
|
||||
if walkOrder(components("/a/b"), components("/a-c")) >= 0 {
|
||||
t.Fatal("/a/b is walked before /a-c")
|
||||
@@ -115,7 +115,7 @@ func TestWalkOrderIsNameByName(t *testing.T) {
|
||||
|
||||
// A walk stopped midway carries on from its cursor: what was before the cursor is not walked again, what is after
|
||||
// it is, and every file of the first walk is found.
|
||||
func TestAnInterruptedWalkCarriesOnFromItsCursor(t *testing.T) {
|
||||
func testAnInterruptedWalkCarriesOnFromItsCursor(t *testing.T) {
|
||||
top := tree(t, "a/1!", "a/2", "a-b/3!", "b/c/4!", "b/c/5", "b/d!", "c/6!", "d/7!")
|
||||
w := mine()
|
||||
w.every = 0 // a checkpoint at every path
|
||||
@@ -169,7 +169,7 @@ func tree2(t *testing.T, top, n string) {
|
||||
}
|
||||
|
||||
// A search's commands and walk run on a lowered thread while the rest of the engine keeps its priority.
|
||||
func TestTheSearchRunsOnALoweredThreadOfItsOwn(t *testing.T) {
|
||||
func testTheSearchRunsOnALoweredThreadOfItsOwn(t *testing.T) {
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(1)
|
||||
var err error
|
||||
@@ -185,7 +185,7 @@ func TestTheSearchRunsOnALoweredThreadOfItsOwn(t *testing.T) {
|
||||
|
||||
// Another filesystem's mount point is left without being read, and a file found that is gone, or no longer
|
||||
// setuid-root, when the walk ends is not asked about.
|
||||
func TestTheWalkLeavesMountPointsAndDropsWhatWentMeanwhile(t *testing.T) {
|
||||
func testTheWalkLeavesMountPointsAndDropsWhatWentMeanwhile(t *testing.T) {
|
||||
top := tree(t, "fuse/secret!", "bin/x!", "bin/y!")
|
||||
w := mine()
|
||||
w.mountPoints = map[string]bool{filepath.Join(top, "fuse"): true}
|
||||
@@ -205,9 +205,20 @@ func TestTheWalkLeavesMountPointsAndDropsWhatWentMeanwhile(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAMountPointIsReadAsTheKernelEscapesIt(t *testing.T) {
|
||||
func testAMountPointIsReadAsTheKernelEscapesIt(t *testing.T) {
|
||||
mp := MountPoints("/dev/a /mnt/a\\040b ext4 rw 0 0\n/dev/b /mnt/back\\134slash ext4 rw 0 0\n")
|
||||
if !mp["/mnt/a b"] || !mp[`/mnt/back\slash`] {
|
||||
t.Fatalf("read %v", mp)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSetuidWalk runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestSetuidWalk(t *testing.T) {
|
||||
t.Run("TheWalkFindsSetuidAndSetgidRootFilesAndFollowsNoLink", testTheWalkFindsSetuidAndSetgidRootFilesAndFollowsNoLink)
|
||||
t.Run("AWalkThatCannotReadADirectoryIsIncomplete", testAWalkThatCannotReadADirectoryIsIncomplete)
|
||||
t.Run("WalkOrderIsNameByName", testWalkOrderIsNameByName)
|
||||
t.Run("AnInterruptedWalkCarriesOnFromItsCursor", testAnInterruptedWalkCarriesOnFromItsCursor)
|
||||
t.Run("TheSearchRunsOnALoweredThreadOfItsOwn", testTheSearchRunsOnALoweredThreadOfItsOwn)
|
||||
t.Run("TheWalkLeavesMountPointsAndDropsWhatWentMeanwhile", testTheWalkLeavesMountPointsAndDropsWhatWentMeanwhile)
|
||||
t.Run("AMountPointIsReadAsTheKernelEscapesIt", testAMountPointIsReadAsTheKernelEscapesIt)
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ import (
|
||||
// runtime's socket, an ACL on a secret, a setuid program no package owns — each said; each unread question
|
||||
// unknown; and the judge's commands in the C locale.
|
||||
|
||||
func TestEachFurtherWayToRootIsSaid(t *testing.T) {
|
||||
func testEachFurtherWayToRootIsSaid(t *testing.T) {
|
||||
const broker = "/var/lib/mesh/node-tools/broker"
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
@@ -88,7 +88,7 @@ func TestEachFurtherWayToRootIsSaid(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestWhatGrantsSomebodyElseIsNoWay(t *testing.T) {
|
||||
func testWhatGrantsSomebodyElseIsNoWay(t *testing.T) {
|
||||
m := clean()
|
||||
m.texts = map[string]string{"/etc/doas.conf": "permit operator\npermit :wheel\n# permit agent\n",
|
||||
"/usr/share/polkit-1/rules.d/50-default.rules": `polkit.addAdminRule(function(a, s) { return ["unix-group:wheel"]; });`}
|
||||
@@ -101,7 +101,7 @@ func TestWhatGrantsSomebodyElseIsNoWay(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestDoasWithoutSudoIsJudgedFromItsRules(t *testing.T) {
|
||||
func testDoasWithoutSudoIsJudgedFromItsRules(t *testing.T) {
|
||||
m := clean()
|
||||
m.sudo, m.sudoErr = "", fmt.Errorf("sudo: %w", exec.ErrNotFound)
|
||||
m.texts = map[string]string{"/etc/doas.conf": "permit nopass agent\n"}
|
||||
@@ -111,7 +111,7 @@ func TestDoasWithoutSudoIsJudgedFromItsRules(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAFurtherQuestionUnansweredIsUnknown(t *testing.T) {
|
||||
func testAFurtherQuestionUnansweredIsUnknown(t *testing.T) {
|
||||
m := clean()
|
||||
m.findErr = errors.New("find: interrupted")
|
||||
if v := lookAgent(t, m); v.State != Unknown {
|
||||
@@ -131,7 +131,7 @@ func TestAFurtherQuestionUnansweredIsUnknown(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestANotJudgedSearchStillSaysAWayFound(t *testing.T) {
|
||||
func testANotJudgedSearchStillSaysAWayFound(t *testing.T) {
|
||||
j := New(fakeReader{ways: []string{"in the group docker, which grants root"}, err: &SetuidNotJudged{Pending: true, Since: time.Now()}})
|
||||
j.Set([]Account{{Module: "m", ID: "m.a", Name: "agent", Root: true}})
|
||||
st, _ := j.Look(context.Background())
|
||||
@@ -159,7 +159,7 @@ func (f fakeReader) Escalation(context.Context, string, []string) ([]string, err
|
||||
return f.ways, f.err
|
||||
}
|
||||
|
||||
func TestParseACL(t *testing.T) {
|
||||
func testParseACL(t *testing.T) {
|
||||
entry := func(tag, perm uint16, id uint32) []byte {
|
||||
b := make([]byte, 8)
|
||||
binary.LittleEndian.PutUint16(b, tag)
|
||||
@@ -189,7 +189,7 @@ func TestParseACL(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheJudgesCommandsRunInTheCLocale(t *testing.T) {
|
||||
func testTheJudgesCommandsRunInTheCLocale(t *testing.T) {
|
||||
t.Setenv("LC_ALL", "de_DE.UTF-8")
|
||||
t.Setenv("LANG", "de_DE.UTF-8")
|
||||
out, err := CLocale(t.Context(), "sh", "-c", `echo "$LC_ALL $LANG"`)
|
||||
@@ -202,13 +202,13 @@ func TestTheJudgesCommandsRunInTheCLocale(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheJudgedListIsWrittenDown(t *testing.T) {
|
||||
func testTheJudgedListIsWrittenDown(t *testing.T) {
|
||||
if len(Judged) < 8 || len(NotJudged) == 0 {
|
||||
t.Fatal("what is judged and what is not are both written down")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDistributionRulesForASeatOrForSomebodyAreNotEveryone(t *testing.T) {
|
||||
func testDistributionRulesForASeatOrForSomebodyAreNotEveryone(t *testing.T) {
|
||||
for _, rule := range []string{
|
||||
`polkit.addRule(function(a, s) { if (s.local && s.active) return polkit.Result.YES; });`,
|
||||
`polkit.addRule(function(a, s) { if (s.isInGroup("wheel")) return polkit.Result.YES; });`,
|
||||
@@ -223,7 +223,7 @@ func TestDistributionRulesForASeatOrForSomebodyAreNotEveryone(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAMachineMissingWhatTheJudgeReadsIsUnknown(t *testing.T) {
|
||||
func testAMachineMissingWhatTheJudgeReadsIsUnknown(t *testing.T) {
|
||||
for _, file := range []string{"/proc/sys/fs/protected_hardlinks", "/proc/net/tcp", "/proc/mounts"} {
|
||||
m := clean()
|
||||
delete(m.proc, file)
|
||||
@@ -233,7 +233,7 @@ func TestAMachineMissingWhatTheJudgeReadsIsUnknown(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSuidMountsLeaveOutNosuidPseudoAndContainerLayers(t *testing.T) {
|
||||
func testSuidMountsLeaveOutNosuidPseudoAndContainerLayers(t *testing.T) {
|
||||
got := SuidMounts("/dev/sdb1 /srv xfs rw 0 0\n/dev/sda2 / ext4 rw 0 0\noverlay /var/lib/docker/overlay2/x/merged overlay rw 0 0\n" +
|
||||
"/dev/sdc1 /data ext4 rw,nosuid 0 0\nproc /proc proc rw 0 0\nhost:/x /mnt/nfs nfs4 rw 0 0\n/dev/sdd1 /my\\040disk ext4 rw 0 0\n")
|
||||
if strings.Join(got, "|") != "/|/my disk|/srv" {
|
||||
@@ -242,7 +242,7 @@ func TestSuidMountsLeaveOutNosuidPseudoAndContainerLayers(t *testing.T) {
|
||||
}
|
||||
|
||||
// Each polkit rule is judged on its own, comments taken out (the third review of 2026-10-08).
|
||||
func TestAnUnconditionalPolkitYesIsNotMaskedByAnotherRuleOrAComment(t *testing.T) {
|
||||
func testAnUnconditionalPolkitYesIsNotMaskedByAnotherRuleOrAComment(t *testing.T) {
|
||||
cases := []struct {
|
||||
name, text string
|
||||
every bool
|
||||
@@ -270,7 +270,7 @@ polkit.addRule(function(a, s) { /* isInGroup("wheel") */ return polkit.Result.YE
|
||||
}
|
||||
|
||||
// The package manager is asked about every path found in one call, and answers each: owned, or owned by nothing.
|
||||
func TestThePackageManagerIsAskedOnceForEveryPathFound(t *testing.T) {
|
||||
func testThePackageManagerIsAskedOnceForEveryPathFound(t *testing.T) {
|
||||
m := clean()
|
||||
m.setuid = "/usr/bin/sudo\n/usr/bin/passwd\n/usr/local/bin/x\n/opt/y\n"
|
||||
m.packaged = map[string]bool{"/usr/bin/sudo": true, "/usr/bin/passwd": true}
|
||||
@@ -303,3 +303,20 @@ func TestThePackageManagerIsAskedOnceForEveryPathFound(t *testing.T) {
|
||||
t.Error("a walk that did not complete was read as an answer")
|
||||
}
|
||||
}
|
||||
|
||||
// TestWays runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestWays(t *testing.T) {
|
||||
t.Run("EachFurtherWayToRootIsSaid", testEachFurtherWayToRootIsSaid)
|
||||
t.Run("WhatGrantsSomebodyElseIsNoWay", testWhatGrantsSomebodyElseIsNoWay)
|
||||
t.Run("DoasWithoutSudoIsJudgedFromItsRules", testDoasWithoutSudoIsJudgedFromItsRules)
|
||||
t.Run("AFurtherQuestionUnansweredIsUnknown", testAFurtherQuestionUnansweredIsUnknown)
|
||||
t.Run("ANotJudgedSearchStillSaysAWayFound", testANotJudgedSearchStillSaysAWayFound)
|
||||
t.Run("ParseACL", testParseACL)
|
||||
t.Run("TheJudgesCommandsRunInTheCLocale", testTheJudgesCommandsRunInTheCLocale)
|
||||
t.Run("TheJudgedListIsWrittenDown", testTheJudgedListIsWrittenDown)
|
||||
t.Run("DistributionRulesForASeatOrForSomebodyAreNotEveryone", testDistributionRulesForASeatOrForSomebodyAreNotEveryone)
|
||||
t.Run("AMachineMissingWhatTheJudgeReadsIsUnknown", testAMachineMissingWhatTheJudgeReadsIsUnknown)
|
||||
t.Run("SuidMountsLeaveOutNosuidPseudoAndContainerLayers", testSuidMountsLeaveOutNosuidPseudoAndContainerLayers)
|
||||
t.Run("AnUnconditionalPolkitYesIsNotMaskedByAnotherRuleOrAComment", testAnUnconditionalPolkitYesIsNotMaskedByAnotherRuleOrAComment)
|
||||
t.Run("ThePackageManagerIsAskedOnceForEveryPathFound", testThePackageManagerIsAskedOnceForEveryPathFound)
|
||||
}
|
||||
|
||||
+95
-8
@@ -23,6 +23,7 @@ import (
|
||||
"github.com/novox/mesh-host/internal/compositions"
|
||||
"slices"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
@@ -77,6 +78,14 @@ type Have struct {
|
||||
PullWait *nodeengine.PullWait
|
||||
// Wait is the hold or wait the have says, in the recovery wait with its ask-at and act (design 47 G §560).
|
||||
Wait *nodeengine.Wait
|
||||
// Run is the composition run the module was applied from, its pipeline sequence in decimal (design 47 H2 §813 (1),
|
||||
// H-A-384 (2), H-A-388; nodeengine.HaveByNodeModuleValue.Run): kept in the have, so a restarted engine applies no
|
||||
// older run again. A write that names none keeps the one the module's last have said (writeHave).
|
||||
Run string
|
||||
// Pipeline is the pipeline of the want the module was applied from, its key <branch>.<source>, kept beside Run
|
||||
// (H-A-429 (1), H-A-458 (1); nodeengine.HaveByNodeModuleValue.Pipeline): a want's run is compared with Run only when
|
||||
// the want's pipeline is of the same branch (pipelineBranch). Kept and replaced together with Run.
|
||||
Pipeline string
|
||||
}
|
||||
|
||||
// Haves is the node's have bucket as the agent uses it.
|
||||
@@ -180,6 +189,13 @@ type Env struct {
|
||||
// them. The node-engine's filling tells the provisioner's client then to fill again what it refused (mesh-host
|
||||
// internal/filling Knock; ace, 2026-10-25 21:17). Nil tells nothing.
|
||||
Settled func(module string)
|
||||
// TakenAtStart is told, outside the agent's lock, each module taken as running at this start from its have or the
|
||||
// kept declaration, with no apply, and the composition it runs: the node-engine converges the owner and mode of each
|
||||
// record-held directory entry of it (H-A-374, H-A-392). Nil tells nothing.
|
||||
TakenAtStart func(module string, runs compositions.Composed)
|
||||
// DirectoryDrift reads, for the verb composition's diff, each directory entry of runs the mesh made whose owner or
|
||||
// mode on disk differ (apply.DirectoryDrifts, H-A-392). Nil reads none.
|
||||
DirectoryDrift func(runs compositions.Composed) []nodeengine.CompositionAnswerDriftItem
|
||||
// RunsChanged is told, outside the agent's lock, that what runs (Everything) changed other than by an apply or a
|
||||
// removal: once at the start, when the haves and the compositions they name are read, and each time a module is
|
||||
// taken as running from its have or the kept declaration. Like Settled, the filling then tells the provisioner's
|
||||
@@ -733,11 +749,18 @@ func (a *Agent) writeHave(ctx context.Context, h Have) {
|
||||
h.Kept = a.kept[h.Module]
|
||||
a.mu.Unlock()
|
||||
}
|
||||
if h.Composed == "" && h.Module != NodeModule {
|
||||
if last, ok := a.env.Haves.Read(ctx, h.Module); ok && last.Composed != "" {
|
||||
h.FP, h.Composed = last.FP, last.Composed
|
||||
if h.Sealed == nil {
|
||||
h.Sealed = last.Sealed
|
||||
if (h.Composed == "" || h.Run == "") && h.Module != NodeModule {
|
||||
if last, ok := a.env.Haves.Read(ctx, h.Module); ok {
|
||||
if h.Composed == "" && last.Composed != "" {
|
||||
h.FP, h.Composed = last.FP, last.Composed
|
||||
if h.Sealed == nil {
|
||||
h.Sealed = last.Sealed
|
||||
}
|
||||
}
|
||||
// The run the module was applied from stays in its have until an apply from another run (H-A-384 (2)), with
|
||||
// the pipeline it was of (H-A-458 (1)).
|
||||
if h.Run == "" {
|
||||
h.Run, h.Pipeline = last.Run, last.Pipeline
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -828,7 +851,7 @@ func (a *Agent) takeWant(u Update) string {
|
||||
if _, ok := meshwants.ParseWantsByWantNodeNodeKey(u.Key); ok {
|
||||
w := wantNow{Node: true, Rev: u.Revision}
|
||||
if !u.Deleted {
|
||||
nw, err := meshwants.DecodeWantsByWantNodeNodeValue(u.Value)
|
||||
nw, _, err := meshwants.DecodeWantsByWantNodeNodeValue(u.Value)
|
||||
if err != nil {
|
||||
a.sayOnce("want:node", fmt.Sprintf("the node's own want is not one: %v", err))
|
||||
return ""
|
||||
@@ -844,7 +867,7 @@ func (a *Agent) takeWant(u Update) string {
|
||||
}
|
||||
w := wantNow{Rev: u.Revision}
|
||||
if !u.Deleted {
|
||||
want, err := meshwants.DecodeWantsByWantNodeModuleValue(u.Value)
|
||||
want, _, err := meshwants.DecodeWantsByWantNodeModuleValue(u.Value)
|
||||
if err != nil {
|
||||
a.sayOnce("want:"+module, fmt.Sprintf("the want of %s is not one: %v", module, err))
|
||||
return ""
|
||||
@@ -1511,6 +1534,25 @@ func (a *Agent) settleOne(ctx context.Context, module string) {
|
||||
} else {
|
||||
a.mu.Unlock()
|
||||
}
|
||||
// Design 47 H2 §813 (1), H-A-384 (2): the run the module was applied from is its have's, never this engine's memory, so
|
||||
// a restarted engine applies no older run again. Read only for a want that carries one, and compared only within the
|
||||
// want's branch: a want of another branch is a placement the assigner made on purpose and replaces whatever stands
|
||||
// (H-A-429 (1), H-A-458 (1)). A pipeline's key is <branch>.<source>, so every pipeline of a branch has its own key and
|
||||
// the branch is the key without its last part.
|
||||
appliedRun := ""
|
||||
if w.Want.Run != "" {
|
||||
h, found, unread := a.readHave(ctx, module)
|
||||
if unread {
|
||||
a.mu.Lock()
|
||||
a.sayOnce("run-unread:"+module+":"+w.Want.Run, fmt.Sprintf("the want of %s carries run %s, and its have, which says "+
|
||||
"the run it was applied from, cannot be read: nothing is applied until it reads", module, w.Want.Run))
|
||||
a.mu.Unlock()
|
||||
return
|
||||
}
|
||||
if found && pipelineBranch(h.Pipeline) == pipelineBranch(w.Want.Pipeline) {
|
||||
appliedRun = h.Run
|
||||
}
|
||||
}
|
||||
a.mu.Lock()
|
||||
r, runs := a.running[module]
|
||||
// A module whose last apply failed runs no composition whole, whatever it ran before (ranFailed).
|
||||
@@ -1544,6 +1586,13 @@ func (a *Agent) settleOne(ctx context.Context, module string) {
|
||||
a.mu.Unlock()
|
||||
return // failed already for exactly these keys: retried by the next change of either
|
||||
}
|
||||
if was := appliedRun; !runIsNewer(w.Want.Run, was) {
|
||||
// Design 47 H2 §813 (1), H-A-355: one writer per composition key, and the engine applies again only a newer write.
|
||||
a.sayOnce("run:"+module+":"+w.Want.Run, fmt.Sprintf("the want of %s carries run %s, and the engine applied it from run %s, "+
|
||||
"which is not older: nothing is applied", module, w.Want.Run, was))
|
||||
a.mu.Unlock()
|
||||
return
|
||||
}
|
||||
if module == NodeModule {
|
||||
// Not while a module's composition cannot be read or is refused: what it carries may be what left the node's own,
|
||||
// and the node's own apply would remove it, held out by nothing (issue 1945, the review's gap 2).
|
||||
@@ -1666,6 +1715,7 @@ func (a *Agent) baseline(ctx context.Context, module string, w wantNow, comp com
|
||||
a.running[module] = nodeengine.HaveByNodeModuleValue{Fp: h.FP, Composed: h.Composed, Phase: nodeengineclient.PhaseRunning}
|
||||
a.mu.Unlock()
|
||||
a.runsChanged(module + " was taken from its have")
|
||||
a.takenAtStart(module, comp.C)
|
||||
// Said again, so the session holds the module and its key carries the health this engine judges,
|
||||
// not the one an older engine left there (xorg's unknown on g14 and shanks, 2026-10-25).
|
||||
a.writeHave(ctx, Have{Module: module, FP: h.FP, Composed: h.Composed,
|
||||
@@ -1695,6 +1745,7 @@ func (a *Agent) baseline(ctx context.Context, module string, w wantNow, comp com
|
||||
a.running[module] = nodeengine.HaveByNodeModuleValue{Fp: w.Want.Fp, Composed: w.Composed, Phase: nodeengineclient.PhaseRunning}
|
||||
a.mu.Unlock()
|
||||
a.runsChanged(module + " was taken from the kept declaration")
|
||||
a.takenAtStart(module, comp.C)
|
||||
a.writeHave(ctx, Have{Module: module, FP: w.Want.Fp, Composed: w.Composed, Phase: string(nodeengineclient.PhaseRunning)})
|
||||
return true
|
||||
}
|
||||
@@ -1829,15 +1880,51 @@ func (a *Agent) apply(ctx context.Context, module string, w wantNow, comp compNo
|
||||
delete(a.notComposed, module) // the apply says what it runs now
|
||||
a.running[module] = nodeengine.HaveByNodeModuleValue{Fp: fp, Composed: dig, Phase: nodeengineclient.PhaseRunning}
|
||||
a.applied[module] = comp
|
||||
run, pipeline := w.Want.Run, w.Want.Pipeline
|
||||
a.mu.Unlock()
|
||||
if run != "" {
|
||||
a.env.Say(fmt.Sprintf("applied %s from run %s", what, run))
|
||||
}
|
||||
a.keepApplied(module, comp)
|
||||
if a.env.Settled != nil {
|
||||
a.env.Settled(module)
|
||||
}
|
||||
a.writeHave(ctx, Have{Module: module, FP: fp, Composed: dig, Phase: string(nodeengineclient.PhaseRunning), Detail: res.Detail})
|
||||
a.writeHave(ctx, Have{Module: module, FP: fp, Composed: dig, Phase: string(nodeengineclient.PhaseRunning), Detail: res.Detail, Run: run, Pipeline: pipeline})
|
||||
a.catchUp(ctx, module, catchUps)
|
||||
}
|
||||
|
||||
// takenAtStart tells TakenAtStart of a module taken as running at this start (H-A-392).
|
||||
func (a *Agent) takenAtStart(module string, runs compositions.Composed) {
|
||||
if a.env.TakenAtStart != nil {
|
||||
a.env.TakenAtStart(module, runs)
|
||||
}
|
||||
}
|
||||
|
||||
// runIsNewer says whether a want's run orders after the run a module was applied from (design 47 H2 §813 (1)), both of one
|
||||
// pipeline (settleOne compares no runs of two, H-A-458 (1)): each is
|
||||
// the composition run's pipeline sequence in decimal. A want or an apply without one is not ordered by run, nor is a run
|
||||
// that is no decimal number.
|
||||
// pipelineBranch is the branch of a pipeline's key <branch>.<source> (design 47 H1, the runner's key; H-A-458 (1)): the
|
||||
// key without its last part. A key with no source part is its own branch.
|
||||
func pipelineBranch(key string) string {
|
||||
if i := strings.LastIndexByte(key, '.'); i >= 0 {
|
||||
return key[:i]
|
||||
}
|
||||
return key
|
||||
}
|
||||
|
||||
func runIsNewer(want, applied string) bool {
|
||||
if want == "" || applied == "" {
|
||||
return true
|
||||
}
|
||||
w, err1 := strconv.ParseUint(want, 10, 64)
|
||||
p, err2 := strconv.ParseUint(applied, 10, 64)
|
||||
if err1 != nil || err2 != nil {
|
||||
return true
|
||||
}
|
||||
return w > p
|
||||
}
|
||||
|
||||
// ranFailed marks what runs of a module as failed once an apply of it failed (novox/hq issue 1966, 2026-11-08): a failed
|
||||
// apply may have replaced some of its resources (distribution's store container) before it stopped, so what ran is no
|
||||
// longer whole, and a want of it again (a put back) is applied rather than taken as running. Called with a.mu held.
|
||||
|
||||
+168
-21
@@ -132,10 +132,12 @@ type bed struct {
|
||||
others [][]compositions.Composed
|
||||
said []string
|
||||
// settled is each module Settled was told, and settledRan whether what runs held it then.
|
||||
settled []string
|
||||
settledRan []bool
|
||||
ag *Agent // the agent run() runs
|
||||
env Env
|
||||
settled []string
|
||||
// takenAtStart is each module TakenAtStart was told, with its composition's resource count.
|
||||
takenAtStart []string
|
||||
settledRan []bool
|
||||
ag *Agent // the agent run() runs
|
||||
env Env
|
||||
// runs is, by module, a build the agent already runs when run() starts it.
|
||||
runs map[string]string
|
||||
}
|
||||
@@ -179,6 +181,11 @@ func newBed(t *testing.T) *bed {
|
||||
}
|
||||
return Backup{Done: true}
|
||||
},
|
||||
TakenAtStart: func(m string, runs compositions.Composed) {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
b.takenAtStart = append(b.takenAtStart, fmt.Sprintf("%s:%d", m, len(runs.Resources)))
|
||||
},
|
||||
Settled: func(m string) {
|
||||
ran := false
|
||||
if b.ag != nil {
|
||||
@@ -290,7 +297,7 @@ func (b *bed) appliedList() []string {
|
||||
|
||||
// R6-A AC1 (the agent, with a bus that is a fake): given a want naming a digest and that composition, the module is
|
||||
// applied and its have names the fingerprint and the digest; a composition whose digest no want names is not applied.
|
||||
func TestAWantAndItsCompositionApplyTheModuleAndTheHaveNamesBoth(t *testing.T) {
|
||||
func testAWantAndItsCompositionApplyTheModuleAndTheHaveNamesBoth(t *testing.T) {
|
||||
b := newBed(t)
|
||||
stop := b.run()
|
||||
defer stop()
|
||||
@@ -331,6 +338,14 @@ func TestAWantAndItsCompositionApplyTheModuleAndTheHaveNamesBoth(t *testing.T) {
|
||||
ckn, crawn, dign := composition(t, "web", fpn, false, archive("a", d1), archive("b", d2))
|
||||
b.comps.put(ckn, crawn)
|
||||
wkn, wrawn := wantFor(t, "web", fpn, dign, "")
|
||||
// Design 47 H2 §780, §813 (1): the want is read tolerantly, a field this engine does not know and a later form kept
|
||||
// rather than refused, so the engine that reads run runs before the assigner writes it.
|
||||
var later map[string]any
|
||||
if err := json.Unmarshal(wrawn, &later); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
later["form"], later["a-later-field"], later["run"] = 3, "x", "7"
|
||||
wrawn, _ = json.Marshal(later)
|
||||
b.wants.put(wkn, wrawn)
|
||||
b.idle()
|
||||
if got := len(b.appliedList()) - before; got != 1 {
|
||||
@@ -339,11 +354,82 @@ func TestAWantAndItsCompositionApplyTheModuleAndTheHaveNamesBoth(t *testing.T) {
|
||||
if h := b.haves.last("web"); h.Phase != string(nodeengineclient.PhaseRunning) || h.Wait != nil || h.FP != fpn {
|
||||
t.Fatalf("the have is %s %q wait %+v, want running at %s with no wait (§750)", h.Phase, h.Detail, h.Wait, fpn)
|
||||
}
|
||||
// Design 47 H2 §813 (1), H-A-355: the engine applies a composition again only when its run is newer than the one it
|
||||
// applied, naming the run in its journal; a want of an older run is said and not applied.
|
||||
for _, row := range []struct {
|
||||
fp, run string
|
||||
applied int
|
||||
}{{"6", "5", 0}, {"6", "7", 0}, {"6", "8", 1}} {
|
||||
before := len(b.appliedList())
|
||||
fpr := fpOf(row.fp)
|
||||
ckr, crawr, digr := composition(t, "web", fpr, false, archive("a", d2))
|
||||
b.comps.put(ckr, crawr)
|
||||
wkr, _ := wantFor(t, "web", fpr, digr, "")
|
||||
rawr, err := bucketstest.Want(meshwants.WantsByWantNodeModuleValue{Fp: fpr, Run: row.run})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b.wants.put(wkr, rawr)
|
||||
b.idle()
|
||||
if got := len(b.appliedList()) - before; got != row.applied {
|
||||
t.Errorf("a want of run %s after run 7: applied %d times, want %d", row.run, got, row.applied)
|
||||
}
|
||||
}
|
||||
// H-A-384 (2), H-A-388: the run is kept in the have, never in memory: the have names run 8, and a have an earlier life of
|
||||
// the engine wrote at run 20 holds a want of run 10 back, though this one applied run 8 last.
|
||||
if h := b.haves.last("web"); h.Run != "8" {
|
||||
t.Errorf("the have names run %q after run 8 was applied", h.Run)
|
||||
}
|
||||
h := b.haves.last("web")
|
||||
h.Run = "20"
|
||||
b.haves.Write(context.Background(), h)
|
||||
before = len(b.appliedList())
|
||||
fpr := fpOf("9")
|
||||
ckr, crawr, digr := composition(t, "web", fpr, false, archive("a", d1))
|
||||
b.comps.put(ckr, crawr)
|
||||
wkr, _ := wantFor(t, "web", fpr, digr, "")
|
||||
rawr, _ := bucketstest.Want(meshwants.WantsByWantNodeModuleValue{Fp: fpr, Run: "10"})
|
||||
b.wants.put(wkr, rawr)
|
||||
b.idle()
|
||||
if got := len(b.appliedList()) - before; got != 0 {
|
||||
t.Errorf("a want of run 10 after a have of run 20: applied %d times, want none", got)
|
||||
}
|
||||
// H-A-429 (1), H-A-458 (1): a want's run is compared with the have's only within one branch, a pipeline's key being
|
||||
// <branch>.<source>: a lower run of another branch replaces what stands, and the have keeps its pipeline beside its
|
||||
// run; a lower run of an older pipeline of the same branch is refused.
|
||||
for _, row := range []struct {
|
||||
fp, run, pipeline string
|
||||
applied int
|
||||
}{{"7", "10", "feat.10", 1}, {"8", "9", "feat.9", 0}, {"b", "5", "main.5", 1}} {
|
||||
before := len(b.appliedList())
|
||||
fpr := fpOf(row.fp)
|
||||
ckr, crawr, digr := composition(t, "web", fpr, false, archive("a", d2))
|
||||
b.comps.put(ckr, crawr)
|
||||
wkr, _ := wantFor(t, "web", fpr, digr, "")
|
||||
rawr, _ := bucketstest.Want(meshwants.WantsByWantNodeModuleValue{Fp: fpr, Run: row.run, Pipeline: row.pipeline})
|
||||
b.wants.put(wkr, rawr)
|
||||
b.idle()
|
||||
if got := len(b.appliedList()) - before; got != row.applied {
|
||||
t.Errorf("a want of run %s of pipeline %s: applied %d times, want %d", row.run, row.pipeline, got, row.applied)
|
||||
}
|
||||
}
|
||||
if h := b.haves.last("web"); h.Run != "5" || h.Pipeline != "main.5" {
|
||||
t.Errorf("the have names run %q of pipeline %q, want run 5 of main.5", h.Run, h.Pipeline)
|
||||
}
|
||||
b.mu.Lock()
|
||||
said := strings.Join(b.said, "\n")
|
||||
b.mu.Unlock()
|
||||
for _, want := range []string{"from run 7", "from run 8", "carries run 5, and the engine applied it from run 7",
|
||||
"carries run 10, and the engine applied it from run 20", "carries run 9, and the engine applied it from run 10"} {
|
||||
if !strings.Contains(said, want) {
|
||||
t.Errorf("the journal does not say %q:\n%s", want, said)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// R6-A AC2: given a kept declaration and wants and compositions equal to it, when the agent starts, nothing is applied
|
||||
// and every have names its fingerprint and digest.
|
||||
func TestStartingOnWhatTheKeptDeclarationHoldsAppliesNothing(t *testing.T) {
|
||||
func testStartingOnWhatTheKeptDeclarationHoldsAppliesNothing(t *testing.T) {
|
||||
b := newBed(t)
|
||||
fp := fpOf("a")
|
||||
rs := []json.RawMessage{file("web", "x", "1"), file("web", "y", "2")}
|
||||
@@ -363,6 +449,11 @@ func TestStartingOnWhatTheKeptDeclarationHoldsAppliesNothing(t *testing.T) {
|
||||
if got := b.appliedList(); len(got) != 0 {
|
||||
t.Fatalf("a module that already runs what the want names was applied: %v", got)
|
||||
}
|
||||
// H-A-392: a module taken as running at the start is told with the composition it runs, for its directories' drift.
|
||||
if b.mu.Lock(); !slices.Equal(b.takenAtStart, []string{"web:2"}) {
|
||||
t.Errorf("taken at the start were %v; want web with its two resources", b.takenAtStart)
|
||||
}
|
||||
b.mu.Unlock()
|
||||
t.Run("starting on its own have applies nothing", testStartingOnItsOwnHaveAppliesNothing)
|
||||
}
|
||||
|
||||
@@ -457,7 +548,7 @@ func testStartingOnItsOwnHaveSaysTheHaveAgainSoItsHealthIsThisEngines(t *testing
|
||||
|
||||
// A module whose kept resources differ from the composition is applied, and a failed apply is retried only by a change
|
||||
// of either key.
|
||||
func TestAFailedApplyIsRetriedOnlyByAChangeOfEitherKey(t *testing.T) {
|
||||
func testAFailedApplyIsRetriedOnlyByAChangeOfEitherKey(t *testing.T) {
|
||||
t.Run("1957: the judge's edge reconciles, and a failed re-apply is failed", testReconcileAppliesARunningModuleAgainAndLeavesTheHeldAndTheUnwantedAlone)
|
||||
// A real failure is not retried by the clock, however short the backoff: only by a change of either key.
|
||||
t.Run("a real failure", func(t *testing.T) {
|
||||
@@ -694,7 +785,7 @@ func TestAFailedApplyIsRetriedOnlyByAChangeOfEitherKey(t *testing.T) {
|
||||
|
||||
// R6-A AC5: a data module that ran before asks its backup before any resource changes; a refusal holds it, nothing is
|
||||
// applied and the have says held; when the want then says skip, the module is applied.
|
||||
func TestADataModuleIsBackedUpFirstAndHeldWhenItFails(t *testing.T) {
|
||||
func testADataModuleIsBackedUpFirstAndHeldWhenItFails(t *testing.T) {
|
||||
b := newBed(t)
|
||||
fp1, fp2 := fpOf("a"), fpOf("b")
|
||||
ck1, craw1, dig1 := composition(t, "db", fp1, true, file("db", "x", "1"))
|
||||
@@ -980,7 +1071,7 @@ func cutAsAHaveIs(s string) string {
|
||||
}
|
||||
|
||||
// A data module with a good backup is applied after it; one that never ran has nothing to back up.
|
||||
func TestABackupDoneIsFollowedByTheApplyAndANewModuleIsNotBackedUp(t *testing.T) {
|
||||
func testABackupDoneIsFollowedByTheApplyAndANewModuleIsNotBackedUp(t *testing.T) {
|
||||
t.Run("a move across a kept data's form change is taken as a restore point and restored at a revert", testAMoveAcrossAFormChange)
|
||||
b := newBed(t)
|
||||
stop := b.run()
|
||||
@@ -1012,7 +1103,7 @@ func TestABackupDoneIsFollowedByTheApplyAndANewModuleIsNotBackedUp(t *testing.T)
|
||||
}
|
||||
|
||||
// R6-A AC4 at the agent: a removed want removes that module only, and its have is written removed.
|
||||
func TestARemovedWantRemovesThatModuleOnly(t *testing.T) {
|
||||
func testARemovedWantRemovesThatModuleOnly(t *testing.T) {
|
||||
t.Run("its composition holds nothing back", testARemovedModulesCompositionHoldsNothingBack)
|
||||
b := newBed(t)
|
||||
stop := b.run()
|
||||
@@ -1041,7 +1132,7 @@ func TestARemovedWantRemovesThatModuleOnly(t *testing.T) {
|
||||
// module, the holder of the seat node-backup and the bus module (found by their claims), each pipeline's wants by rank (the
|
||||
// older source first), the rest by name, and its own module last; a want of a higher rank waits, on this machine, for the lower
|
||||
// ranks of its pipeline, held in its have as a wait of step placing, and the read apply-order answers the order with why.
|
||||
func TestTheOrderTheChangedWantsAreAppliedIn(t *testing.T) {
|
||||
func testTheOrderTheChangedWantsAreAppliedIn(t *testing.T) {
|
||||
type mod struct {
|
||||
name string
|
||||
pipeline string // the want's pipeline, with its rank
|
||||
@@ -1143,7 +1234,7 @@ func TestTheOrderTheChangedWantsAreAppliedIn(t *testing.T) {
|
||||
|
||||
// What a module's apply must not take is every other module that runs, those the agent holds and those still running from
|
||||
// the kept declaration (ADR 0429 §4): the resources of the kept declaration reach Apply as the others.
|
||||
func TestApplyingOneModuleHoldsOutTheModulesStillRunningFromTheKeptDeclaration(t *testing.T) {
|
||||
func testApplyingOneModuleHoldsOutTheModulesStillRunningFromTheKeptDeclaration(t *testing.T) {
|
||||
b := newBed(t)
|
||||
b.kept = map[string][]json.RawMessage{"db": {file("db", "x", "1")}, NodeModule: {file("node", "n", "n")}}
|
||||
stop := b.run()
|
||||
@@ -1167,7 +1258,7 @@ func TestApplyingOneModuleHoldsOutTheModulesStillRunningFromTheKeptDeclaration(t
|
||||
}
|
||||
|
||||
// Everything is what runs: the agent's compositions and the kept resources of each module it does not hold.
|
||||
func TestEverythingIsWhatTheAgentRunsAndWhatIsKeptForTheRest(t *testing.T) {
|
||||
func testEverythingIsWhatTheAgentRunsAndWhatIsKeptForTheRest(t *testing.T) {
|
||||
b := newBed(t)
|
||||
b.kept = map[string][]json.RawMessage{"db": {file("db", "x", "1")}, "web": {file("web", "x", "old")}}
|
||||
a := New(b.env)
|
||||
@@ -1365,7 +1456,7 @@ func testAFailedApplyIsAppliedAgainAfterARestartWhateverIsKept(t *testing.T) {
|
||||
}
|
||||
|
||||
// A have written before the switch carries no composition: then the kept declaration says what runs.
|
||||
func TestAHaveWithNoCompositionDefersToTheKeptDeclaration(t *testing.T) {
|
||||
func testAHaveWithNoCompositionDefersToTheKeptDeclaration(t *testing.T) {
|
||||
b := newBed(t)
|
||||
fp := fpOf("a")
|
||||
ck, craw, dig := composition(t, "web", fp, false, file("web", "x", "1"))
|
||||
@@ -1488,7 +1579,7 @@ func testARemovedModulesCompositionHoldsNothingBack(t *testing.T) {
|
||||
|
||||
// The node's own composition is not applied while a module's composition in the node's bucket cannot be read: what that one carries may be what left the node's own, and the node's own apply would remove
|
||||
// it (issue 1945, the review's gap 2). It is said, naming the composition, and applied once that one reads.
|
||||
func TestTheNodesOwnWaitsWhileAModulesCompositionCannotBeRead(t *testing.T) {
|
||||
func testTheNodesOwnWaitsWhileAModulesCompositionCannotBeRead(t *testing.T) {
|
||||
b := newBed(t)
|
||||
bad, err := compositions.Key(node, "broken", fpOf("c"))
|
||||
if err != nil {
|
||||
@@ -1524,7 +1615,7 @@ func TestTheNodesOwnWaitsWhileAModulesCompositionCannotBeRead(t *testing.T) {
|
||||
// A stale refused composition beside a newer readable one of the same module does not hold the node's own apply back:
|
||||
// only the composition the module's want names, else its newest, counts (the review of issue 1945: the bucket keeps
|
||||
// compositions written before the filled paths, which the SDK now refuses, and nobody applies them).
|
||||
func TestAStaleRefusedCompositionDoesNotHoldTheNodesOwnBack(t *testing.T) {
|
||||
func testAStaleRefusedCompositionDoesNotHoldTheNodesOwnBack(t *testing.T) {
|
||||
b := newBed(t)
|
||||
stale, err := compositions.Key(node, "power", fpOf("a"))
|
||||
if err != nil {
|
||||
@@ -1547,7 +1638,7 @@ func TestAStaleRefusedCompositionDoesNotHoldTheNodesOwnBack(t *testing.T) {
|
||||
// record of its resources: they were removed since (issue 1945, live on 2026-10-25: ace's and g14's node-engines removed
|
||||
// ca-trust's, power's and matrix's resources in a node's own apply, and the wants that named those modules' own
|
||||
// compositions were judged already running from the kept declaration, so nothing made them again).
|
||||
func TestACompositionWhoseResourcesWereRemovedIsAppliedAgain(t *testing.T) {
|
||||
func testACompositionWhoseResourcesWereRemovedIsAppliedAgain(t *testing.T) {
|
||||
for _, from := range []string{"kept", "have"} {
|
||||
t.Run(from, func(t *testing.T) {
|
||||
b := newBed(t)
|
||||
@@ -1578,7 +1669,7 @@ func TestACompositionWhoseResourcesWereRemovedIsAppliedAgain(t *testing.T) {
|
||||
// Only a have in a phase baseline takes as running names what runs; and what runs carries Data, from the composition
|
||||
// or, from the kept declaration, from the module's manifest, so a data module is not judged to move its data against
|
||||
// its first composition after a restart (mongodb and mssql on novox).
|
||||
func TestWhatRunsBeforeTheAgentTakesAModuleNamesItsFilledPaths(t *testing.T) {
|
||||
func testWhatRunsBeforeTheAgentTakesAModuleNamesItsFilledPaths(t *testing.T) {
|
||||
const old, added = "/tmp/r6/power/settings", "/tmp/r6/power/bound"
|
||||
filledFile := func(id string) json.RawMessage {
|
||||
return json.RawMessage(`{"id":"power.` + id + `","type":"file","module":"power","path":"/tmp/r6/power/` + id +
|
||||
@@ -1673,7 +1764,7 @@ func TestWhatRunsBeforeTheAgentTakesAModuleNamesItsFilledPaths(t *testing.T) {
|
||||
// composition composed for the want's build is applied, and only when it differs from what runs; for a module of
|
||||
// policy record a move that recreates a container waits in phase waiting-yes with its judgement until the want names
|
||||
// the yes for that composition, and is then applied.
|
||||
func TestTheNodesOwnCompositionIsAppliedWhenItDiffersAndARecordMoveWaitsForAYes(t *testing.T) {
|
||||
func testTheNodesOwnCompositionIsAppliedWhenItDiffersAndARecordMoveWaitsForAYes(t *testing.T) {
|
||||
b := newBed(t)
|
||||
b.env.SelfComposed = true
|
||||
b.env.Policy = func(_ context.Context, m string) string {
|
||||
@@ -1850,10 +1941,11 @@ func TestTheNodesOwnCompositionIsAppliedWhenItDiffersAndARecordMoveWaitsForAYes(
|
||||
b.haves.Write(context.Background(), Have{Module: "broken", FP: brokenFP, Composed: brokenDig, Phase: string(nodeengineclient.PhaseFailed),
|
||||
Detail: "apply: unit failed to start"})
|
||||
want("broken", brokenFP, "")
|
||||
eventually(t, "unread's want was not taken", func() bool {
|
||||
// Every want taken before the mark, not unread's alone: fresh's taken after it was not marked (seen under -race).
|
||||
eventually(t, "the wants were not taken", func() bool {
|
||||
b.ag.mu.Lock()
|
||||
defer b.ag.mu.Unlock()
|
||||
return b.ag.wants["unread"].Present
|
||||
return b.ag.wants["unread"].Present && b.ag.wants["fresh"].Present && b.ag.wants["broken"].Present
|
||||
})
|
||||
b.ag.NotComposed(context.Background(), "a stand-in for web's password, again")
|
||||
if h := b.haves.last("unread"); h.Module != "" {
|
||||
@@ -1935,7 +2027,20 @@ func TestTheNodesOwnCompositionIsAppliedWhenItDiffersAndARecordMoveWaitsForAYes(
|
||||
// container it recreates; the revision that runs, asked by its digest, is no move (issue 774).
|
||||
keep(dk, draw)
|
||||
keep(dk, drawMoved)
|
||||
// H-A-392: and with diff, each directory the mesh made of what runs whose mode or owner on disk drifted.
|
||||
b.ag.env.DirectoryDrift = func(runs compositions.Composed) []nodeengine.CompositionAnswerDriftItem {
|
||||
return []nodeengine.CompositionAnswerDriftItem{{ID: runs.Module + ".data", Path: "/srv/db", Drift: "mode 0700, 0711 declared"}}
|
||||
}
|
||||
view, err := b.ag.Composition(context.Background(), "db", "", true)
|
||||
if len(view.Drift) != 1 || view.Drift[0].ID != "db.data" {
|
||||
t.Errorf("the diff of db names the drift %+v", view.Drift)
|
||||
}
|
||||
// H-A-458 (2): the answer is read as the seat's contract has it, drift among its fields.
|
||||
if raw, merr := json.Marshal(view); merr != nil {
|
||||
t.Error(merr)
|
||||
} else if read, _, derr := nodeengine.DecodeCompositionAnswer(raw); derr != nil || len(read.Drift) != 1 || read.Drift[0] != view.Drift[0] {
|
||||
t.Errorf("the composition answer read through the contract: drift %+v, %v", read.Drift, derr)
|
||||
}
|
||||
if err != nil || view.Have == nil || view.Have.Phase != string(nodeengineclient.PhaseWaitingYes) || view.Composition.Digest != ddigMoved ||
|
||||
view.Runs == nil || view.Runs.Composed != ddig || view.Judged.Judgement != string(nodeengineclient.JudgedRecreates) ||
|
||||
!view.Judged.WaitsForYes || len(view.Diff) != 1 || view.Diff[0].ID != "db.server" || view.Diff[0].Change != "changed" ||
|
||||
@@ -1949,6 +2054,29 @@ func TestTheNodesOwnCompositionIsAppliedWhenItDiffersAndARecordMoveWaitsForAYes(
|
||||
if _, err := b.ag.Composition(context.Background(), "db", "sha256:"+strings.Repeat("0", 64), false); err == nil {
|
||||
t.Error("a digest no revision has was answered")
|
||||
}
|
||||
// Design 47 H2 §813 (3): composition-diff answers, by resource, the entries that differ between what runs and the
|
||||
// revision asked, by its digest or its revision; a secret's value is masked, an environment entry named by its name.
|
||||
if d, err := b.ag.CompositionDiff(context.Background(), "db", 0, ddigMoved); err != nil || d.Running != ddig || d.Other == nil ||
|
||||
d.Other.Digest != ddigMoved || len(d.Resources) != 1 || d.Resources[0].Resource != "db.server" || len(d.Resources[0].Entries) != 1 ||
|
||||
d.Resources[0].Entries[0] != (nodeengine.CompositionDiffEntry{Name: "image", Running: "db@sha256:" + strings.Repeat("1", 64),
|
||||
Other: "db@sha256:" + strings.Repeat("7", 64)}) {
|
||||
t.Errorf("composition-diff of db's waiting revision reads %+v (%v)", d, err)
|
||||
}
|
||||
if d, err := b.ag.CompositionDiff(context.Background(), "db", int64(view.Revisions[0].Revision), ""); err != nil ||
|
||||
d.Other == nil || d.Other.Digest != ddig || len(d.Resources) != 0 {
|
||||
t.Errorf("composition-diff of db's running revision, by its revision, reads %+v (%v)", d, err)
|
||||
}
|
||||
if _, err := b.ag.CompositionDiff(context.Background(), "db", 0, ""); err == nil {
|
||||
t.Error("composition-diff with neither a revision nor a digest was answered")
|
||||
}
|
||||
if got := DiffResources([]json.RawMessage{json.RawMessage(`{"id":"web.key","type":"file","sealed":"a","content":"x"}`),
|
||||
json.RawMessage(`{"id":"web.run","type":"process","env":{"MODE":"a","GONE":"1"}}`)},
|
||||
[]json.RawMessage{json.RawMessage(`{"id":"web.key","type":"file","sealed":"b","content":"y"}`),
|
||||
json.RawMessage(`{"id":"web.run","type":"process","env":{"MODE":"b"}}`)}); len(got) != 2 ||
|
||||
!slices.Equal(got[0].Entries, []nodeengine.CompositionDiffEntry{{Name: "content", Masked: true}, {Name: "sealed", Masked: true}}) ||
|
||||
!slices.Equal(got[1].Entries, []nodeengine.CompositionDiffEntry{{Name: "env.GONE", Running: "1"}, {Name: "env.MODE", Running: "a", Other: "b"}}) {
|
||||
t.Errorf("the entries that differ, a secret masked, read %+v", got)
|
||||
}
|
||||
// Issue 774 (ace, 2026-11-04 01:29): the node's own revision shows its own fields, the provisioner client's account
|
||||
// and the adoption among them, and what the composer's last pass held.
|
||||
ownKey, ownRaw, ownDig := encodedAs(t, compositions.Composed{Node: node, Own: compositions.NodeOwn{Provisioner: "mesh-provisioner-client",
|
||||
@@ -2147,3 +2275,22 @@ func testReconcileAppliesARunningModuleAgainAndLeavesTheHeldAndTheUnwantedAlone(
|
||||
t.Fatalf("a failed apply was tried again with no edge: %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAgent runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestAgent(t *testing.T) {
|
||||
t.Run("AWantAndItsCompositionApplyTheModuleAndTheHaveNamesBoth", testAWantAndItsCompositionApplyTheModuleAndTheHaveNamesBoth)
|
||||
t.Run("StartingOnWhatTheKeptDeclarationHoldsAppliesNothing", testStartingOnWhatTheKeptDeclarationHoldsAppliesNothing)
|
||||
t.Run("AFailedApplyIsRetriedOnlyByAChangeOfEitherKey", testAFailedApplyIsRetriedOnlyByAChangeOfEitherKey)
|
||||
t.Run("ADataModuleIsBackedUpFirstAndHeldWhenItFails", testADataModuleIsBackedUpFirstAndHeldWhenItFails)
|
||||
t.Run("ABackupDoneIsFollowedByTheApplyAndANewModuleIsNotBackedUp", testABackupDoneIsFollowedByTheApplyAndANewModuleIsNotBackedUp)
|
||||
t.Run("ARemovedWantRemovesThatModuleOnly", testARemovedWantRemovesThatModuleOnly)
|
||||
t.Run("TheOrderTheChangedWantsAreAppliedIn", testTheOrderTheChangedWantsAreAppliedIn)
|
||||
t.Run("ApplyingOneModuleHoldsOutTheModulesStillRunningFromTheKeptDeclaration", testApplyingOneModuleHoldsOutTheModulesStillRunningFromTheKeptDeclaration)
|
||||
t.Run("EverythingIsWhatTheAgentRunsAndWhatIsKeptForTheRest", testEverythingIsWhatTheAgentRunsAndWhatIsKeptForTheRest)
|
||||
t.Run("AHaveWithNoCompositionDefersToTheKeptDeclaration", testAHaveWithNoCompositionDefersToTheKeptDeclaration)
|
||||
t.Run("TheNodesOwnWaitsWhileAModulesCompositionCannotBeRead", testTheNodesOwnWaitsWhileAModulesCompositionCannotBeRead)
|
||||
t.Run("AStaleRefusedCompositionDoesNotHoldTheNodesOwnBack", testAStaleRefusedCompositionDoesNotHoldTheNodesOwnBack)
|
||||
t.Run("ACompositionWhoseResourcesWereRemovedIsAppliedAgain", testACompositionWhoseResourcesWereRemovedIsAppliedAgain)
|
||||
t.Run("WhatRunsBeforeTheAgentTakesAModuleNamesItsFilledPaths", testWhatRunsBeforeTheAgentTakesAModuleNamesItsFilledPaths)
|
||||
t.Run("TheNodesOwnCompositionIsAppliedWhenItDiffersAndARecordMoveWaitsForAYes", testTheNodesOwnCompositionIsAppliedWhenItDiffersAndARecordMoveWaitsForAYes)
|
||||
}
|
||||
|
||||
@@ -2,9 +2,14 @@ package agent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"maps"
|
||||
"slices"
|
||||
|
||||
"git.novox.be/novox/mesh-contracts/go/clients/nodeengineclient"
|
||||
"git.novox.be/novox/mesh-contracts/go/seats/nodeengine"
|
||||
engcomp "github.com/novox/mesh-host/internal/compositions"
|
||||
|
||||
"git.novox.be/novox/mesh-sdk/go/catalogue"
|
||||
@@ -44,6 +49,10 @@ type CompositionView struct {
|
||||
Judged JudgedView `json:"judged"`
|
||||
// Diff is every resource that differs from what runs, when asked.
|
||||
Diff []judge.ResourceChange `json:"diff,omitempty"`
|
||||
// Drift is, when the diff is asked, each directory entry of what runs that the mesh made, as its record holds, whose
|
||||
// owner or mode on disk differ from it (H-A-374, H-A-392): read-only; the engine sets it right at its next start or
|
||||
// apply of the module. Its form is the node-engine seat's contract's (H-A-458 (2)).
|
||||
Drift []nodeengine.CompositionAnswerDriftItem `json:"drift,omitempty"`
|
||||
// Own is, of the node's own composition (module node), its own fields beside what runs names (issue 774: ace's
|
||||
// own composition dropped the provisioner client's account, and nothing read could show it).
|
||||
Own *OwnView `json:"own,omitempty"`
|
||||
@@ -297,6 +306,9 @@ func (a *Agent) Composition(ctx context.Context, module, digest string, diff boo
|
||||
}
|
||||
if diff {
|
||||
view.Diff = judge.ChangedResources(running, read.C)
|
||||
if running != nil && a.env.DirectoryDrift != nil {
|
||||
view.Drift = a.env.DirectoryDrift(*running)
|
||||
}
|
||||
}
|
||||
return view, nil
|
||||
}
|
||||
@@ -335,3 +347,160 @@ func (a *Agent) revisionsOf(ctx context.Context, key string) ([]compNow, error)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// CompositionDiff answers the node-engine seat's read verb composition-diff (design 47 H2 §813 (3), H-A-349 DQ-12b): one
|
||||
// module's composition that runs beside another revision of its composition key, given by its revision or its digest,
|
||||
// as the entries that differ per resource; environment entries by name, a secret's value masked. It changes nothing.
|
||||
func (a *Agent) CompositionDiff(ctx context.Context, module string, revision int64, digest string) (nodeengine.CompositionDiffAnswer, error) {
|
||||
answer := nodeengine.CompositionDiffAnswer{Node: a.env.Node, Module: module, Resources: []nodeengine.CompositionDiffResource{}}
|
||||
switch {
|
||||
case module == "":
|
||||
return answer, errors.New("name the module, or node for the node's own composition")
|
||||
case (revision == 0) == (digest == ""):
|
||||
return answer, errors.New("give the revision or the digest of the composition to compare with, one of the two")
|
||||
}
|
||||
a.mu.Lock()
|
||||
fp := ""
|
||||
if w := a.wants[module]; w.Present {
|
||||
fp = w.Want.Fp
|
||||
}
|
||||
running, known := a.runningComposition(module)
|
||||
a.mu.Unlock()
|
||||
if fp == "" && known {
|
||||
fp = running.FP
|
||||
}
|
||||
if module != NodeModule && fp == "" {
|
||||
return answer, fmt.Errorf("%s has no want and nothing runs of it on %s, so no composition of it is kept here", module, a.env.Node)
|
||||
}
|
||||
key, err := a.compositionKey(module, fp)
|
||||
if err != nil {
|
||||
return answer, err
|
||||
}
|
||||
revs, err := a.revisionsOf(ctx, key)
|
||||
if err != nil {
|
||||
return answer, fmt.Errorf("the revisions of %s cannot be read: %w", key, err)
|
||||
}
|
||||
var other *compNow
|
||||
for i := range revs {
|
||||
if (revision != 0 && revs[i].Rev == uint64(revision)) || (digest != "" && revs[i].Err == nil && revs[i].Dig == digest) {
|
||||
other = &revs[i]
|
||||
}
|
||||
}
|
||||
if other == nil {
|
||||
return answer, fmt.Errorf("no revision of %s the bucket keeps is the one asked; composition lists those it keeps", key)
|
||||
}
|
||||
answer.Other = &nodeengine.Revision{Key: key, Revision: int64(other.Rev), Digest: other.Dig, Resources: int64(len(other.C.Resources)),
|
||||
Latest: other.Rev == revs[len(revs)-1].Rev}
|
||||
if other.Err != nil {
|
||||
answer.Other.Refused = other.Err.Error()
|
||||
return answer, nil
|
||||
}
|
||||
var from []json.RawMessage
|
||||
if known {
|
||||
from = running.Resources
|
||||
if answer.Running, err = engcomp.DigestOf(running); err != nil {
|
||||
return answer, fmt.Errorf("the composition that runs of %s has no digest: %w", module, err)
|
||||
}
|
||||
}
|
||||
answer.Resources = DiffResources(from, other.C.Resources)
|
||||
return answer, nil
|
||||
}
|
||||
|
||||
// DiffResources is, per resource by its id, the entries that differ from running to other (design 47 H2 §813 (3)): each
|
||||
// top-level field by its name, the environment's entries each by `env.<name>`, and a value the declaration keeps secret
|
||||
// (a file's sealed, vault-sealed or secrets, and the content of a file that has any of them) masked. Resources in id
|
||||
// order, entries in name order; none that is the same in both.
|
||||
func DiffResources(running, other []json.RawMessage) []nodeengine.CompositionDiffResource {
|
||||
was, now := entriesByID(running), entriesByID(other)
|
||||
ids := map[string]bool{}
|
||||
for id := range was {
|
||||
ids[id] = true
|
||||
}
|
||||
for id := range now {
|
||||
ids[id] = true
|
||||
}
|
||||
out := []nodeengine.CompositionDiffResource{}
|
||||
for _, id := range slices.Sorted(maps.Keys(ids)) {
|
||||
w, n := was[id], now[id]
|
||||
names := map[string]bool{}
|
||||
for k := range w.values {
|
||||
names[k] = true
|
||||
}
|
||||
for k := range n.values {
|
||||
names[k] = true
|
||||
}
|
||||
var entries []nodeengine.CompositionDiffEntry
|
||||
for _, name := range slices.Sorted(maps.Keys(names)) {
|
||||
rv, rok := w.values[name]
|
||||
ov, ook := n.values[name]
|
||||
if rok == ook && rv == ov {
|
||||
continue
|
||||
}
|
||||
e := nodeengine.CompositionDiffEntry{Name: name}
|
||||
if w.secret[name] || n.secret[name] {
|
||||
e.Masked = true
|
||||
} else {
|
||||
e.Running, e.Other = rv, ov
|
||||
}
|
||||
entries = append(entries, e)
|
||||
}
|
||||
if len(entries) > 0 {
|
||||
out = append(out, nodeengine.CompositionDiffResource{Resource: id, Entries: entries})
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// resourceEntries are one resource's entries by name, as text, and which of them hold a secret.
|
||||
type resourceEntries struct {
|
||||
values map[string]string
|
||||
secret map[string]bool
|
||||
}
|
||||
|
||||
// secretFields are the fields of a resource the declaration keeps secret (declaration.File.Secret, its Secrets).
|
||||
var secretFields = []string{"sealed", "vault-sealed", "secrets"}
|
||||
|
||||
func entriesByID(resources []json.RawMessage) map[string]resourceEntries {
|
||||
out := map[string]resourceEntries{}
|
||||
for _, raw := range resources {
|
||||
var fields map[string]json.RawMessage
|
||||
if json.Unmarshal(raw, &fields) != nil {
|
||||
continue
|
||||
}
|
||||
var id string
|
||||
_ = json.Unmarshal(fields["id"], &id)
|
||||
r := resourceEntries{values: map[string]string{}, secret: map[string]bool{}}
|
||||
hasSecret := false
|
||||
for _, f := range secretFields {
|
||||
if _, ok := fields[f]; ok {
|
||||
hasSecret = true
|
||||
}
|
||||
}
|
||||
for name, value := range fields {
|
||||
if name == "env" {
|
||||
var env map[string]string
|
||||
if json.Unmarshal(value, &env) == nil {
|
||||
for k, v := range env {
|
||||
r.values["env."+k] = v
|
||||
}
|
||||
continue
|
||||
}
|
||||
}
|
||||
r.values[name] = entryText(value)
|
||||
if slices.Contains(secretFields, name) || (hasSecret && name == "content") {
|
||||
r.secret[name] = true
|
||||
}
|
||||
}
|
||||
out[id] = r
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// entryText is a field's value as the answer says it: a string as itself, anything else as its JSON.
|
||||
func entryText(value json.RawMessage) string {
|
||||
var s string
|
||||
if json.Unmarshal(value, &s) == nil {
|
||||
return s
|
||||
}
|
||||
return string(value)
|
||||
}
|
||||
|
||||
@@ -14,7 +14,7 @@ import (
|
||||
// mode, because the media library and the download spool are the operator's and several modules
|
||||
// share them. This is the opposite of a directory on every axis, and the whole reason the two are
|
||||
// different shapes.
|
||||
func TestAnAccessPresentIsConfirmedAndNothingIsChanged(t *testing.T) {
|
||||
func testAnAccessPresentIsConfirmedAndNothingIsChanged(t *testing.T) {
|
||||
dir := t.TempDir() // the operator's directory, already there
|
||||
d := declare(t, `{"id":"lib","type":"access","path":"`+dir+`","mode":"read-write"}`)
|
||||
|
||||
@@ -35,7 +35,7 @@ func TestAnAccessPresentIsConfirmedAndNothingIsChanged(t *testing.T) {
|
||||
// library must not delete the library — that is the data loss ADR 0030 exists to prevent, on a
|
||||
// directory the mesh never made. The record is dropped; the operator's data is left exactly as it
|
||||
// is.
|
||||
func TestAnUndeclaredAccessLeavesTheOperatorsPathAlone(t *testing.T) {
|
||||
func testAnUndeclaredAccessLeavesTheOperatorsPathAlone(t *testing.T) {
|
||||
lib := t.TempDir() // the operator's library
|
||||
keep := t.TempDir()
|
||||
if err := os.WriteFile(lib+"/a-real-file", []byte("the operator's data"), 0o644); err != nil {
|
||||
@@ -73,3 +73,9 @@ func TestAnUndeclaredAccessLeavesTheOperatorsPathAlone(t *testing.T) {
|
||||
t.Errorf("dropping an access was not reported as forgotten: %+v", report.Outcomes)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAccess runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestAccess(t *testing.T) {
|
||||
t.Run("AnAccessPresentIsConfirmedAndNothingIsChanged", testAnAccessPresentIsConfirmedAndNothingIsChanged)
|
||||
t.Run("AnUndeclaredAccessLeavesTheOperatorsPathAlone", testAnUndeclaredAccessLeavesTheOperatorsPathAlone)
|
||||
}
|
||||
|
||||
+102
-49
@@ -31,7 +31,7 @@ func noServices(context.Context, string, ...string) (string, error) {
|
||||
return "", errors.New("this test declares no services and should not have run a command")
|
||||
}
|
||||
|
||||
func TestApplyingTwiceChangesNothingTheSecondTime(t *testing.T) {
|
||||
func testApplyingTwiceChangesNothingTheSecondTime(t *testing.T) {
|
||||
// Idempotence is what makes an apply safe to run on a schedule. Without it, a host that
|
||||
// reconciles every few minutes rewrites files forever and every reader sees churn.
|
||||
dir := t.TempDir()
|
||||
@@ -61,7 +61,7 @@ func TestApplyingTwiceChangesNothingTheSecondTime(t *testing.T) {
|
||||
//
|
||||
// Not by overwriting silently — by noticing. An edit that vanishes without a word is how somebody
|
||||
// spends an afternoon re-fixing a bug they already fixed.
|
||||
func TestADriftedMachineIsReturned(t *testing.T) {
|
||||
func testADriftedMachineIsReturned(t *testing.T) {
|
||||
// The other half of idempotence, and the half that matters: converging is not "do nothing
|
||||
// if the state file says it was done". The machine is read, not the record.
|
||||
dir := t.TempDir()
|
||||
@@ -91,7 +91,7 @@ func TestADriftedMachineIsReturned(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestADroppedResourceIsRemoved(t *testing.T) {
|
||||
func testADroppedResourceIsRemoved(t *testing.T) {
|
||||
// novox/hq ADR 0005: the host removes what it previously applied and is no longer
|
||||
// declared. Removing a line from a declaration is an act with an effect.
|
||||
dir := t.TempDir()
|
||||
@@ -129,7 +129,7 @@ func TestADroppedResourceIsRemoved(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestNothingTheHostDidNotCreateIsTouched(t *testing.T) {
|
||||
func testNothingTheHostDidNotCreateIsTouched(t *testing.T) {
|
||||
// The boundary the whole removal rule turns on. A machine has things on it the mesh did
|
||||
// not put there, and a converger that treats "not declared" as "must not exist" deletes
|
||||
// them. Authoritative over its own footprint; inert everywhere else.
|
||||
@@ -152,7 +152,7 @@ func TestNothingTheHostDidNotCreateIsTouched(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestARenameToTheSamePathDoesNotDeleteTheNewFile(t *testing.T) {
|
||||
func testARenameToTheSamePathDoesNotDeleteTheNewFile(t *testing.T) {
|
||||
// Why removal happens FIRST. A resource leaving a declaration while another arrives at the
|
||||
// same path is an ordinary rename; removing afterwards would delete the file just written.
|
||||
dir := t.TempDir()
|
||||
@@ -186,7 +186,7 @@ func TestARenameToTheSamePathDoesNotDeleteTheNewFile(t *testing.T) {
|
||||
// (novox/hq 04-ISSUES/011; design 42 zfs-owns-zfs §1, ADR 0679 §16 (a)): the resources of no module are all
|
||||
// attempted, so one broken resource holds no machine hostage and every failure is counted, not just the first;
|
||||
// a module's apply stops at its first failed resource, reports each one left, and no other module is touched.
|
||||
func TestAFailedResourceFailsTheApplyAndWhatFollowsIsAttemptedByWhoseItIs(t *testing.T) {
|
||||
func testAFailedResourceFailsTheApplyAndWhatFollowsIsAttemptedByWhoseItIs(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
for _, name := range []string{"blocker", "one", "two"} {
|
||||
if err := os.WriteFile(filepath.Join(dir, name), []byte("i am a file\n"), 0o644); err != nil {
|
||||
@@ -272,7 +272,7 @@ func TestAFailedResourceFailsTheApplyAndWhatFollowsIsAttemptedByWhoseItIs(t *tes
|
||||
}
|
||||
}
|
||||
|
||||
func TestNothingIsRecordedUntilItWorked(t *testing.T) {
|
||||
func testNothingIsRecordedUntilItWorked(t *testing.T) {
|
||||
// novox/hq ADR 0018. A record written before the fact restates the request in a new place
|
||||
// and inherits none of the authority of having happened.
|
||||
dir := t.TempDir()
|
||||
@@ -293,7 +293,7 @@ func TestNothingIsRecordedUntilItWorked(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAModeIsMaintainedNotJustSet(t *testing.T) {
|
||||
func testAModeIsMaintainedNotJustSet(t *testing.T) {
|
||||
// A permission set at creation is not a permission maintained — this repository has
|
||||
// already paid for that once, with generated files left world-readable because the mode
|
||||
// applied only when the file was first written.
|
||||
@@ -324,7 +324,7 @@ func TestAModeIsMaintainedNotJustSet(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAServiceIsReadBackNotAssumed(t *testing.T) {
|
||||
func testAServiceIsReadBackNotAssumed(t *testing.T) {
|
||||
// `systemctl start` returning zero says the transaction was accepted, not that the unit is
|
||||
// running. A unit that starts and immediately dies satisfies the command.
|
||||
started := false
|
||||
@@ -352,7 +352,7 @@ func TestAServiceIsReadBackNotAssumed(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnUnknownServiceStateIsRefusedNotGuessed(t *testing.T) {
|
||||
func testAnUnknownServiceStateIsRefusedNotGuessed(t *testing.T) {
|
||||
run := func(ctx context.Context, name string, args ...string) (string, error) {
|
||||
args = oldShape(name, args)
|
||||
return "LoadState=loaded\nActiveState=reticent\n", nil
|
||||
@@ -370,7 +370,7 @@ func TestAnUnknownServiceStateIsRefusedNotGuessed(t *testing.T) {
|
||||
// nothing of it runs, whatever its last run did (novox/hq issue 1126). The kernel module's
|
||||
// linux-modules-cleanup.service failed on ace with "was asked to be stopped and is running": an
|
||||
// inactive one-shot with ExecMainStatus=0 reads "running", and stopping it changes nothing.
|
||||
func TestABootOneShotDeclaredStoppedIsSatisfiedAtRest(t *testing.T) {
|
||||
func testABootOneShotDeclaredStoppedIsSatisfiedAtRest(t *testing.T) {
|
||||
for _, c := range []struct{ name, status string }{
|
||||
{"exited 0: never ran, ran at boot, or unloaded", "0"},
|
||||
} {
|
||||
@@ -402,7 +402,7 @@ func TestABootOneShotDeclaredStoppedIsSatisfiedAtRest(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestADroppedServiceIsGivenBackTheStateItWasFoundIn(t *testing.T) {
|
||||
func testADroppedServiceIsGivenBackTheStateItWasFoundIn(t *testing.T) {
|
||||
// novox/hq ADR 0118: undeclaring removes what the mesh made, gives back what it changed, and
|
||||
// leaves what was the machine's. A service resource never installs a unit — so undeclaring it
|
||||
// undoes what the mesh did to the unit, and nothing more. Stopping every undeclared unit is
|
||||
@@ -462,7 +462,7 @@ func TestADroppedServiceIsGivenBackTheStateItWasFoundIn(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAServiceRecordsTheStateItWasFoundInOnceAndCarriesIt(t *testing.T) {
|
||||
func testAServiceRecordsTheStateItWasFoundInOnceAndCarriesIt(t *testing.T) {
|
||||
// Read the first time the host applies the unit — before it starts or enables anything —
|
||||
// and never again: by the next apply, the unit's state is the mesh's doing.
|
||||
active := "inactive"
|
||||
@@ -512,7 +512,7 @@ func TestAServiceRecordsTheStateItWasFoundInOnceAndCarriesIt(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAUnitThatDoesNotExistIsNotStopped(t *testing.T) {
|
||||
func testAUnitThatDoesNotExistIsNotStopped(t *testing.T) {
|
||||
// Found by applying inside a raised machine. `systemctl is-active` says "inactive" for a
|
||||
// unit that DOES NOT EXIST exactly as it does for one that is installed and stopped, so
|
||||
// declaring a unit stopped reported success for a unit the host cannot manage at all.
|
||||
@@ -539,7 +539,7 @@ func TestAUnitThatDoesNotExistIsNotStopped(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAMaskedUnitIsRefused(t *testing.T) {
|
||||
func testAMaskedUnitIsRefused(t *testing.T) {
|
||||
// Masked means someone deliberately made it unstartable. Applying over that would undo a
|
||||
// decision the host did not make and cannot see the reason for.
|
||||
masked := func(ctx context.Context, name string, args ...string) (string, error) {
|
||||
@@ -554,7 +554,7 @@ func TestAMaskedUnitIsRefused(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestForgettingAUnitThatIsGoneDoesNotStrandTheNode(t *testing.T) {
|
||||
func testForgettingAUnitThatIsGoneDoesNotStrandTheNode(t *testing.T) {
|
||||
// Found on a real machine. Removing an orphaned service runs `systemctl stop`, which fails
|
||||
// when the unit no longer exists — and a failure there fails the whole apply. A host
|
||||
// holding a record of an uninstalled unit could then apply NOTHING, ever, with no way out
|
||||
@@ -610,7 +610,7 @@ func parseTrusted(t *testing.T, raw string) *declaration.Declaration {
|
||||
const pinned = "docker.io/library/postgres@sha256:" +
|
||||
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
|
||||
|
||||
func TestABrokenPackageDatabaseIsNotReadAsNotInstalled(t *testing.T) {
|
||||
func testABrokenPackageDatabaseIsNotReadAsNotInstalled(t *testing.T) {
|
||||
// The same trap serviceState documents. `pacman -Q x` exits non-zero both for a package
|
||||
// that is not installed and for a database that cannot be read — so believing the first
|
||||
// answer would silently reinstall on a machine whose package manager is broken, or report
|
||||
@@ -632,7 +632,7 @@ func TestABrokenPackageDatabaseIsNotReadAsNotInstalled(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnInstalledPackageIsNotReinstalled(t *testing.T) {
|
||||
func testAnInstalledPackageIsNotReinstalled(t *testing.T) {
|
||||
var installed bool
|
||||
run := func(ctx context.Context, name string, args ...string) (string, error) {
|
||||
args = oldShape(name, args)
|
||||
@@ -657,7 +657,7 @@ func TestAnInstalledPackageIsNotReinstalled(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAPackageIsNeverUninstalled(t *testing.T) {
|
||||
func testAPackageIsNeverUninstalled(t *testing.T) {
|
||||
// Deliberate: the host cannot know what else needs the package. Uninstalling a container
|
||||
// runtime because a declaration changed would stop every container on the node, and the
|
||||
// machine may have had it before the mesh ever saw it. Undeclaring is not "remove it".
|
||||
@@ -692,7 +692,7 @@ func TestAPackageIsNeverUninstalled(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnActionThatIsAlreadyTrueDoesNotRun(t *testing.T) {
|
||||
func testAnActionThatIsAlreadyTrueDoesNotRun(t *testing.T) {
|
||||
// Verify is the idempotency check as well as the read-back. The host does not know what a
|
||||
// database is, so "is it already there" is a question only the declaration can ask.
|
||||
var ran bool
|
||||
@@ -719,7 +719,7 @@ func TestAnActionThatIsAlreadyTrueDoesNotRun(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnActionThatSucceedsAndDoesNothingFails(t *testing.T) {
|
||||
func testAnActionThatSucceedsAndDoesNothingFails(t *testing.T) {
|
||||
// The whole reason verify is mandatory: a command that exits zero and has no effect is
|
||||
// this repository's most expensive failure shape. Here the command "succeeds" every time
|
||||
// and verify never passes.
|
||||
@@ -746,7 +746,7 @@ func TestAnActionThatSucceedsAndDoesNothingFails(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnActionRunsInsideTheContainerItNames(t *testing.T) {
|
||||
func testAnActionRunsInsideTheContainerItNames(t *testing.T) {
|
||||
// Steps 2 and 3 of the bootstrap act on something inside the store's container, before
|
||||
// there is any mesh to ask.
|
||||
var sawExec bool
|
||||
@@ -770,7 +770,7 @@ func TestAnActionRunsInsideTheContainerItNames(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAContainerThatExitsImmediatelyFailsTheApply(t *testing.T) {
|
||||
func testAContainerThatExitsImmediatelyFailsTheApply(t *testing.T) {
|
||||
// `docker run --detach` returning an id says the container was created, not that it is
|
||||
// still running. A container whose entrypoint dies satisfies the command exactly as one
|
||||
// that came up does — which is the read-back rule, in the place it matters most.
|
||||
@@ -802,7 +802,7 @@ func TestAContainerThatExitsImmediatelyFailsTheApply(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAContainerWhoseDeclarationChangedIsReplaced(t *testing.T) {
|
||||
func testAContainerWhoseDeclarationChangedIsReplaced(t *testing.T) {
|
||||
// A container's configuration is fixed when it is created, so any change is a replacement.
|
||||
// The spec label is what makes the difference visible without diffing everything the
|
||||
// runtime reports — which cannot be done reliably, because a runtime normalises what it is
|
||||
@@ -845,7 +845,7 @@ func TestAContainerWhoseDeclarationChangedIsReplaced(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAContainerThatMatchesIsLeftAlone(t *testing.T) {
|
||||
func testAContainerThatMatchesIsLeftAlone(t *testing.T) {
|
||||
d := parseTrusted(t, `{"declaration":1,"resources":[
|
||||
{"id":"store","type":"container","name":"store","image":"`+pinned+`","env":{"PGDATA":"/data"}}
|
||||
]}`)
|
||||
@@ -876,7 +876,7 @@ func TestAContainerThatMatchesIsLeftAlone(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAContainerIsRecreatedWhenARestartOnResourceChanged(t *testing.T) {
|
||||
func testAContainerIsRecreatedWhenARestartOnResourceChanged(t *testing.T) {
|
||||
// A container reads a mounted file once, at start. When the file changed this pass but the
|
||||
// container's spec did not, the plain "spec matches, leave it" rule would keep the process
|
||||
// holding the old value for ever, with every check passing (novox/hq 04-ISSUES/009). A
|
||||
@@ -933,7 +933,7 @@ func TestAContainerIsRecreatedWhenARestartOnResourceChanged(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestRestartOnFiresOnlyForResourcesThatChanged(t *testing.T) {
|
||||
func testRestartOnFiresOnlyForResourcesThatChanged(t *testing.T) {
|
||||
// restart-on must not mean "always restart": it names resources, and only a resource that
|
||||
// changed this pass is a reason. This is the guard shared by containers and services
|
||||
// (novox/hq 04-ISSUES/009), so a container that reflects an unchanged file is left running.
|
||||
@@ -987,7 +987,7 @@ func systemctlStub(t *testing.T, load, active, enabled string, verbs *[]string)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAServiceIsEnabledAtBootWhenAsked(t *testing.T) {
|
||||
func testAServiceIsEnabledAtBootWhenAsked(t *testing.T) {
|
||||
// The gap this closes: the host could start a unit and never make it survive a reboot, so
|
||||
// the declaration reported success and stopped being true at the next power cut.
|
||||
var verbs []string
|
||||
@@ -1008,7 +1008,7 @@ func TestAServiceIsEnabledAtBootWhenAsked(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestBootIsEnabledBeforeTheUnitIsStarted(t *testing.T) {
|
||||
func testBootIsEnabledBeforeTheUnitIsStarted(t *testing.T) {
|
||||
// Order matters when an apply fails part way. Enabled-and-stopped comes back at the next
|
||||
// boot; running-and-disabled does not. So the more durable half is made true first.
|
||||
var verbs []string
|
||||
@@ -1024,7 +1024,7 @@ func TestBootIsEnabledBeforeTheUnitIsStarted(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAlreadyEnabledAndRunningIsUnchanged(t *testing.T) {
|
||||
func testAlreadyEnabledAndRunningIsUnchanged(t *testing.T) {
|
||||
var verbs []string
|
||||
d := parseTrusted(t, `{"declaration":1,"resources":[
|
||||
{"id":"rt","type":"service","unit":"docker.service","state":"running","boot":"enabled"}
|
||||
@@ -1043,7 +1043,7 @@ func TestAlreadyEnabledAndRunningIsUnchanged(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestOmittingBootLeavesItAlone(t *testing.T) {
|
||||
func testOmittingBootLeavesItAlone(t *testing.T) {
|
||||
// Absent means the host asserts nothing. A machine whose operator enabled something must
|
||||
// not have it silently disabled because a declaration did not mention it.
|
||||
var verbs []string
|
||||
@@ -1061,7 +1061,7 @@ func TestOmittingBootLeavesItAlone(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAStaticUnitCannotBeEnabled(t *testing.T) {
|
||||
func testAStaticUnitCannotBeEnabled(t *testing.T) {
|
||||
// `static` is neither enabled nor disabled: the unit has no install section and CANNOT be
|
||||
// enabled. Reading it as "disabled" would have the host try, fail, and blame the wrong
|
||||
// thing — the same shape as reading a missing unit as "stopped".
|
||||
@@ -1080,7 +1080,7 @@ func TestAStaticUnitCannotBeEnabled(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnUnknownBootStateIsRefusedNotGuessed(t *testing.T) {
|
||||
func testAnUnknownBootStateIsRefusedNotGuessed(t *testing.T) {
|
||||
var verbs []string
|
||||
d := parseTrusted(t, `{"declaration":1,"resources":[
|
||||
{"id":"rt","type":"service","unit":"x.service","state":"running","boot":"enabled"}
|
||||
@@ -1094,7 +1094,7 @@ func TestAnUnknownBootStateIsRefusedNotGuessed(t *testing.T) {
|
||||
|
||||
// --- more than one container runtime (novox/hq ADR 0005) ---
|
||||
|
||||
func TestTheRuntimeProbeIsPerRuntime(t *testing.T) {
|
||||
func testTheRuntimeProbeIsPerRuntime(t *testing.T) {
|
||||
// Verified against a real podman 6.1.0 before this was written:
|
||||
//
|
||||
// docker info --format '{{.ServerVersion}}' -> 29.7.2
|
||||
@@ -1137,7 +1137,7 @@ func TestTheRuntimeProbeIsPerRuntime(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAContainerUsesTheRuntimeTheMachineHas(t *testing.T) {
|
||||
func testAContainerUsesTheRuntimeTheMachineHas(t *testing.T) {
|
||||
// The applier must not call `docker` on a machine that has podman. Adoption keeps what the
|
||||
// machine already has (novox/hq research 012), so hardcoding one contradicts it.
|
||||
var calledWith []string
|
||||
@@ -1175,7 +1175,7 @@ func TestAContainerUsesTheRuntimeTheMachineHas(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestNoRuntimeIsSaidPlainly(t *testing.T) {
|
||||
func testNoRuntimeIsSaidPlainly(t *testing.T) {
|
||||
// Naming what was tried, because "docker: command not found" on a machine that deliberately
|
||||
// runs podman sends the reader looking for the wrong thing.
|
||||
run := func(ctx context.Context, name string, args ...string) (string, error) {
|
||||
@@ -1208,7 +1208,7 @@ func archHost(t *testing.T) system.System {
|
||||
return s
|
||||
}
|
||||
|
||||
func TestAServiceIsRestartedWhenWhatItReflectsChanges(t *testing.T) {
|
||||
func testAServiceIsRestartedWhenWhatItReflectsChanges(t *testing.T) {
|
||||
// A running service does not re-read its configuration. Replace the file, find the service
|
||||
// already running, do nothing — and the machine keeps behaving as it did while every check
|
||||
// passes, because the file is right and the service is up.
|
||||
@@ -1326,7 +1326,7 @@ func TestAServiceIsRestartedWhenWhatItReflectsChanges(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAServiceIsNotRestartedByAChangeItDoesNotName(t *testing.T) {
|
||||
func testAServiceIsNotRestartedByAChangeItDoesNotName(t *testing.T) {
|
||||
// The list is what it reflects, not everything in the declaration. A service restarted by any
|
||||
// change anywhere would make every apply a fleet-wide bounce.
|
||||
dir := t.TempDir()
|
||||
@@ -1382,7 +1382,7 @@ func recordingServices(commands *[]string) Runner {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAFileChangedOnTheMachineIsCorrectedAndSaidSo(t *testing.T) {
|
||||
func testAFileChangedOnTheMachineIsCorrectedAndSaidSo(t *testing.T) {
|
||||
// The question this answers: how would anybody know somebody edited a managed file? Before
|
||||
// this they would not. It was rewritten within five minutes and reported as "updated",
|
||||
// which is what the mesh changing its mind looks like — so the person's change vanished and
|
||||
@@ -1424,7 +1424,7 @@ func TestAFileChangedOnTheMachineIsCorrectedAndSaidSo(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheMeshChangingItsMindIsNotDrift(t *testing.T) {
|
||||
func testTheMeshChangingItsMindIsNotDrift(t *testing.T) {
|
||||
// The other half. A new declaration is an ordinary update and must not read as somebody
|
||||
// having meddled, or every real change would look like an incident.
|
||||
dir := t.TempDir()
|
||||
@@ -1451,7 +1451,7 @@ func TestTheMeshChangingItsMindIsNotDrift(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnUntouchedFileIsStillUnchanged(t *testing.T) {
|
||||
func testAnUntouchedFileIsStillUnchanged(t *testing.T) {
|
||||
// And nothing about this makes a steady machine look busy.
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "thing.conf")
|
||||
@@ -1474,7 +1474,7 @@ func TestAnUntouchedFileIsStillUnchanged(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAFailedActionStopsWhatFollows(t *testing.T) {
|
||||
func testAFailedActionStopsWhatFollows(t *testing.T) {
|
||||
// An action is the only shape whose purpose is to make something true BEFORE the next thing
|
||||
// needs it, which is why it is the only one with a verify. The bootstrap is a row of them:
|
||||
// the store answers, then its databases exist, then their schemas, then the broker.
|
||||
@@ -1515,7 +1515,7 @@ func TestAFailedActionStopsWhatFollows(t *testing.T) {
|
||||
// `resolv.conf` — so every internal name the mesh wrote for the machine is invisible to what the
|
||||
// machine is running. That was hit for real: a database client on one node could not resolve
|
||||
// another node, on a mesh where both names were correct and present on both machines.
|
||||
func TestAContainerIsGivenTheMeshsNames(t *testing.T) {
|
||||
func testAContainerIsGivenTheMeshsNames(t *testing.T) {
|
||||
var ran []string
|
||||
run := func(_ context.Context, name string, args ...string) (string, error) {
|
||||
args = oldShape(name, args)
|
||||
@@ -1551,7 +1551,7 @@ func TestAContainerIsGivenTheMeshsNames(t *testing.T) {
|
||||
}
|
||||
|
||||
// And a container given no names is run exactly as before.
|
||||
func TestAContainerGivenNoNamesIsRunAsBefore(t *testing.T) {
|
||||
func testAContainerGivenNoNamesIsRunAsBefore(t *testing.T) {
|
||||
var ran []string
|
||||
run := func(_ context.Context, name string, args ...string) (string, error) {
|
||||
args = oldShape(name, args)
|
||||
@@ -1594,7 +1594,7 @@ func TestAContainerGivenNoNamesIsRunAsBefore(t *testing.T) {
|
||||
// waits: what depends on something being *usable* retries, which is what both example
|
||||
// provisioners do and is more robust than start ordering, because a dependency can also restart
|
||||
// long after everything was applied.
|
||||
func TestResourcesAreAppliedInTheOrderTheyWereDeclared(t *testing.T) {
|
||||
func testResourcesAreAppliedInTheOrderTheyWereDeclared(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
var order []string
|
||||
done := map[string]bool{}
|
||||
@@ -1656,7 +1656,7 @@ func TestResourcesAreAppliedInTheOrderTheyWereDeclared(t *testing.T) {
|
||||
// puts in a directory is itself a declared resource, and orphans are removed in reverse
|
||||
// declaration order — so what the mesh wrote is already gone by the time the directory is
|
||||
// reached. Anything still there was put there by something else.
|
||||
func TestADirectoryHoldingAnythingTheMeshDidNotPutThereIsKept(t *testing.T) {
|
||||
func testADirectoryHoldingAnythingTheMeshDidNotPutThereIsKept(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
data := filepath.Join(root, "keycloak")
|
||||
|
||||
@@ -1702,7 +1702,7 @@ func TestADirectoryHoldingAnythingTheMeshDidNotPutThereIsKept(t *testing.T) {
|
||||
}
|
||||
|
||||
// An empty one is the mesh's own, and goes.
|
||||
func TestAnEmptyDirectoryIsStillRemoved(t *testing.T) {
|
||||
func testAnEmptyDirectoryIsStillRemoved(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
mine := filepath.Join(root, "config")
|
||||
d := declare(t, `{"id":"c","type":"directory","path":"`+mine+`","mode":"0700"}`)
|
||||
@@ -1730,7 +1730,7 @@ func TestAnEmptyDirectoryIsStillRemoved(t *testing.T) {
|
||||
// replaced, and every check passes: the container is up, the spec matched, the machine reported
|
||||
// success. Making what a container reads part of what it is turns that from a tripwire into a
|
||||
// standing comparison.
|
||||
func TestAContainerStaleFromAnEarlierApplyIsReplaced(t *testing.T) {
|
||||
func testAContainerStaleFromAnEarlierApplyIsReplaced(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
conf := filepath.Join(dir, "db.env")
|
||||
// Already on disk with the current content, so this apply changes nothing at all.
|
||||
@@ -1781,7 +1781,7 @@ func TestAContainerStaleFromAnEarlierApplyIsReplaced(t *testing.T) {
|
||||
|
||||
// A seed is written once. What grows in it afterwards is somebody else's work the mesh asked for,
|
||||
// and a reconcile leaves it alone — content, mode and owner — and says so (novox/hq issue 035).
|
||||
func TestASeedIsCreatedOnceAndWhatGrowsInItIsKept(t *testing.T) {
|
||||
func testASeedIsCreatedOnceAndWhatGrowsInItIsKept(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "acl.conf")
|
||||
d := parse(t, fmt.Sprintf(`{"declaration":1,"resources":[
|
||||
@@ -1815,3 +1815,56 @@ func TestASeedIsCreatedOnceAndWhatGrowsInItIsKept(t *testing.T) {
|
||||
t.Fatalf("what grew in the seed was wiped: %q", grown)
|
||||
}
|
||||
}
|
||||
|
||||
// TestApply runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestApply(t *testing.T) {
|
||||
t.Run("ApplyingTwiceChangesNothingTheSecondTime", testApplyingTwiceChangesNothingTheSecondTime)
|
||||
t.Run("ADriftedMachineIsReturned", testADriftedMachineIsReturned)
|
||||
t.Run("ADroppedResourceIsRemoved", testADroppedResourceIsRemoved)
|
||||
t.Run("NothingTheHostDidNotCreateIsTouched", testNothingTheHostDidNotCreateIsTouched)
|
||||
t.Run("ARenameToTheSamePathDoesNotDeleteTheNewFile", testARenameToTheSamePathDoesNotDeleteTheNewFile)
|
||||
t.Run("AFailedResourceFailsTheApplyAndWhatFollowsIsAttemptedByWhoseItIs", testAFailedResourceFailsTheApplyAndWhatFollowsIsAttemptedByWhoseItIs)
|
||||
t.Run("NothingIsRecordedUntilItWorked", testNothingIsRecordedUntilItWorked)
|
||||
t.Run("AModeIsMaintainedNotJustSet", testAModeIsMaintainedNotJustSet)
|
||||
t.Run("AServiceIsReadBackNotAssumed", testAServiceIsReadBackNotAssumed)
|
||||
t.Run("AnUnknownServiceStateIsRefusedNotGuessed", testAnUnknownServiceStateIsRefusedNotGuessed)
|
||||
t.Run("ABootOneShotDeclaredStoppedIsSatisfiedAtRest", testABootOneShotDeclaredStoppedIsSatisfiedAtRest)
|
||||
t.Run("ADroppedServiceIsGivenBackTheStateItWasFoundIn", testADroppedServiceIsGivenBackTheStateItWasFoundIn)
|
||||
t.Run("AServiceRecordsTheStateItWasFoundInOnceAndCarriesIt", testAServiceRecordsTheStateItWasFoundInOnceAndCarriesIt)
|
||||
t.Run("AUnitThatDoesNotExistIsNotStopped", testAUnitThatDoesNotExistIsNotStopped)
|
||||
t.Run("AMaskedUnitIsRefused", testAMaskedUnitIsRefused)
|
||||
t.Run("ForgettingAUnitThatIsGoneDoesNotStrandTheNode", testForgettingAUnitThatIsGoneDoesNotStrandTheNode)
|
||||
t.Run("ABrokenPackageDatabaseIsNotReadAsNotInstalled", testABrokenPackageDatabaseIsNotReadAsNotInstalled)
|
||||
t.Run("AnInstalledPackageIsNotReinstalled", testAnInstalledPackageIsNotReinstalled)
|
||||
t.Run("APackageIsNeverUninstalled", testAPackageIsNeverUninstalled)
|
||||
t.Run("AnActionThatIsAlreadyTrueDoesNotRun", testAnActionThatIsAlreadyTrueDoesNotRun)
|
||||
t.Run("AnActionThatSucceedsAndDoesNothingFails", testAnActionThatSucceedsAndDoesNothingFails)
|
||||
t.Run("AnActionRunsInsideTheContainerItNames", testAnActionRunsInsideTheContainerItNames)
|
||||
t.Run("AContainerThatExitsImmediatelyFailsTheApply", testAContainerThatExitsImmediatelyFailsTheApply)
|
||||
t.Run("AContainerWhoseDeclarationChangedIsReplaced", testAContainerWhoseDeclarationChangedIsReplaced)
|
||||
t.Run("AContainerThatMatchesIsLeftAlone", testAContainerThatMatchesIsLeftAlone)
|
||||
t.Run("AContainerIsRecreatedWhenARestartOnResourceChanged", testAContainerIsRecreatedWhenARestartOnResourceChanged)
|
||||
t.Run("RestartOnFiresOnlyForResourcesThatChanged", testRestartOnFiresOnlyForResourcesThatChanged)
|
||||
t.Run("AServiceIsEnabledAtBootWhenAsked", testAServiceIsEnabledAtBootWhenAsked)
|
||||
t.Run("BootIsEnabledBeforeTheUnitIsStarted", testBootIsEnabledBeforeTheUnitIsStarted)
|
||||
t.Run("AlreadyEnabledAndRunningIsUnchanged", testAlreadyEnabledAndRunningIsUnchanged)
|
||||
t.Run("OmittingBootLeavesItAlone", testOmittingBootLeavesItAlone)
|
||||
t.Run("AStaticUnitCannotBeEnabled", testAStaticUnitCannotBeEnabled)
|
||||
t.Run("AnUnknownBootStateIsRefusedNotGuessed", testAnUnknownBootStateIsRefusedNotGuessed)
|
||||
t.Run("TheRuntimeProbeIsPerRuntime", testTheRuntimeProbeIsPerRuntime)
|
||||
t.Run("AContainerUsesTheRuntimeTheMachineHas", testAContainerUsesTheRuntimeTheMachineHas)
|
||||
t.Run("NoRuntimeIsSaidPlainly", testNoRuntimeIsSaidPlainly)
|
||||
t.Run("AServiceIsRestartedWhenWhatItReflectsChanges", testAServiceIsRestartedWhenWhatItReflectsChanges)
|
||||
t.Run("AServiceIsNotRestartedByAChangeItDoesNotName", testAServiceIsNotRestartedByAChangeItDoesNotName)
|
||||
t.Run("AFileChangedOnTheMachineIsCorrectedAndSaidSo", testAFileChangedOnTheMachineIsCorrectedAndSaidSo)
|
||||
t.Run("TheMeshChangingItsMindIsNotDrift", testTheMeshChangingItsMindIsNotDrift)
|
||||
t.Run("AnUntouchedFileIsStillUnchanged", testAnUntouchedFileIsStillUnchanged)
|
||||
t.Run("AFailedActionStopsWhatFollows", testAFailedActionStopsWhatFollows)
|
||||
t.Run("AContainerIsGivenTheMeshsNames", testAContainerIsGivenTheMeshsNames)
|
||||
t.Run("AContainerGivenNoNamesIsRunAsBefore", testAContainerGivenNoNamesIsRunAsBefore)
|
||||
t.Run("ResourcesAreAppliedInTheOrderTheyWereDeclared", testResourcesAreAppliedInTheOrderTheyWereDeclared)
|
||||
t.Run("ADirectoryHoldingAnythingTheMeshDidNotPutThereIsKept", testADirectoryHoldingAnythingTheMeshDidNotPutThereIsKept)
|
||||
t.Run("AnEmptyDirectoryIsStillRemoved", testAnEmptyDirectoryIsStillRemoved)
|
||||
t.Run("AContainerStaleFromAnEarlierApplyIsReplaced", testAContainerStaleFromAnEarlierApplyIsReplaced)
|
||||
t.Run("ASeedIsCreatedOnceAndWhatGrowsInItIsKept", testASeedIsCreatedOnceAndWhatGrowsInItIsKept)
|
||||
}
|
||||
|
||||
@@ -27,7 +27,7 @@ func archiveDecl(t *testing.T, id, path string, files map[string]string, more st
|
||||
`","path":"` + path + `"}` + more, digest
|
||||
}
|
||||
|
||||
func TestUnassigningAnArchiveRemovesExactlyWhatItUnpacked(t *testing.T) {
|
||||
func testUnassigningAnArchiveRemovesExactlyWhatItUnpacked(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
target := filepath.Join(dir, "bundles", "notes", "tools")
|
||||
archive, _ := archiveDecl(t, "notes.tools", target,
|
||||
@@ -71,7 +71,7 @@ func TestUnassigningAnArchiveRemovesExactlyWhatItUnpacked(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestADirectoryFoundBeforeTheArchiveKeepsWhatWasInIt(t *testing.T) {
|
||||
func testADirectoryFoundBeforeTheArchiveKeepsWhatWasInIt(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
target := filepath.Join(dir, "powerlevel10k")
|
||||
if err := os.MkdirAll(filepath.Join(target, "lib"), 0o755); err != nil {
|
||||
@@ -134,7 +134,7 @@ func TestADirectoryFoundBeforeTheArchiveKeepsWhatWasInIt(t *testing.T) {
|
||||
|
||||
// A file the archive would write over that the mesh did not put there refuses the archive, and the
|
||||
// directory is left exactly as it was.
|
||||
func TestAnArchiveDoesNotWriteOverAFileItFound(t *testing.T) {
|
||||
func testAnArchiveDoesNotWriteOverAFileItFound(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
target := filepath.Join(dir, "theme")
|
||||
os.MkdirAll(target, 0o755)
|
||||
@@ -247,7 +247,7 @@ func TestAnArchiveDoesNotWriteOverAFileItFound(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestADirectoryTheHostMadeGoesOnlyWhenEmpty(t *testing.T) {
|
||||
func testADirectoryTheHostMadeGoesOnlyWhenEmpty(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
target := filepath.Join(dir, "theme")
|
||||
archive, _ := archiveDecl(t, "shell.theme", target, map[string]string{"p10k.zsh": "t", "lib/a.zsh": "a"}, "")
|
||||
@@ -278,7 +278,7 @@ func TestADirectoryTheHostMadeGoesOnlyWhenEmpty(t *testing.T) {
|
||||
|
||||
// An archive recorded before the host kept what it unpacked cannot be told from anything else in
|
||||
// its directory: it is left in place, said and forgotten, and the apply goes on.
|
||||
func TestAnArchiveRecordedBeforeItsFilesWereKeptIsLeftAndForgotten(t *testing.T) {
|
||||
func testAnArchiveRecordedBeforeItsFilesWereKeptIsLeftAndForgotten(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
target := filepath.Join(dir, "tools")
|
||||
os.MkdirAll(target, 0o755)
|
||||
@@ -308,7 +308,7 @@ func TestAnArchiveRecordedBeforeItsFilesWereKeptIsLeftAndForgotten(t *testing.T)
|
||||
// One recorded before, still declared and unchanged, is read from its own bytes on the next apply,
|
||||
// so it can be undeclared from then on: the whole directory when it holds exactly the archive, only
|
||||
// the archive's files when it holds anything else.
|
||||
func TestAnArchiveRecordedBeforeLearnsWhatItUnpacked(t *testing.T) {
|
||||
func testAnArchiveRecordedBeforeLearnsWhatItUnpacked(t *testing.T) {
|
||||
for _, extra := range []bool{false, true} {
|
||||
dir := t.TempDir()
|
||||
target := filepath.Join(dir, "tools")
|
||||
@@ -352,3 +352,13 @@ func TestAnArchiveRecordedBeforeLearnsWhatItUnpacked(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestArchiveRemoval runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestArchiveRemoval(t *testing.T) {
|
||||
t.Run("UnassigningAnArchiveRemovesExactlyWhatItUnpacked", testUnassigningAnArchiveRemovesExactlyWhatItUnpacked)
|
||||
t.Run("ADirectoryFoundBeforeTheArchiveKeepsWhatWasInIt", testADirectoryFoundBeforeTheArchiveKeepsWhatWasInIt)
|
||||
t.Run("AnArchiveDoesNotWriteOverAFileItFound", testAnArchiveDoesNotWriteOverAFileItFound)
|
||||
t.Run("ADirectoryTheHostMadeGoesOnlyWhenEmpty", testADirectoryTheHostMadeGoesOnlyWhenEmpty)
|
||||
t.Run("AnArchiveRecordedBeforeItsFilesWereKeptIsLeftAndForgotten", testAnArchiveRecordedBeforeItsFilesWereKeptIsLeftAndForgotten)
|
||||
t.Run("AnArchiveRecordedBeforeLearnsWhatItUnpacked", testAnArchiveRecordedBeforeLearnsWhatItUnpacked)
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ import (
|
||||
|
||||
// novox/hq issue 220: the tree on disk is exactly the archive. A file the previous archive had and
|
||||
// this one does not is gone, and nothing is left beside the directory.
|
||||
func TestAnArchiveReplacesTheTreeItWasUnpackedOver(t *testing.T) {
|
||||
func testAnArchiveReplacesTheTreeItWasUnpackedOver(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
first, firstDigest := anArchive(t, map[string]string{"index.js": "old", "node_modules/dep/index.js": "dep"})
|
||||
d := declare(t, `{"id":"bundle-tools","type":"archive","source":"`+serving(t, first)+
|
||||
@@ -44,7 +44,7 @@ func TestAnArchiveReplacesTheTreeItWasUnpackedOver(t *testing.T) {
|
||||
|
||||
// A tree is replaced only by one that unpacked whole: an archive refused halfway leaves the old
|
||||
// tree as it was.
|
||||
func TestARefusedArchiveLeavesTheTreeItWouldHaveReplaced(t *testing.T) {
|
||||
func testARefusedArchiveLeavesTheTreeItWouldHaveReplaced(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
first, firstDigest := anArchive(t, map[string]string{"index.js": "old"})
|
||||
d := declare(t, `{"id":"bundle-tools","type":"archive","source":"`+serving(t, first)+
|
||||
@@ -66,3 +66,9 @@ func TestARefusedArchiveLeavesTheTreeItWouldHaveReplaced(t *testing.T) {
|
||||
t.Fatalf("%d entries beside the tree after a refused archive", len(entries))
|
||||
}
|
||||
}
|
||||
|
||||
// TestArchiveReplace runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestArchiveReplace(t *testing.T) {
|
||||
t.Run("AnArchiveReplacesTheTreeItWasUnpackedOver", testAnArchiveReplacesTheTreeItWasUnpackedOver)
|
||||
t.Run("ARefusedArchiveLeavesTheTreeItWouldHaveReplaced", testARefusedArchiveLeavesTheTreeItWouldHaveReplaced)
|
||||
}
|
||||
|
||||
@@ -75,7 +75,7 @@ const workstationHosts = "127.0.0.1\tlocalhost\n" +
|
||||
|
||||
const meshNames = "10.42.0.1 ace\n10.42.0.2 novox\n"
|
||||
|
||||
func TestABlockKeepsEveryLineOutsideItsMarkers(t *testing.T) {
|
||||
func testABlockKeepsEveryLineOutsideItsMarkers(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "hosts")
|
||||
if err := os.WriteFile(path, []byte(workstationHosts), 0o640); err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -129,7 +129,7 @@ func TestABlockKeepsEveryLineOutsideItsMarkers(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestUndeclaringABlockAddedAtTheEndGivesTheFileBackExactly(t *testing.T) {
|
||||
func testUndeclaringABlockAddedAtTheEndGivesTheFileBackExactly(t *testing.T) {
|
||||
for name, original := range map[string]string{
|
||||
"ending in a line": "127.0.0.1 localhost\n",
|
||||
"ending in a blank line": "127.0.0.1 localhost\n\n",
|
||||
@@ -147,7 +147,7 @@ func TestUndeclaringABlockAddedAtTheEndGivesTheFileBackExactly(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestABlockAddedAtTheEndIsSetApartFromTheMachinesLines(t *testing.T) {
|
||||
func testABlockAddedAtTheEndIsSetApartFromTheMachinesLines(t *testing.T) {
|
||||
for name, c := range map[string]struct{ before, after string }{
|
||||
"no line end": {"127.0.0.1 localhost", "127.0.0.1 localhost\n\n" + marked(namesID, meshNames)},
|
||||
"a line end": {"127.0.0.1 localhost\n", "127.0.0.1 localhost\n\n" + marked(namesID, meshNames)},
|
||||
@@ -167,7 +167,7 @@ func TestABlockAddedAtTheEndIsSetApartFromTheMachinesLines(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheRegionEndsInExactlyOneLineEnd(t *testing.T) {
|
||||
func testTheRegionEndsInExactlyOneLineEnd(t *testing.T) {
|
||||
for content, body := range map[string]string{
|
||||
"10.42.0.1 ace": "10.42.0.1 ace\n",
|
||||
"10.42.0.1 ace\n": "10.42.0.1 ace\n",
|
||||
@@ -188,7 +188,7 @@ func TestTheRegionEndsInExactlyOneLineEnd(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestARegionAlreadyThereIsRewrittenInPlaceAndGivenBack(t *testing.T) {
|
||||
func testARegionAlreadyThereIsRewrittenInPlaceAndGivenBack(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "hosts")
|
||||
before := "127.0.0.1 localhost\n"
|
||||
after := "# BEGIN devtool x\n127.0.0.1 x.test\n# END devtool x\n192.168.1.20 printer\n"
|
||||
@@ -218,7 +218,7 @@ func TestARegionAlreadyThereIsRewrittenInPlaceAndGivenBack(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestARegionWithNoRecordHoldingExactlyTheDeclaredLinesIsTheMeshs(t *testing.T) {
|
||||
func testARegionWithNoRecordHoldingExactlyTheDeclaredLinesIsTheMeshs(t *testing.T) {
|
||||
// A host that wrote the region and died before saving its state: what is between the markers
|
||||
// is exactly what the mesh declares, and remembered as the machine's it would never go.
|
||||
path := filepath.Join(t.TempDir(), "hosts")
|
||||
@@ -234,7 +234,7 @@ func TestARegionWithNoRecordHoldingExactlyTheDeclaredLinesIsTheMeshs(t *testing.
|
||||
}
|
||||
}
|
||||
|
||||
func TestADriftedRegionIsCorrected(t *testing.T) {
|
||||
func testADriftedRegionIsCorrected(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "hosts")
|
||||
_ = os.WriteFile(path, []byte(workstationHosts), 0o644)
|
||||
_, state := applyBlockDecl(t, blockDecl(t, path, meshNames), store.State{})
|
||||
@@ -260,7 +260,7 @@ func TestADriftedRegionIsCorrected(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestTwoRegionsInOneFileAreEachTheirOwn(t *testing.T) {
|
||||
func testTwoRegionsInOneFileAreEachTheirOwn(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "hosts")
|
||||
_ = os.WriteFile(path, []byte(workstationHosts), 0o644)
|
||||
raw := fmt.Sprintf(`{"declaration":1,"resources":[
|
||||
@@ -290,7 +290,7 @@ func TestTwoRegionsInOneFileAreEachTheirOwn(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestABlockInAFileThatWasNotThereIsCreatedAndRemovedWithIt(t *testing.T) {
|
||||
func testABlockInAFileThatWasNotThereIsCreatedAndRemovedWithIt(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "conf.d", "mesh.conf")
|
||||
report, state := applyBlockDecl(t, blockDecl(t, path, meshNames, `"mode":"0600"`), store.State{})
|
||||
if got := readText(t, path); got != marked(namesID, meshNames) {
|
||||
@@ -322,7 +322,7 @@ func TestABlockInAFileThatWasNotThereIsCreatedAndRemovedWithIt(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestMarkersThatDoNotPairAreRefusedAndLeftAlone(t *testing.T) {
|
||||
func testMarkersThatDoNotPairAreRefusedAndLeftAlone(t *testing.T) {
|
||||
for name, text := range map[string]string{
|
||||
"a begin with no end": "a\n# BEGIN mesh " + namesID + "\nb\n",
|
||||
"an end with no begin": "a\n# END mesh " + namesID + "\n",
|
||||
@@ -343,7 +343,7 @@ func TestMarkersThatDoNotPairAreRefusedAndLeftAlone(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAMarkerOfAnotherIDIsNotThisRegion(t *testing.T) {
|
||||
func testAMarkerOfAnotherIDIsNotThisRegion(t *testing.T) {
|
||||
// The id is part of the marker: a region whose id merely starts with this one is not it.
|
||||
path := filepath.Join(t.TempDir(), "hosts")
|
||||
other := marked(namesID+"-extra", "10.9.9.9 other\n")
|
||||
@@ -358,7 +358,7 @@ func TestAMarkerOfAnotherIDIsNotThisRegion(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestABlockAtTheStartStandsAboveEverything(t *testing.T) {
|
||||
func testABlockAtTheStartStandsAboveEverything(t *testing.T) {
|
||||
// dhcpcd scopes every line after `interface X` to that interface, so the mesh's global options
|
||||
// go above all of it.
|
||||
dhcpcd := "hostname\nduid\n\ninterface enp6s0\nstatic ip_address=192.168.1.5/24\n"
|
||||
@@ -399,7 +399,7 @@ func TestABlockAtTheStartStandsAboveEverything(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
func TestARegionAlreadyThereIsNotMovedWhereverAtSaysItGoes(t *testing.T) {
|
||||
func testARegionAlreadyThereIsNotMovedWhereverAtSaysItGoes(t *testing.T) {
|
||||
for _, at := range []string{`"at":"start"`, `"at":"end"`} {
|
||||
path := filepath.Join(t.TempDir(), "dhcpcd.conf")
|
||||
original := "hostname\n" + marked(namesID, "old\n") + "interface enp6s0\n"
|
||||
@@ -412,7 +412,7 @@ func TestARegionAlreadyThereIsNotMovedWhereverAtSaysItGoes(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAFileWrittenIntoABlockIsNeverHeldOnAnAdoptedNode(t *testing.T) {
|
||||
func testAFileWrittenIntoABlockIsNeverHeldOnAnAdoptedNode(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "hosts")
|
||||
_ = os.WriteFile(path, []byte(workstationHosts), 0o644)
|
||||
resource := fmt.Sprintf(`{"id":%q,"type":"file","path":%q,"into":"block","content":%q}`, namesID, path, meshNames)
|
||||
@@ -450,7 +450,7 @@ func TestAFileWrittenIntoABlockIsNeverHeldOnAnAdoptedNode(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheRecordOfABlockSurvivesTheStateFile(t *testing.T) {
|
||||
func testTheRecordOfABlockSurvivesTheStateFile(t *testing.T) {
|
||||
// What undeclaring needs is in the state a host saves, not only in memory.
|
||||
path := filepath.Join(t.TempDir(), "hosts")
|
||||
original := "a\n" + marked(namesID, "old\n")
|
||||
@@ -496,7 +496,7 @@ func applyKeepingIn(t *testing.T, raw string, known store.State, keepDir string)
|
||||
return report, state
|
||||
}
|
||||
|
||||
func TestAFileTheMeshWroteWholeAndMadeItselfKeepsOnlyItsLoopbackLines(t *testing.T) {
|
||||
func testAFileTheMeshWroteWholeAndMadeItselfKeepsOnlyItsLoopbackLines(t *testing.T) {
|
||||
// Written whole into a file that was not there, then declared as a block under the same id:
|
||||
// the old names must not stay above the region, where a resolver would answer from them first.
|
||||
path := filepath.Join(t.TempDir(), "hosts")
|
||||
@@ -523,7 +523,7 @@ func TestAFileTheMeshWroteWholeAndMadeItselfKeepsOnlyItsLoopbackLines(t *testing
|
||||
}
|
||||
}
|
||||
|
||||
func TestAFileTheMeshWroteWholeOverAnOriginalGetsTheOriginalBack(t *testing.T) {
|
||||
func testAFileTheMeshWroteWholeOverAnOriginalGetsTheOriginalBack(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "hosts")
|
||||
_ = os.WriteFile(path, []byte(workstationHosts), 0o644)
|
||||
keep := t.TempDir()
|
||||
@@ -544,7 +544,7 @@ func TestAFileTheMeshWroteWholeOverAnOriginalGetsTheOriginalBack(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAFileTheMeshWroteWholeAndSomebodyChangedIsWrittenIntoAsItStands(t *testing.T) {
|
||||
func testAFileTheMeshWroteWholeAndSomebodyChangedIsWrittenIntoAsItStands(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "hosts")
|
||||
_, state := applyKeepingIn(t, wholeDecl(path, oldWholeHosts), store.State{}, t.TempDir())
|
||||
edited := oldWholeHosts + "192.168.1.20 printer\n"
|
||||
@@ -558,7 +558,7 @@ func TestAFileTheMeshWroteWholeAndSomebodyChangedIsWrittenIntoAsItStands(t *test
|
||||
}
|
||||
}
|
||||
|
||||
func TestALinkedFileStaysALink(t *testing.T) {
|
||||
func testALinkedFileStaysALink(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
real := filepath.Join(dir, "static", "hosts")
|
||||
_ = os.MkdirAll(filepath.Dir(real), 0o755)
|
||||
@@ -583,7 +583,7 @@ func TestALinkedFileStaysALink(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestALastLineWithNoEndIsGivenBackWithNone(t *testing.T) {
|
||||
func testALastLineWithNoEndIsGivenBackWithNone(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "hosts")
|
||||
_ = os.WriteFile(path, []byte("x"), 0o644)
|
||||
_, state := applyBlockDecl(t, blockDecl(t, path, meshNames), store.State{})
|
||||
@@ -596,7 +596,7 @@ func TestALastLineWithNoEndIsGivenBackWithNone(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAFailedBlockWriteKeepsItsHold(t *testing.T) {
|
||||
func testAFailedBlockWriteKeepsItsHold(t *testing.T) {
|
||||
// Held from when it was declared whole, then declared as a block into a file whose markers do
|
||||
// not pair: the write is refused, and the hold — with where its original is — stays.
|
||||
path := filepath.Join(t.TempDir(), "hosts")
|
||||
@@ -616,3 +616,28 @@ func TestAFailedBlockWriteKeepsItsHold(t *testing.T) {
|
||||
t.Errorf("a failed write released the hold: %+v", state.Held)
|
||||
}
|
||||
}
|
||||
|
||||
// TestBlock runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestBlock(t *testing.T) {
|
||||
t.Run("ABlockKeepsEveryLineOutsideItsMarkers", testABlockKeepsEveryLineOutsideItsMarkers)
|
||||
t.Run("UndeclaringABlockAddedAtTheEndGivesTheFileBackExactly", testUndeclaringABlockAddedAtTheEndGivesTheFileBackExactly)
|
||||
t.Run("ABlockAddedAtTheEndIsSetApartFromTheMachinesLines", testABlockAddedAtTheEndIsSetApartFromTheMachinesLines)
|
||||
t.Run("TheRegionEndsInExactlyOneLineEnd", testTheRegionEndsInExactlyOneLineEnd)
|
||||
t.Run("ARegionAlreadyThereIsRewrittenInPlaceAndGivenBack", testARegionAlreadyThereIsRewrittenInPlaceAndGivenBack)
|
||||
t.Run("ARegionWithNoRecordHoldingExactlyTheDeclaredLinesIsTheMeshs", testARegionWithNoRecordHoldingExactlyTheDeclaredLinesIsTheMeshs)
|
||||
t.Run("ADriftedRegionIsCorrected", testADriftedRegionIsCorrected)
|
||||
t.Run("TwoRegionsInOneFileAreEachTheirOwn", testTwoRegionsInOneFileAreEachTheirOwn)
|
||||
t.Run("ABlockInAFileThatWasNotThereIsCreatedAndRemovedWithIt", testABlockInAFileThatWasNotThereIsCreatedAndRemovedWithIt)
|
||||
t.Run("MarkersThatDoNotPairAreRefusedAndLeftAlone", testMarkersThatDoNotPairAreRefusedAndLeftAlone)
|
||||
t.Run("AMarkerOfAnotherIDIsNotThisRegion", testAMarkerOfAnotherIDIsNotThisRegion)
|
||||
t.Run("ABlockAtTheStartStandsAboveEverything", testABlockAtTheStartStandsAboveEverything)
|
||||
t.Run("ARegionAlreadyThereIsNotMovedWhereverAtSaysItGoes", testARegionAlreadyThereIsNotMovedWhereverAtSaysItGoes)
|
||||
t.Run("AFileWrittenIntoABlockIsNeverHeldOnAnAdoptedNode", testAFileWrittenIntoABlockIsNeverHeldOnAnAdoptedNode)
|
||||
t.Run("TheRecordOfABlockSurvivesTheStateFile", testTheRecordOfABlockSurvivesTheStateFile)
|
||||
t.Run("AFileTheMeshWroteWholeAndMadeItselfKeepsOnlyItsLoopbackLines", testAFileTheMeshWroteWholeAndMadeItselfKeepsOnlyItsLoopbackLines)
|
||||
t.Run("AFileTheMeshWroteWholeOverAnOriginalGetsTheOriginalBack", testAFileTheMeshWroteWholeOverAnOriginalGetsTheOriginalBack)
|
||||
t.Run("AFileTheMeshWroteWholeAndSomebodyChangedIsWrittenIntoAsItStands", testAFileTheMeshWroteWholeAndSomebodyChangedIsWrittenIntoAsItStands)
|
||||
t.Run("ALinkedFileStaysALink", testALinkedFileStaysALink)
|
||||
t.Run("ALastLineWithNoEndIsGivenBackWithNone", testALastLineWithNoEndIsGivenBackWithNone)
|
||||
t.Run("AFailedBlockWriteKeepsItsHold", testAFailedBlockWriteKeepsItsHold)
|
||||
}
|
||||
|
||||
@@ -129,7 +129,7 @@ func applyBusy(t *testing.T, m *aBusyMachine, d *declaration.Declaration, known
|
||||
|
||||
// The decision's first check: an apply that would replace a container whose busy command exits 0 leaves it
|
||||
// running, applies the rest, and replaces it on the first pass the command exits non-zero.
|
||||
func TestABusyContainerIsLeftRunningAndReplacedOnTheFirstPassItSaysIdle(t *testing.T) {
|
||||
func testABusyContainerIsLeftRunningAndReplacedOnTheFirstPassItSaysIdle(t *testing.T) {
|
||||
now := time.Date(2026, 10, 13, 1, 0, 0, 0, time.UTC)
|
||||
atClock(t, &now)
|
||||
m := newBusyMachine()
|
||||
@@ -206,7 +206,7 @@ func TestABusyContainerIsLeftRunningAndReplacedOnTheFirstPassItSaysIdle(t *testi
|
||||
}
|
||||
|
||||
// An idle container is replaced at once, as one that declares nothing is: asked once, nothing waits.
|
||||
func TestAnIdleContainerIsReplacedAtOnce(t *testing.T) {
|
||||
func testAnIdleContainerIsReplacedAtOnce(t *testing.T) {
|
||||
m := newBusyMachine()
|
||||
_, state := applyBusy(t, m, twoContainers(t, "1", "1"), store.State{})
|
||||
m.answer(false, "")
|
||||
@@ -228,7 +228,7 @@ func TestAnIdleContainerIsReplacedAtOnce(t *testing.T) {
|
||||
|
||||
// Past the bound it is replaced anyway, the report carrying the command's last output — and the bound holds
|
||||
// across a restart of the node-engine: the wait is read back from the state on disk.
|
||||
func TestABusyContainerIsReplacedAtTheBoundEvenAfterARestart(t *testing.T) {
|
||||
func testABusyContainerIsReplacedAtTheBoundEvenAfterARestart(t *testing.T) {
|
||||
now := time.Date(2026, 10, 13, 1, 0, 0, 0, time.UTC)
|
||||
atClock(t, &now)
|
||||
m := newBusyMachine()
|
||||
@@ -274,7 +274,7 @@ func TestABusyContainerIsReplacedAtTheBoundEvenAfterARestart(t *testing.T) {
|
||||
|
||||
// While one container waits, a send that changes another module on the same machine is applied at once: the
|
||||
// apply returns after one ask, and holds nothing for the wait.
|
||||
func TestASendToAnotherModuleIsAppliedWhileOneWaits(t *testing.T) {
|
||||
func testASendToAnotherModuleIsAppliedWhileOneWaits(t *testing.T) {
|
||||
now := time.Date(2026, 10, 13, 1, 0, 0, 0, time.UTC)
|
||||
atClock(t, &now)
|
||||
m := newBusyMachine()
|
||||
@@ -305,7 +305,7 @@ func TestASendToAnotherModuleIsAppliedWhileOneWaits(t *testing.T) {
|
||||
}
|
||||
|
||||
// A container's busy is held to its shape where it arrives.
|
||||
func TestBusyIsReadAndHeldToItsShape(t *testing.T) {
|
||||
func testBusyIsReadAndHeldToItsShape(t *testing.T) {
|
||||
d := twoContainers(t, "1", "1")
|
||||
c := d.Resources[0].(*declaration.Container)
|
||||
if c.Busy == nil || c.Busy.Command != "mesh-builder busy" || c.Busy.Within() != 5*time.Second {
|
||||
@@ -330,7 +330,7 @@ func TestBusyIsReadAndHeldToItsShape(t *testing.T) {
|
||||
// directory (a service, an identity's or a library's change) is in no container's spec and counts as changed only
|
||||
// in the pass it changed, so the container must not read unchanged at the next pass and drop from the report as if
|
||||
// replaced (novox/hq ADR 0335).
|
||||
func TestAReplacementOwedToARestartTriggerIsMadeOnceIdle(t *testing.T) {
|
||||
func testAReplacementOwedToARestartTriggerIsMadeOnceIdle(t *testing.T) {
|
||||
now := time.Date(2026, 10, 13, 1, 0, 0, 0, time.UTC)
|
||||
atClock(t, &now)
|
||||
d := parse(t, `{"declaration":1,"resources":[
|
||||
@@ -368,7 +368,7 @@ func TestAReplacementOwedToARestartTriggerIsMadeOnceIdle(t *testing.T) {
|
||||
}
|
||||
|
||||
// A wait kept from a clock that later went back is never longer than the bound from now.
|
||||
func TestAWaitFromAClockThatWentBackIsClampedToNow(t *testing.T) {
|
||||
func testAWaitFromAClockThatWentBackIsClampedToNow(t *testing.T) {
|
||||
now := time.Date(2026, 10, 13, 1, 0, 0, 0, time.UTC)
|
||||
atClock(t, &now)
|
||||
m := newBusyMachine()
|
||||
@@ -384,7 +384,7 @@ func TestAWaitFromAClockThatWentBackIsClampedToNow(t *testing.T) {
|
||||
}
|
||||
|
||||
// An ask that fails — no shell in the image, a timeout, a paused container — is not busy: replaced at once.
|
||||
func TestAnAskThatFailsIsIdle(t *testing.T) {
|
||||
func testAnAskThatFailsIsIdle(t *testing.T) {
|
||||
m := newBusyMachine()
|
||||
_, state := applyBusy(t, m, twoContainers(t, "1", "1"), store.State{})
|
||||
failing := func(ctx context.Context, name string, args ...string) (string, error) {
|
||||
@@ -411,7 +411,7 @@ func TestAnAskThatFailsIsIdle(t *testing.T) {
|
||||
}
|
||||
|
||||
// A stopped container holds no work: it is replaced without being asked.
|
||||
func TestAStoppedContainerIsNotAsked(t *testing.T) {
|
||||
func testAStoppedContainerIsNotAsked(t *testing.T) {
|
||||
m := newBusyMachine()
|
||||
_, state := applyBusy(t, m, twoContainers(t, "1", "1"), store.State{})
|
||||
m.answer(true, "would say busy")
|
||||
@@ -432,3 +432,16 @@ func TestAStoppedContainerIsNotAsked(t *testing.T) {
|
||||
t.Fatalf("a stopped container was asked, or not replaced: %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestBusy runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestBusy(t *testing.T) {
|
||||
t.Run("ABusyContainerIsLeftRunningAndReplacedOnTheFirstPassItSaysIdle", testABusyContainerIsLeftRunningAndReplacedOnTheFirstPassItSaysIdle)
|
||||
t.Run("AnIdleContainerIsReplacedAtOnce", testAnIdleContainerIsReplacedAtOnce)
|
||||
t.Run("ABusyContainerIsReplacedAtTheBoundEvenAfterARestart", testABusyContainerIsReplacedAtTheBoundEvenAfterARestart)
|
||||
t.Run("ASendToAnotherModuleIsAppliedWhileOneWaits", testASendToAnotherModuleIsAppliedWhileOneWaits)
|
||||
t.Run("BusyIsReadAndHeldToItsShape", testBusyIsReadAndHeldToItsShape)
|
||||
t.Run("AReplacementOwedToARestartTriggerIsMadeOnceIdle", testAReplacementOwedToARestartTriggerIsMadeOnceIdle)
|
||||
t.Run("AWaitFromAClockThatWentBackIsClampedToNow", testAWaitFromAClockThatWentBackIsClampedToNow)
|
||||
t.Run("AnAskThatFailsIsIdle", testAnAskThatFailsIsIdle)
|
||||
t.Run("AStoppedContainerIsNotAsked", testAStoppedContainerIsNotAsked)
|
||||
}
|
||||
|
||||
@@ -14,7 +14,7 @@ func groupsContainer(groups ...int64) *declaration.Container {
|
||||
}
|
||||
|
||||
// 1637/AC1: both run commands carry one --group-add per group, and none without groups.
|
||||
func TestAContainerIsAddedItsSupplementaryGroups(t *testing.T) {
|
||||
func testAContainerIsAddedItsSupplementaryGroups(t *testing.T) {
|
||||
with := groupsContainer(2000, 2001)
|
||||
for name, args := range map[string][]string{
|
||||
"detached": detachedRunArgs(with, "x"),
|
||||
@@ -37,7 +37,7 @@ func TestAContainerIsAddedItsSupplementaryGroups(t *testing.T) {
|
||||
}
|
||||
|
||||
// 1637/AC2: a changed set of groups recreates the container; no groups leaves the spec as it was.
|
||||
func TestAChangeOfGroupsRecreatesTheContainer(t *testing.T) {
|
||||
func testAChangeOfGroupsRecreatesTheContainer(t *testing.T) {
|
||||
none, a, b := groupsContainer(), groupsContainer(2000), groupsContainer(2000, 2001)
|
||||
if containerSpec(none, inputs{}) == containerSpec(a, inputs{}) || containerSpec(a, inputs{}) == containerSpec(b, inputs{}) {
|
||||
t.Error("1637/AC2: a change of groups does not change the container's spec")
|
||||
@@ -52,3 +52,9 @@ func TestAChangeOfGroupsRecreatesTheContainer(t *testing.T) {
|
||||
t.Error("1637/AC2: a container with no groups has its spec moved")
|
||||
}
|
||||
}
|
||||
|
||||
// TestContainerGroups runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestContainerGroups(t *testing.T) {
|
||||
t.Run("AContainerIsAddedItsSupplementaryGroups", testAContainerIsAddedItsSupplementaryGroups)
|
||||
t.Run("AChangeOfGroupsRecreatesTheContainer", testAChangeOfGroupsRecreatesTheContainer)
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ import (
|
||||
|
||||
// A taken container keeps a found network by a per-machine setting (novox/hq ADR 0163, rule 4):
|
||||
// joined once it runs, part of its spec, and refused when it cannot be joined.
|
||||
func TestAContainerJoinsTheNetworksItKeeps(t *testing.T) {
|
||||
func testAContainerJoinsTheNetworksItKeeps(t *testing.T) {
|
||||
var ran []string
|
||||
connectFails := false
|
||||
run := func(_ context.Context, name string, args ...string) (string, error) {
|
||||
@@ -78,7 +78,7 @@ func TestAContainerJoinsTheNetworksItKeeps(t *testing.T) {
|
||||
|
||||
var specOfLast string
|
||||
|
||||
func TestACapabilityReachesTheRuntimeAndTheSpec(t *testing.T) {
|
||||
func testACapabilityReachesTheRuntimeAndTheSpec(t *testing.T) {
|
||||
var ran []string
|
||||
run := func(_ context.Context, name string, args ...string) (string, error) {
|
||||
args = oldShape(name, args)
|
||||
@@ -119,7 +119,7 @@ func TestACapabilityReachesTheRuntimeAndTheSpec(t *testing.T) {
|
||||
|
||||
// A package may be declared absent (novox/hq ADR 0180): removed when it is installed, read back,
|
||||
// left alone when it is not.
|
||||
func TestAPackageDeclaredAbsentIsRemovedWhenPresentAndLeftWhenNot(t *testing.T) {
|
||||
func testAPackageDeclaredAbsentIsRemovedWhenPresentAndLeftWhenNot(t *testing.T) {
|
||||
installed := true
|
||||
var ran []string
|
||||
run := func(_ context.Context, name string, args ...string) (string, error) {
|
||||
@@ -156,3 +156,10 @@ func TestAPackageDeclaredAbsentIsRemovedWhenPresentAndLeftWhenNot(t *testing.T)
|
||||
t.Fatalf("a package already absent was touched: %+v\n%v", report.Outcomes[0], ran)
|
||||
}
|
||||
}
|
||||
|
||||
// TestContainersKept runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestContainersKept(t *testing.T) {
|
||||
t.Run("AContainerJoinsTheNetworksItKeeps", testAContainerJoinsTheNetworksItKeeps)
|
||||
t.Run("ACapabilityReachesTheRuntimeAndTheSpec", testACapabilityReachesTheRuntimeAndTheSpec)
|
||||
t.Run("APackageDeclaredAbsentIsRemovedWhenPresentAndLeftWhenNot", testAPackageDeclaredAbsentIsRemovedWhenPresentAndLeftWhenNot)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
package apply
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"git.novox.be/novox/mesh-sdk/go/declaration"
|
||||
"github.com/novox/mesh-host/internal/store"
|
||||
)
|
||||
|
||||
// ConvergeDirectories gives each directory entry of d whose record known holds, found on disk with another owner or mode
|
||||
// than declared, its declared owner and mode (design 47 H2's E lines, H-A-374, H-A-392): at the engine's start, so a
|
||||
// drift lasts at most until then, and with no apply of an unchanged composition. One the mesh never made (its record used
|
||||
// as found, issue 339) is left as found and said. Answered as one line per directory set right or left; a directory
|
||||
// declared that is missing, that has no record, or that is as declared, says nothing.
|
||||
func ConvergeDirectories(d *declaration.Declaration, known store.State) []string {
|
||||
if d == nil {
|
||||
return nil
|
||||
}
|
||||
var lines []string
|
||||
for _, r := range d.Resources {
|
||||
dir, ok := r.(*declaration.Directory)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
rec, held := known.Find(dir.ID)
|
||||
if !held || rec.Type != string(declaration.TypeDirectory) {
|
||||
continue
|
||||
}
|
||||
drift, err := directoryDrift(dir)
|
||||
switch {
|
||||
case errors.Is(err, os.ErrNotExist) || (err == nil && drift == ""):
|
||||
continue
|
||||
case err != nil:
|
||||
lines = append(lines, fmt.Sprintf("%s (%s) cannot be judged at this start: %v", dir.Path, dir.ID, err))
|
||||
continue
|
||||
}
|
||||
out, err := applyDirectory(dir, rec, true)
|
||||
switch {
|
||||
case err != nil:
|
||||
lines = append(lines, fmt.Sprintf("%s (%s) is %s and cannot be set right at this start: %v", dir.Path, dir.ID, drift, err))
|
||||
case out.asFound:
|
||||
lines = append(lines, fmt.Sprintf("%s (%s) is %s, and is left as found at this start: %s", dir.Path, dir.ID, drift, out.Detail))
|
||||
default:
|
||||
lines = append(lines, fmt.Sprintf("%s (%s) was %s, and is set right at this start", dir.Path, dir.ID, drift))
|
||||
}
|
||||
}
|
||||
return lines
|
||||
}
|
||||
|
||||
// DirectoryDrift is one directory entry the mesh made, as its record holds, whose owner or mode on disk differ from
|
||||
// what is declared (H-A-392): its id, its path and how it differs, in words.
|
||||
type DirectoryDrift struct {
|
||||
ID string `json:"id"`
|
||||
Path string `json:"path"`
|
||||
Drift string `json:"drift"`
|
||||
}
|
||||
|
||||
// DirectoryDrifts is each directory entry of d the mesh made, by its record in known (not used as found), whose owner or
|
||||
// mode on disk differ from its entry's (H-A-392): read-only, what the verb composition's diff names as drift. A directory
|
||||
// that is missing, has no record, or cannot be read says nothing here.
|
||||
func DirectoryDrifts(d *declaration.Declaration, known store.State) []DirectoryDrift {
|
||||
if d == nil {
|
||||
return nil
|
||||
}
|
||||
var out []DirectoryDrift
|
||||
for _, r := range d.Resources {
|
||||
dir, ok := r.(*declaration.Directory)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if rec, held := known.Find(dir.ID); !held || rec.Type != string(declaration.TypeDirectory) || rec.AsFound {
|
||||
continue
|
||||
}
|
||||
if drift, err := directoryDrift(dir); err == nil && drift != "" {
|
||||
out = append(out, DirectoryDrift{ID: dir.ID, Path: dir.Path, Drift: drift})
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// directoryDrift says how a directory on disk differs from its entry's owner and mode, in words; empty when it does not.
|
||||
func directoryDrift(dir *declaration.Directory) (string, error) {
|
||||
mode, err := dirModeOf(dir.Mode, 0o755)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
info, err := os.Lstat(dir.Path)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if !info.IsDir() {
|
||||
return "", fmt.Errorf("%s is not a directory", dir.Path)
|
||||
}
|
||||
owned, err := ownedBy(dir.Path, dir.Owner)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
var drift string
|
||||
if dirBits(info.Mode()) != dirBits(mode) {
|
||||
drift = fmt.Sprintf("mode %s, %s declared", modeText(dirBits(info.Mode())), modeText(mode))
|
||||
}
|
||||
if !owned {
|
||||
if drift != "" {
|
||||
drift += ", and "
|
||||
}
|
||||
drift += fmt.Sprintf("owned by %s, %s declared", ownerText(info), dir.Owner)
|
||||
}
|
||||
return drift, nil
|
||||
}
|
||||
@@ -27,7 +27,7 @@ func declaredHomeFixture(t *testing.T) (home string, user *declaration.User) {
|
||||
}
|
||||
|
||||
// 1542/AC1: the .ssh of a declared account, owned by it, is refused by nothing.
|
||||
func TestIssue1542ADeclaredAccountsSSHIsPlaced(t *testing.T) {
|
||||
func testIssue1542ADeclaredAccountsSSHIsPlaced(t *testing.T) {
|
||||
home, user := declaredHomeFixture(t)
|
||||
ssh := &declaration.Directory{ID: "mesh-build-go.ssh-dir", Type: declaration.TypeDirectory, Path: home + "/.ssh",
|
||||
Mode: "0700", Owner: "mesh-build-go"}
|
||||
@@ -45,7 +45,7 @@ func TestIssue1542ADeclaredAccountsSSHIsPlaced(t *testing.T) {
|
||||
|
||||
// 1542/AC2: another account's directory below the declared home is refused as below any home, and a .ssh below
|
||||
// no home of the machine or the declaration is refused with today's words.
|
||||
func TestIssue1542OnlyTheDeclaredAccountsOwnIsPlaced(t *testing.T) {
|
||||
func testIssue1542OnlyTheDeclaredAccountsOwnIsPlaced(t *testing.T) {
|
||||
home, user := declaredHomeFixture(t)
|
||||
other := &declaration.Directory{ID: "notes.ssh-dir", Type: declaration.TypeDirectory, Path: home + "/.ssh",
|
||||
Mode: "0700", Owner: "intruder"}
|
||||
@@ -76,7 +76,7 @@ func TestIssue1542OnlyTheDeclaredAccountsOwnIsPlaced(t *testing.T) {
|
||||
}
|
||||
|
||||
// 1542/AC3: a declared account is no home to anyone but the directory placement guard.
|
||||
func TestIssue1542DeclaredAccountsAreNotHomesToTheOtherGuards(t *testing.T) {
|
||||
func testIssue1542DeclaredAccountsAreNotHomesToTheOtherGuards(t *testing.T) {
|
||||
home, user := declaredHomeFixture(t)
|
||||
_ = refusedPlaces([]declaration.Resource{user})
|
||||
if _, ok := accountsOfHomes()[home]; ok {
|
||||
@@ -89,7 +89,7 @@ func TestIssue1542DeclaredAccountsAreNotHomesToTheOtherGuards(t *testing.T) {
|
||||
|
||||
// A declared account is added as a home and never takes one over (reviewer, issue 1542): the person's own .ssh
|
||||
// stays refused to every other account, whatever a declaration says about a user.
|
||||
func TestIssue1542ADeclaredAccountTakesNoExistingHome(t *testing.T) {
|
||||
func testIssue1542ADeclaredAccountTakesNoExistingHome(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
passwd := filepath.Join(dir, "passwd")
|
||||
body := "root:x:0:0::/root:/bin/sh\njochen:x:1000:1000::/home/jochen:/bin/sh\n" +
|
||||
@@ -140,7 +140,7 @@ func TestIssue1542ADeclaredAccountTakesNoExistingHome(t *testing.T) {
|
||||
|
||||
// The account the mesh made, as declared, is judged the same at the next apply (issue 1542): once it is in the
|
||||
// user database with exactly the declared home, its .ssh is still placed.
|
||||
func TestIssue1542TheAccountTheMeshMadeIsStillPlacedAtTheNextApply(t *testing.T) {
|
||||
func testIssue1542TheAccountTheMeshMadeIsStillPlacedAtTheNextApply(t *testing.T) {
|
||||
home, user := declaredHomeFixture(t)
|
||||
ssh := &declaration.Directory{ID: "mesh-build-go.ssh-dir", Type: declaration.TypeDirectory, Path: home + "/.ssh",
|
||||
Mode: "0700", Owner: "mesh-build-go"}
|
||||
@@ -156,3 +156,12 @@ func TestIssue1542TheAccountTheMeshMadeIsStillPlacedAtTheNextApply(t *testing.T)
|
||||
t.Fatalf("second apply, the account made as declared: %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDeclaredHome runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestDeclaredHome(t *testing.T) {
|
||||
t.Run("Issue1542ADeclaredAccountsSSHIsPlaced", testIssue1542ADeclaredAccountsSSHIsPlaced)
|
||||
t.Run("Issue1542OnlyTheDeclaredAccountsOwnIsPlaced", testIssue1542OnlyTheDeclaredAccountsOwnIsPlaced)
|
||||
t.Run("Issue1542DeclaredAccountsAreNotHomesToTheOtherGuards", testIssue1542DeclaredAccountsAreNotHomesToTheOtherGuards)
|
||||
t.Run("Issue1542ADeclaredAccountTakesNoExistingHome", testIssue1542ADeclaredAccountTakesNoExistingHome)
|
||||
t.Run("Issue1542TheAccountTheMeshMadeIsStillPlacedAtTheNextApply", testIssue1542TheAccountTheMeshMadeIsStillPlacedAtTheNextApply)
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ import (
|
||||
// A take is a comparison (novox/hq ADR 0163): while a module's container is held, the host reports
|
||||
// the found image and its age beside the declared one, the networks and who else is on them, the
|
||||
// mounts and the ports — and says when the declared image is the older.
|
||||
func TestAHeldContainerCarriesTheFactsATakeCompares(t *testing.T) {
|
||||
func testAHeldContainerCarriesTheFactsATakeCompares(t *testing.T) {
|
||||
dir, page, m := predecessor(t)
|
||||
m.containers["hello-web"].image = "web:1.27"
|
||||
m.containers["hello-web"].imageID = "sha256:found"
|
||||
@@ -54,7 +54,7 @@ func TestAHeldContainerCarriesTheFactsATakeCompares(t *testing.T) {
|
||||
}
|
||||
|
||||
// A declared image not yet on the machine leaves its age unknown and the comparison undecided.
|
||||
func TestAnImageNotYetPulledLeavesTheDowngradeUndecided(t *testing.T) {
|
||||
func testAnImageNotYetPulledLeavesTheDowngradeUndecided(t *testing.T) {
|
||||
dir, page, m := predecessor(t)
|
||||
m.containers["hello-web"].image = "web:1.27"
|
||||
m.containers["hello-web"].imageID = "sha256:found"
|
||||
@@ -66,7 +66,7 @@ func TestAnImageNotYetPulledLeavesTheDowngradeUndecided(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheDifferenceIsWhatIsLostAndWhatIsNew(t *testing.T) {
|
||||
func testTheDifferenceIsWhatIsLostAndWhatIsNew(t *testing.T) {
|
||||
differs, lines := differenceOf("a\nprivate scope: local\nb\n", "a\nb\nupstream: public\n")
|
||||
if !differs || len(lines) != 2 || lines[0] != "- private scope: local" || lines[1] != "+ upstream: public" {
|
||||
t.Fatalf("got %v %v", differs, lines)
|
||||
@@ -77,7 +77,7 @@ func TestTheDifferenceIsWhatIsLostAndWhatIsNew(t *testing.T) {
|
||||
}
|
||||
|
||||
// What runs on the machine that the mesh neither wrote nor holds is reported (ADR 0163).
|
||||
func TestStraysAreWhatRunsHereThatNobodyAsked(t *testing.T) {
|
||||
func testStraysAreWhatRunsHereThatNobodyAsked(t *testing.T) {
|
||||
m := &machine{containers: map[string]*fakeContainer{
|
||||
"hello-web": {id: "ours", running: true, image: "web:1"},
|
||||
"gitea-old": {id: "left-behind", running: true, image: "gitea:1.22"},
|
||||
@@ -95,3 +95,11 @@ func TestStraysAreWhatRunsHereThatNobodyAsked(t *testing.T) {
|
||||
t.Fatalf("strays: %+v", strays)
|
||||
}
|
||||
}
|
||||
|
||||
// TestFacts runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestFacts(t *testing.T) {
|
||||
t.Run("AHeldContainerCarriesTheFactsATakeCompares", testAHeldContainerCarriesTheFactsATakeCompares)
|
||||
t.Run("AnImageNotYetPulledLeavesTheDowngradeUndecided", testAnImageNotYetPulledLeavesTheDowngradeUndecided)
|
||||
t.Run("TheDifferenceIsWhatIsLostAndWhatIsNew", testTheDifferenceIsWhatIsLostAndWhatIsNew)
|
||||
t.Run("StraysAreWhatRunsHereThatNobodyAsked", testStraysAreWhatRunsHereThatNobodyAsked)
|
||||
}
|
||||
|
||||
@@ -51,7 +51,7 @@ func watching(t *testing.T, path string) Runner {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAWholeFileIsHandedToItsNewOwnerNotRemoved(t *testing.T) {
|
||||
func testAWholeFileIsHandedToItsNewOwnerNotRemoved(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "resolv.conf")
|
||||
if err := os.WriteFile(path, []byte(theOriginal), 0o644); err != nil {
|
||||
@@ -117,7 +117,7 @@ func TestAWholeFileIsHandedToItsNewOwnerNotRemoved(t *testing.T) {
|
||||
|
||||
// A file the mesh made where there was none is handed over the same way, and is still the mesh's —
|
||||
// undeclared, it goes.
|
||||
func TestAFileTheMeshMadeIsHandedOverAndStillGoesWithItsLastOwner(t *testing.T) {
|
||||
func testAFileTheMeshMadeIsHandedOverAndStillGoesWithItsLastOwner(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "resolv.conf")
|
||||
run := watching(t, path)
|
||||
_, state, err := Apply(context.Background(), archHost(t), parse(t, heldBy(t, path, "resolv-conf", firstOwners)),
|
||||
@@ -144,7 +144,7 @@ func TestAFileTheMeshMadeIsHandedOverAndStillGoesWithItsLastOwner(t *testing.T)
|
||||
|
||||
// A file edited on the machine since the first owner wrote it is still corrected and said so by the
|
||||
// new owner: the handover judges drift against what this host last wrote there.
|
||||
func TestAHandedOverFileChangedOnTheMachineIsSaidCorrected(t *testing.T) {
|
||||
func testAHandedOverFileChangedOnTheMachineIsSaidCorrected(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "resolv.conf")
|
||||
_, state, err := Apply(context.Background(), archHost(t), parse(t, heldBy(t, path, "resolv-conf", firstOwners)),
|
||||
store.State{}, store.OriginDeclared, recordingServices(new([]string)), nil, nil)
|
||||
@@ -165,7 +165,7 @@ func TestAHandedOverFileChangedOnTheMachineIsSaidCorrected(t *testing.T) {
|
||||
}
|
||||
|
||||
// The preview says the same before it happens.
|
||||
func TestThePlanHandsAFileOverRatherThanRemovingIt(t *testing.T) {
|
||||
func testThePlanHandsAFileOverRatherThanRemovingIt(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "resolv.conf")
|
||||
_, state, err := Apply(context.Background(), archHost(t), parse(t, heldBy(t, path, "resolv-conf", firstOwners)),
|
||||
store.State{}, store.OriginDeclared, recordingServices(new([]string)), nil, nil)
|
||||
@@ -178,3 +178,11 @@ func TestThePlanHandsAFileOverRatherThanRemovingIt(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestFileHandover runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestFileHandover(t *testing.T) {
|
||||
t.Run("AWholeFileIsHandedToItsNewOwnerNotRemoved", testAWholeFileIsHandedToItsNewOwnerNotRemoved)
|
||||
t.Run("AFileTheMeshMadeIsHandedOverAndStillGoesWithItsLastOwner", testAFileTheMeshMadeIsHandedOverAndStillGoesWithItsLastOwner)
|
||||
t.Run("AHandedOverFileChangedOnTheMachineIsSaidCorrected", testAHandedOverFileChangedOnTheMachineIsSaidCorrected)
|
||||
t.Run("ThePlanHandsAFileOverRatherThanRemovingIt", testThePlanHandsAFileOverRatherThanRemovingIt)
|
||||
}
|
||||
|
||||
@@ -19,7 +19,7 @@ import (
|
||||
|
||||
// An apply leaves a filled file alone, whatever who owns it at runtime says: absent stays absent and is not
|
||||
// recorded, and what the verb wrote stays as it wrote it through every re-apply.
|
||||
func TestAnApplyNeverWritesAFilledFile(t *testing.T) {
|
||||
func testAnApplyNeverWritesAFilledFile(t *testing.T) {
|
||||
for _, c := range []struct{ name, fields, content string }{
|
||||
{"owned", `"content":"","mode":"0640","owner-at-runtime":"owned"`, "port = 8080\n"},
|
||||
{"seed", `"content":"","mode":"0600","owner-at-runtime":"seed"`, "user default on\n"},
|
||||
@@ -78,7 +78,7 @@ func TestAnApplyNeverWritesAFilledFile(t *testing.T) {
|
||||
|
||||
// What reads a filled file is moved by the verb's write, once, never again by an apply: a service under
|
||||
// restart-on is not restarted and a container reading it is not recreated by the re-apply.
|
||||
func TestAnApplyMovesNothingForAFilledFile(t *testing.T) {
|
||||
func testAnApplyMovesNothingForAFilledFile(t *testing.T) {
|
||||
env := filepath.Join(t.TempDir(), "forge.env")
|
||||
d := filledDecl(t, env, `"content":"","mode":"0600","owner-at-runtime":"owned"`,
|
||||
`{"id":"forge.server","type":"container","name":"forge","image":"`+pinned+`","env-file":["`+env+`"]}`)
|
||||
@@ -121,7 +121,7 @@ func TestAnApplyMovesNothingForAFilledFile(t *testing.T) {
|
||||
|
||||
// A filled file the verb never placed is not the mesh's to remove: one found there, or put there by hand, stays
|
||||
// when the file leaves the declaration.
|
||||
func TestAFilledFileTheVerbNeverPlacedIsNotRemoved(t *testing.T) {
|
||||
func testAFilledFileTheVerbNeverPlacedIsNotRemoved(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "the-file")
|
||||
if err := os.WriteFile(path, []byte("the machine's own\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -151,7 +151,7 @@ func TestAFilledFileTheVerbNeverPlacedIsNotRemoved(t *testing.T) {
|
||||
|
||||
// What the verb placed is the mesh's: when the file leaves the declaration it is removed as an orphan, as a file
|
||||
// an apply wrote is.
|
||||
func TestAFilledFileTheVerbPlacedIsRemovedWhenItLeaves(t *testing.T) {
|
||||
func testAFilledFileTheVerbPlacedIsRemovedWhenItLeaves(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "the-file")
|
||||
d := filledDecl(t, path, `"content":"","owner-at-runtime":"owned"`, "")
|
||||
_, state, err := Apply(context.Background(), archHost(t), d, store.State{}, store.OriginDeclared, noServices,
|
||||
@@ -184,7 +184,7 @@ func TestAFilledFileTheVerbPlacedIsRemovedWhenItLeaves(t *testing.T) {
|
||||
// A file the mesh wrote the old way and that is now filled keeps its record for the verb to judge against, and is
|
||||
// not written over by the apply that hands it to the client; a file at the same path recorded under another id
|
||||
// is handed to the filled one, not removed.
|
||||
func TestAFileThatMovesToTheClientIsHandedNotRewritten(t *testing.T) {
|
||||
func testAFileThatMovesToTheClientIsHandedNotRewritten(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "the-file")
|
||||
old := parseTrusted(t, fmt.Sprintf(`{"declaration":1,"resources":[{"id":"m.old","type":"file","path":%q,`+
|
||||
`"content":"port = 1\n"}]}`, path))
|
||||
@@ -216,3 +216,12 @@ func elsewhere(t *testing.T) *declaration.Declaration {
|
||||
return parseTrusted(t, fmt.Sprintf(`{"declaration":1,"resources":[{"id":"n.other","type":"file","path":%q,`+
|
||||
`"content":"x\n"}]}`, filepath.Join(t.TempDir(), "other")))
|
||||
}
|
||||
|
||||
// TestFilledApply runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestFilledApply(t *testing.T) {
|
||||
t.Run("AnApplyNeverWritesAFilledFile", testAnApplyNeverWritesAFilledFile)
|
||||
t.Run("AnApplyMovesNothingForAFilledFile", testAnApplyMovesNothingForAFilledFile)
|
||||
t.Run("AFilledFileTheVerbNeverPlacedIsNotRemoved", testAFilledFileTheVerbNeverPlacedIsNotRemoved)
|
||||
t.Run("AFilledFileTheVerbPlacedIsRemovedWhenItLeaves", testAFilledFileTheVerbPlacedIsRemovedWhenItLeaves)
|
||||
t.Run("AFileThatMovesToTheClientIsHandedNotRewritten", testAFileThatMovesToTheClientIsHandedNotRewritten)
|
||||
}
|
||||
|
||||
@@ -70,7 +70,7 @@ func refusedAsPlacement(t *testing.T, err error) {
|
||||
}
|
||||
|
||||
// 1138/AC1: a filled write asks no runtime, and judges with the roots the last apply read.
|
||||
func TestAFilledWriteAsksNoRuntimeAndUsesTheLastApplysRoots(t *testing.T) {
|
||||
func testAFilledWriteAsksNoRuntimeAndUsesTheLastApplysRoots(t *testing.T) {
|
||||
root := filepath.Join(t.TempDir(), "docker-root")
|
||||
setRuntimeRoots(t, []string{root}) // as if an apply had just read it
|
||||
|
||||
@@ -90,7 +90,7 @@ func TestAFilledWriteAsksNoRuntimeAndUsesTheLastApplysRoots(t *testing.T) {
|
||||
|
||||
// 1138/AC2: given a real apply that read a runtime data root, a filled write below it is refused as today, with
|
||||
// no apply run again in between.
|
||||
func TestAFilledWriteBelowARootARealApplyReadIsRefused(t *testing.T) {
|
||||
func testAFilledWriteBelowARootARealApplyReadIsRefused(t *testing.T) {
|
||||
dir, root := aRuntimeConfig(t)
|
||||
t.Cleanup(func() {
|
||||
runtimeRootsMu.Lock()
|
||||
@@ -116,7 +116,7 @@ func TestAFilledWriteBelowARootARealApplyReadIsRefused(t *testing.T) {
|
||||
|
||||
// 1138/AC3: with no apply having read the roots yet, a filled write judges by the runtimes' configuration files,
|
||||
// asking no runtime.
|
||||
func TestAFilledWriteWithNoApplyYetUsesTheRuntimesConfigFiles(t *testing.T) {
|
||||
func testAFilledWriteWithNoApplyYetUsesTheRuntimesConfigFiles(t *testing.T) {
|
||||
setRuntimeRoots(t, nil) // no apply has read the roots yet
|
||||
_, root := aRuntimeConfig(t)
|
||||
|
||||
@@ -135,7 +135,7 @@ func TestAFilledWriteWithNoApplyYetUsesTheRuntimesConfigFiles(t *testing.T) {
|
||||
}
|
||||
|
||||
// 1138/AC4: a full apply still asks each runtime once, at its start, whatever the number of files it writes.
|
||||
func TestAFullApplyAsksEachRuntimeOnceRegardlessOfFileCount(t *testing.T) {
|
||||
func testAFullApplyAsksEachRuntimeOnceRegardlessOfFileCount(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
var asked []string
|
||||
before := AskRuntimes
|
||||
@@ -166,3 +166,11 @@ func TestAFullApplyAsksEachRuntimeOnceRegardlessOfFileCount(t *testing.T) {
|
||||
t.Errorf("podman was asked %d times for one apply of 3 files; want 1: %v", got, asked)
|
||||
}
|
||||
}
|
||||
|
||||
// TestFilledRuntimeRoots runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestFilledRuntimeRoots(t *testing.T) {
|
||||
t.Run("AFilledWriteAsksNoRuntimeAndUsesTheLastApplysRoots", testAFilledWriteAsksNoRuntimeAndUsesTheLastApplysRoots)
|
||||
t.Run("AFilledWriteBelowARootARealApplyReadIsRefused", testAFilledWriteBelowARootARealApplyReadIsRefused)
|
||||
t.Run("AFilledWriteWithNoApplyYetUsesTheRuntimesConfigFiles", testAFilledWriteWithNoApplyYetUsesTheRuntimesConfigFiles)
|
||||
t.Run("AFullApplyAsksEachRuntimeOnceRegardlessOfFileCount", testAFullApplyAsksEachRuntimeOnceRegardlessOfFileCount)
|
||||
}
|
||||
|
||||
@@ -28,7 +28,7 @@ func filledDecl(t *testing.T, path, fields, more string) *declaration.Declaratio
|
||||
"filled_files":[%q],"resources":[{"id":"m.conf","type":"file","path":%q,%s}%s]}`, path, path, fields, more))
|
||||
}
|
||||
|
||||
func TestAWriteOfAPathNotFilledIsRefused(t *testing.T) {
|
||||
func testAWriteOfAPathNotFilledIsRefused(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
filled := filepath.Join(dir, "filled.conf")
|
||||
other := filepath.Join(dir, "other.conf")
|
||||
@@ -74,7 +74,7 @@ func TestAWriteOfAPathNotFilledIsRefused(t *testing.T) {
|
||||
|
||||
// Each ownership is written by the write verb exactly as an apply of the declared file with the same content: the
|
||||
// same action, the same bytes on disk, the same mode.
|
||||
func TestAFilledFileIsWrittenAsItsOwnershipSays(t *testing.T) {
|
||||
func testAFilledFileIsWrittenAsItsOwnershipSays(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
name, fields, content, before, action string
|
||||
}{
|
||||
@@ -166,7 +166,7 @@ func modeAt(t *testing.T, path string) os.FileMode {
|
||||
// A file that carried a secret keeps the mode a secret is written with: the client filled the value, and the file
|
||||
// is no more readable for it.
|
||||
|
||||
func TestAWriteUnderReloadOnReloadsItsProgramOnce(t *testing.T) {
|
||||
func testAWriteUnderReloadOnReloadsItsProgramOnce(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "daemon.conf")
|
||||
d := filledDecl(t, path, `"content":"","owner-at-runtime":"owned"`,
|
||||
`{"id":"m.daemon","type":"service","unit":"m.service","state":"running","reload-on":["m.conf"]},
|
||||
@@ -213,7 +213,7 @@ func TestAWriteUnderReloadOnReloadsItsProgramOnce(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAWriteUnderRestartOnRestartsItsProgram(t *testing.T) {
|
||||
func testAWriteUnderRestartOnRestartsItsProgram(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "daemon.conf")
|
||||
d := filledDecl(t, path, `"content":"","owner-at-runtime":"owned"`,
|
||||
`{"id":"m.daemon","type":"service","unit":"m.service","state":"running","restart-on":["m.conf"]}`)
|
||||
@@ -230,7 +230,7 @@ func TestAWriteUnderRestartOnRestartsItsProgram(t *testing.T) {
|
||||
}
|
||||
|
||||
// A running container that reads the file at creation is recreated, as an apply recreates it for a changed file.
|
||||
func TestAWriteOfAFileAContainerReadsRecreatesIt(t *testing.T) {
|
||||
func testAWriteOfAFileAContainerReadsRecreatesIt(t *testing.T) {
|
||||
env := filepath.Join(t.TempDir(), "forge.env")
|
||||
d := filledDecl(t, env, `"content":"","mode":"0600","owner-at-runtime":"owned"`,
|
||||
`{"id":"forge.server","type":"container","name":"forge","image":"`+pinned+`","env-file":["`+env+`"]}`)
|
||||
@@ -269,3 +269,12 @@ func count(lines []string, prefix string) int {
|
||||
|
||||
// Two resources declaring one filled path — two modules' blocks in one file — are refused: the request carries the
|
||||
// content only, so it cannot say whose block it is, and nothing is written.
|
||||
|
||||
// TestFilled runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestFilled(t *testing.T) {
|
||||
t.Run("AWriteOfAPathNotFilledIsRefused", testAWriteOfAPathNotFilledIsRefused)
|
||||
t.Run("AFilledFileIsWrittenAsItsOwnershipSays", testAFilledFileIsWrittenAsItsOwnershipSays)
|
||||
t.Run("AWriteUnderReloadOnReloadsItsProgramOnce", testAWriteUnderReloadOnReloadsItsProgramOnce)
|
||||
t.Run("AWriteUnderRestartOnRestartsItsProgram", testAWriteUnderRestartOnRestartsItsProgram)
|
||||
t.Run("AWriteOfAFileAContainerReadsRecreatesIt", testAWriteOfAFileAContainerReadsRecreatesIt)
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ import (
|
||||
)
|
||||
|
||||
// A directory used as found is never quiet, and a person at the machine can hand it over (novox/hq issue 339).
|
||||
func TestAFoundDirectoryIsSaidAndCanBeHandedOver(t *testing.T) {
|
||||
func testAFoundDirectoryIsSaidAndCanBeHandedOver(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
found := filepath.Join(dir, "found")
|
||||
if err := os.Mkdir(found, 0o700); err != nil {
|
||||
@@ -60,7 +60,7 @@ func TestAFoundDirectoryIsSaidAndCanBeHandedOver(t *testing.T) {
|
||||
|
||||
// The review's additions to the guard: the spool, /opt, the container runtimes' data wherever the runtime keeps
|
||||
// it, and an account's .ssh as an access or a mount, or as a directory anywhere but its own home.
|
||||
func TestTheRuntimesDataAndAnySSHAreRefused(t *testing.T) {
|
||||
func testTheRuntimesDataAndAnySSHAreRefused(t *testing.T) {
|
||||
cfg := filepath.Join(t.TempDir(), "daemon.json")
|
||||
if err := os.WriteFile(cfg, []byte(`{"data-root":"/storage/docker"}`), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -90,7 +90,7 @@ func TestTheRuntimesDataAndAnySSHAreRefused(t *testing.T) {
|
||||
|
||||
// When a directory was found is kept from the first apply that found it (novox/hq issue 339): the controller
|
||||
// tells a directory a send found from one found before it by that time, so it must not move with every apply.
|
||||
func TestWhenADirectoryWasFoundIsKept(t *testing.T) {
|
||||
func testWhenADirectoryWasFoundIsKept(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
found := filepath.Join(dir, "found")
|
||||
if err := os.Mkdir(found, 0o700); err != nil {
|
||||
@@ -118,7 +118,7 @@ func TestWhenADirectoryWasFoundIsKept(t *testing.T) {
|
||||
|
||||
// A hand-over is for the resource that was used as found there: another declaration that later points another
|
||||
// resource at the same path is not handed anything (novox/hq issue 339).
|
||||
func TestAHandOverIsForTheResourceThatAskedForIt(t *testing.T) {
|
||||
func testAHandOverIsForTheResourceThatAskedForIt(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
found := filepath.Join(dir, "found")
|
||||
if err := os.Mkdir(found, 0o700); err != nil {
|
||||
@@ -141,7 +141,7 @@ func TestAHandOverIsForTheResourceThatAskedForIt(t *testing.T) {
|
||||
// hand-over refused a link when it was recorded; between then and the apply its parent is swapped for a link to
|
||||
// a victim tree. The apply refuses, and the victim's directory keeps its mode — and so does a directory whose own
|
||||
// name became a link, and one whose grandparent did.
|
||||
func TestAHandedOverDirectoryIsChangedThroughNoLink(t *testing.T) {
|
||||
func testAHandedOverDirectoryIsChangedThroughNoLink(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
swap string
|
||||
applyOnce bool
|
||||
@@ -229,7 +229,7 @@ func TestAHandedOverDirectoryIsChangedThroughNoLink(t *testing.T) {
|
||||
|
||||
// The check at the moment of use, without the path's re-check: a component swapped for a link is refused by the
|
||||
// descriptor walk itself, whatever was resolved a moment before.
|
||||
func TestGiveHandedOverFollowsNoLink(t *testing.T) {
|
||||
func testGiveHandedOverFollowsNoLink(t *testing.T) {
|
||||
dir, err := filepath.EvalSymlinks(t.TempDir())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -255,3 +255,13 @@ func TestGiveHandedOverFollowsNoLink(t *testing.T) {
|
||||
t.Fatalf("the directory itself was not given its mode: %o", info.Mode().Perm())
|
||||
}
|
||||
}
|
||||
|
||||
// TestFoundIsSaid runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestFoundIsSaid(t *testing.T) {
|
||||
t.Run("AFoundDirectoryIsSaidAndCanBeHandedOver", testAFoundDirectoryIsSaidAndCanBeHandedOver)
|
||||
t.Run("TheRuntimesDataAndAnySSHAreRefused", testTheRuntimesDataAndAnySSHAreRefused)
|
||||
t.Run("WhenADirectoryWasFoundIsKept", testWhenADirectoryWasFoundIsKept)
|
||||
t.Run("AHandOverIsForTheResourceThatAskedForIt", testAHandOverIsForTheResourceThatAskedForIt)
|
||||
t.Run("AHandedOverDirectoryIsChangedThroughNoLink", testAHandedOverDirectoryIsChangedThroughNoLink)
|
||||
t.Run("GiveHandedOverFollowsNoLink", testGiveHandedOverFollowsNoLink)
|
||||
}
|
||||
|
||||
@@ -44,7 +44,7 @@ func applyOn(t *testing.T, raw string, known store.State, m *machine) (Report, s
|
||||
return Apply(context.Background(), archHost(t), parse(t, raw), known, store.OriginDeclared, m.run, nil, nil)
|
||||
}
|
||||
|
||||
func TestAUnitWhoseFileTheMeshWroteIsStoppedWhateverItsRecordSays(t *testing.T) {
|
||||
func testAUnitWhoseFileTheMeshWroteIsStoppedWhateverItsRecordSays(t *testing.T) {
|
||||
// The adoption guard's unit file is the mesh's own file resource, written where there was none.
|
||||
// Its service recorded before the host kept what it found has no Found, and forgetting it left
|
||||
// the guard's table loaded on a converged node and its unit file deleted from under it.
|
||||
@@ -110,7 +110,7 @@ func TestAUnitWhoseFileTheMeshWroteIsStoppedWhateverItsRecordSays(t *testing.T)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOnlyAUnitsOwnFileTheMeshCreatedMakesItTheMeshs(t *testing.T) {
|
||||
func testOnlyAUnitsOwnFileTheMeshCreatedMakesItTheMeshs(t *testing.T) {
|
||||
known := store.State{Resources: []store.Applied{
|
||||
{ID: "a", Type: "file", Target: "/etc/systemd/system/made.service"},
|
||||
{ID: "b", Type: "file", Target: "/run/systemd/system/runtime.service"},
|
||||
@@ -129,7 +129,7 @@ func TestOnlyAUnitsOwnFileTheMeshCreatedMakesItTheMeshs(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestWhatWasFoundOutlivesAFirstApplyThatFailed(t *testing.T) {
|
||||
func testWhatWasFoundOutlivesAFirstApplyThatFailed(t *testing.T) {
|
||||
// Enabled, then it would not start: no record. The next apply must not read the enable as
|
||||
// the machine's — or undeclaring leaves enabled a unit the mesh enabled.
|
||||
m := unitsMachine(map[string]*fakeUnit{"filter.service": {active: "inactive", enabled: "disabled", wontStart: true}})
|
||||
@@ -177,7 +177,7 @@ func TestWhatWasFoundOutlivesAFirstApplyThatFailed(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestBootIsFoundTheFirstTimeTheMeshSetsIt(t *testing.T) {
|
||||
func testBootIsFoundTheFirstTimeTheMeshSetsIt(t *testing.T) {
|
||||
// The declaration said nothing about boot at first, so the mesh never touched it: what is
|
||||
// there when a declaration first does is still the machine's.
|
||||
m := unitsMachine(map[string]*fakeUnit{"web.service": {active: "active", enabled: "disabled"}})
|
||||
@@ -204,7 +204,7 @@ func TestBootIsFoundTheFirstTimeTheMeshSetsIt(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAServiceOnceDeclaredWithNoStateIsFoundWhenFirstGivenOne(t *testing.T) {
|
||||
func testAServiceOnceDeclaredWithNoStateIsFoundWhenFirstGivenOne(t *testing.T) {
|
||||
// Declared with no state (novox/hq ADR 0117), the mesh never started or stopped it — so what
|
||||
// is there when a declaration first gives it one is what the machine had.
|
||||
m := unitsMachine(map[string]*fakeUnit{"net.service": {active: "inactive", enabled: "disabled"}})
|
||||
@@ -226,7 +226,7 @@ func TestAServiceOnceDeclaredWithNoStateIsFoundWhenFirstGivenOne(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAUnitWrittenInTheSameApplyIsLoadedBeforeItIsRead(t *testing.T) {
|
||||
func testAUnitWrittenInTheSameApplyIsLoadedBeforeItIsRead(t *testing.T) {
|
||||
// Read before the service manager is told about its new file, the unit is not there to find.
|
||||
dir := t.TempDir()
|
||||
m := unitsMachine(map[string]*fakeUnit{"fresh.service": {active: "inactive", enabled: "disabled"}})
|
||||
@@ -251,7 +251,7 @@ func TestAUnitWrittenInTheSameApplyIsLoadedBeforeItIsRead(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAServiceMovedToAnotherUnitGivesTheOldOneBackAndFindsTheNewOne(t *testing.T) {
|
||||
func testAServiceMovedToAnotherUnitGivesTheOldOneBackAndFindsTheNewOne(t *testing.T) {
|
||||
m := unitsMachine(map[string]*fakeUnit{
|
||||
"old.service": {active: "active", enabled: "enabled"},
|
||||
"new.service": {active: "inactive", enabled: "disabled"},
|
||||
@@ -278,7 +278,7 @@ func TestAServiceMovedToAnotherUnitGivesTheOldOneBackAndFindsTheNewOne(t *testin
|
||||
}
|
||||
}
|
||||
|
||||
func TestARemovalSaysWhatItDid(t *testing.T) {
|
||||
func testARemovalSaysWhatItDid(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
found *store.FoundUnit
|
||||
@@ -334,7 +334,7 @@ func TestARemovalSaysWhatItDid(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAUnitTheMeshStartedIsStoppedWhenUndeclaredAndOneFoundRunningIsNot(t *testing.T) {
|
||||
func testAUnitTheMeshStartedIsStoppedWhenUndeclaredAndOneFoundRunningIsNot(t *testing.T) {
|
||||
// End to end: found by the first apply, carried, given back.
|
||||
m := unitsMachine(map[string]*fakeUnit{
|
||||
"filter.service": {active: "inactive", enabled: "disabled"},
|
||||
@@ -361,7 +361,7 @@ func TestAUnitTheMeshStartedIsStoppedWhenUndeclaredAndOneFoundRunningIsNot(t *te
|
||||
}
|
||||
}
|
||||
|
||||
func TestAUnitHeldAndThenTakenIsFoundAsThePredecessorLeftIt(t *testing.T) {
|
||||
func testAUnitHeldAndThenTakenIsFoundAsThePredecessorLeftIt(t *testing.T) {
|
||||
// Held while its module was untaken, nothing was applied and nothing found; taken, the first
|
||||
// apply finds the predecessor's unit — stopped, but started at boot — before starting it.
|
||||
dir := t.TempDir()
|
||||
@@ -386,3 +386,17 @@ func TestAUnitHeldAndThenTakenIsFoundAsThePredecessorLeftIt(t *testing.T) {
|
||||
t.Errorf("given back as %s and %s; the predecessor left it stopped and enabled", u.active, u.enabled)
|
||||
}
|
||||
}
|
||||
|
||||
// TestFound runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestFound(t *testing.T) {
|
||||
t.Run("AUnitWhoseFileTheMeshWroteIsStoppedWhateverItsRecordSays", testAUnitWhoseFileTheMeshWroteIsStoppedWhateverItsRecordSays)
|
||||
t.Run("OnlyAUnitsOwnFileTheMeshCreatedMakesItTheMeshs", testOnlyAUnitsOwnFileTheMeshCreatedMakesItTheMeshs)
|
||||
t.Run("WhatWasFoundOutlivesAFirstApplyThatFailed", testWhatWasFoundOutlivesAFirstApplyThatFailed)
|
||||
t.Run("BootIsFoundTheFirstTimeTheMeshSetsIt", testBootIsFoundTheFirstTimeTheMeshSetsIt)
|
||||
t.Run("AServiceOnceDeclaredWithNoStateIsFoundWhenFirstGivenOne", testAServiceOnceDeclaredWithNoStateIsFoundWhenFirstGivenOne)
|
||||
t.Run("AUnitWrittenInTheSameApplyIsLoadedBeforeItIsRead", testAUnitWrittenInTheSameApplyIsLoadedBeforeItIsRead)
|
||||
t.Run("AServiceMovedToAnotherUnitGivesTheOldOneBackAndFindsTheNewOne", testAServiceMovedToAnotherUnitGivesTheOldOneBackAndFindsTheNewOne)
|
||||
t.Run("ARemovalSaysWhatItDid", testARemovalSaysWhatItDid)
|
||||
t.Run("AUnitTheMeshStartedIsStoppedWhenUndeclaredAndOneFoundRunningIsNot", testAUnitTheMeshStartedIsStoppedWhenUndeclaredAndOneFoundRunningIsNot)
|
||||
t.Run("AUnitHeldAndThenTakenIsFoundAsThePredecessorLeftIt", testAUnitHeldAndThenTakenIsFoundAsThePredecessorLeftIt)
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ import (
|
||||
// given back running and enabled when that declaration goes (the zfs module holds the distribution's
|
||||
// scrub timer stopped while its own timer scrubs the pool; unassigning it must not leave the pool with no
|
||||
// schedule at all). The report says so.
|
||||
func TestAUnitTheMeshStoppedAndDisabledIsGivenBackRunningAndEnabled(t *testing.T) {
|
||||
func testAUnitTheMeshStoppedAndDisabledIsGivenBackRunningAndEnabled(t *testing.T) {
|
||||
m := unitsMachine(map[string]*fakeUnit{
|
||||
"zfs-scrub-weekly@storage.timer": {active: "active", enabled: "enabled"},
|
||||
})
|
||||
@@ -44,7 +44,7 @@ func TestAUnitTheMeshStoppedAndDisabledIsGivenBackRunningAndEnabled(t *testing.T
|
||||
|
||||
// Only what the mesh's own declaration did is undone: a unit the mesh held stopped that was found stopped
|
||||
// stays stopped, and one found running that the mesh never stopped is left running as before.
|
||||
func TestOnlyWhatTheMeshsDeclarationStoppedIsStartedAgain(t *testing.T) {
|
||||
func testOnlyWhatTheMeshsDeclarationStoppedIsStartedAgain(t *testing.T) {
|
||||
m := unitsMachine(map[string]*fakeUnit{
|
||||
"found-stopped.timer": {active: "inactive", enabled: "disabled"},
|
||||
"left-running.timer": {active: "active", enabled: "enabled"},
|
||||
@@ -69,7 +69,7 @@ func TestOnlyWhatTheMeshsDeclarationStoppedIsStartedAgain(t *testing.T) {
|
||||
|
||||
// A record from before the host kept what it declared says nothing about who stopped the unit: it is
|
||||
// left as it is, never started.
|
||||
func TestARecordWithoutWhatWasDeclaredStartsNothing(t *testing.T) {
|
||||
func testARecordWithoutWhatWasDeclaredStartsNothing(t *testing.T) {
|
||||
m := unitsMachine(map[string]*fakeUnit{"old.timer": {active: "inactive", enabled: "disabled"}})
|
||||
state := store.State{}
|
||||
state.Record(store.Applied{ID: "old", Type: "service", Target: "old.timer", Origin: store.OriginDeclared,
|
||||
@@ -83,7 +83,7 @@ func TestARecordWithoutWhatWasDeclaredStartsNothing(t *testing.T) {
|
||||
}
|
||||
|
||||
// The plan says it before the apply does it.
|
||||
func TestThePlanSaysAStoppedUnitIsStartedAgain(t *testing.T) {
|
||||
func testThePlanSaysAStoppedUnitIsStartedAgain(t *testing.T) {
|
||||
m := unitsMachine(map[string]*fakeUnit{"zfs-scrub-weekly@storage.timer": {active: "active", enabled: "enabled"}})
|
||||
_, state, err := applyOn(t, `{"declaration":1,"resources":[
|
||||
{"id":"w","type":"service","unit":"zfs-scrub-weekly@storage.timer","state":"stopped","boot":"disabled"}]}`,
|
||||
@@ -105,7 +105,7 @@ func TestThePlanSaysAStoppedUnitIsStartedAgain(t *testing.T) {
|
||||
|
||||
// Third review: on removal a unit is started again only when it is exactly as the mesh held it, stopped and
|
||||
// disabled. A masked unit, or one somebody started or enabled since, is left alone, and the report says why.
|
||||
func TestAMaskedOrChangedUnitIsLeftAloneOnRemoval(t *testing.T) {
|
||||
func testAMaskedOrChangedUnitIsLeftAloneOnRemoval(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
name, active, enabled, says string
|
||||
}{
|
||||
@@ -141,7 +141,7 @@ func TestAMaskedOrChangedUnitIsLeftAloneOnRemoval(t *testing.T) {
|
||||
|
||||
// A restore that fails — the start refused, or the unit not running after it — waits: the record stays,
|
||||
// the report says so, and no apply is made fatal by it.
|
||||
func TestAFailedRestoreWaitsAndIsNeverFatal(t *testing.T) {
|
||||
func testAFailedRestoreWaitsAndIsNeverFatal(t *testing.T) {
|
||||
m := unitsMachine(map[string]*fakeUnit{"w.timer": {active: "active", enabled: "enabled"}})
|
||||
_, state, err := applyOn(t, `{"declaration":1,"resources":[
|
||||
{"id":"w","type":"service","unit":"w.timer","state":"stopped","boot":"disabled"}]}`, store.State{}, m)
|
||||
@@ -169,3 +169,13 @@ func TestAFailedRestoreWaitsAndIsNeverFatal(t *testing.T) {
|
||||
state = next
|
||||
}
|
||||
}
|
||||
|
||||
// TestGiveback runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestGiveback(t *testing.T) {
|
||||
t.Run("AUnitTheMeshStoppedAndDisabledIsGivenBackRunningAndEnabled", testAUnitTheMeshStoppedAndDisabledIsGivenBackRunningAndEnabled)
|
||||
t.Run("OnlyWhatTheMeshsDeclarationStoppedIsStartedAgain", testOnlyWhatTheMeshsDeclarationStoppedIsStartedAgain)
|
||||
t.Run("ARecordWithoutWhatWasDeclaredStartsNothing", testARecordWithoutWhatWasDeclaredStartsNothing)
|
||||
t.Run("ThePlanSaysAStoppedUnitIsStartedAgain", testThePlanSaysAStoppedUnitIsStartedAgain)
|
||||
t.Run("AMaskedOrChangedUnitIsLeftAloneOnRemoval", testAMaskedOrChangedUnitIsLeftAloneOnRemoval)
|
||||
t.Run("AFailedRestoreWaitsAndIsNeverFatal", testAFailedRestoreWaitsAndIsNeverFatal)
|
||||
}
|
||||
|
||||
@@ -91,7 +91,7 @@ const (
|
||||
shell = `{"id":"zsh.login","type":"user","name":"operator","groups":[]}`
|
||||
)
|
||||
|
||||
func TestAModulePutsTheAccountInAGroupAndSaysANewLoginIsNeeded(t *testing.T) {
|
||||
func testAModulePutsTheAccountInAGroupAndSaysANewLoginIsNeeded(t *testing.T) {
|
||||
g := newGroupDB([]string{"wheel", "plugdev"}, "openrazer")
|
||||
report, state, err := applyGroupsOf(t, g, store.State{}, shell, razer)
|
||||
if err != nil {
|
||||
@@ -126,7 +126,7 @@ func TestAModulePutsTheAccountInAGroupAndSaysANewLoginIsNeeded(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAGroupTheAccountWasAlreadyInIsNeverTakenBack(t *testing.T) {
|
||||
func testAGroupTheAccountWasAlreadyInIsNeverTakenBack(t *testing.T) {
|
||||
g := newGroupDB([]string{"wheel", "openrazer"})
|
||||
_, state, err := applyGroupsOf(t, g, store.State{}, razer)
|
||||
if err != nil {
|
||||
@@ -143,7 +143,7 @@ func TestAGroupTheAccountWasAlreadyInIsNeverTakenBack(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheGroupTheMeshAddedIsGivenBackWhenItsModuleGoes(t *testing.T) {
|
||||
func testTheGroupTheMeshAddedIsGivenBackWhenItsModuleGoes(t *testing.T) {
|
||||
g := newGroupDB([]string{"wheel"}, "openrazer")
|
||||
_, state, err := applyGroupsOf(t, g, store.State{}, razer)
|
||||
if err != nil {
|
||||
@@ -165,7 +165,7 @@ func TestTheGroupTheMeshAddedIsGivenBackWhenItsModuleGoes(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAGroupAnotherResourceStillAsksForStays(t *testing.T) {
|
||||
func testAGroupAnotherResourceStillAsksForStays(t *testing.T) {
|
||||
both := `{"id":"openrazer.account","type":"user","name":"operator","groups":["openrazer","video"]}`
|
||||
video := `{"id":"media.account","type":"user","name":"operator","groups":["video"]}`
|
||||
g := newGroupDB(nil, "openrazer", "video")
|
||||
@@ -185,7 +185,7 @@ func TestAGroupAnotherResourceStillAsksForStays(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAGroupNoLongerDeclaredIsGivenBackWhileTheAccountStaysDeclared(t *testing.T) {
|
||||
func testAGroupNoLongerDeclaredIsGivenBackWhileTheAccountStaysDeclared(t *testing.T) {
|
||||
g := newGroupDB(nil, "openrazer", "input")
|
||||
two := `{"id":"openrazer.account","type":"user","name":"operator","groups":["openrazer","input"]}`
|
||||
_, state, err := applyGroupsOf(t, g, store.State{}, two)
|
||||
@@ -204,7 +204,7 @@ func TestAGroupNoLongerDeclaredIsGivenBackWhileTheAccountStaysDeclared(t *testin
|
||||
}
|
||||
}
|
||||
|
||||
func TestAGroupThatDoesNotExistYetFailsTheResourceSayingSo(t *testing.T) {
|
||||
func testAGroupThatDoesNotExistYetFailsTheResourceSayingSo(t *testing.T) {
|
||||
g := newGroupDB([]string{"wheel"})
|
||||
_, _, err := applyGroupsOf(t, g, store.State{}, razer)
|
||||
if err == nil || !strings.Contains(err.Error(), "no such group yet") {
|
||||
@@ -217,7 +217,7 @@ func TestAGroupThatDoesNotExistYetFailsTheResourceSayingSo(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAGroupAPersonTookTheAccountOutOfSinceIsPutBackWhileDeclared(t *testing.T) {
|
||||
func testAGroupAPersonTookTheAccountOutOfSinceIsPutBackWhileDeclared(t *testing.T) {
|
||||
g := newGroupDB(nil, "openrazer")
|
||||
_, state, err := applyGroupsOf(t, g, store.State{}, razer)
|
||||
if err != nil {
|
||||
@@ -231,3 +231,14 @@ func TestAGroupAPersonTookTheAccountOutOfSinceIsPutBackWhileDeclared(t *testing.
|
||||
t.Errorf("a declared group was not put back: %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestGroups runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestGroups(t *testing.T) {
|
||||
t.Run("AModulePutsTheAccountInAGroupAndSaysANewLoginIsNeeded", testAModulePutsTheAccountInAGroupAndSaysANewLoginIsNeeded)
|
||||
t.Run("AGroupTheAccountWasAlreadyInIsNeverTakenBack", testAGroupTheAccountWasAlreadyInIsNeverTakenBack)
|
||||
t.Run("TheGroupTheMeshAddedIsGivenBackWhenItsModuleGoes", testTheGroupTheMeshAddedIsGivenBackWhenItsModuleGoes)
|
||||
t.Run("AGroupAnotherResourceStillAsksForStays", testAGroupAnotherResourceStillAsksForStays)
|
||||
t.Run("AGroupNoLongerDeclaredIsGivenBackWhileTheAccountStaysDeclared", testAGroupNoLongerDeclaredIsGivenBackWhileTheAccountStaysDeclared)
|
||||
t.Run("AGroupThatDoesNotExistYetFailsTheResourceSayingSo", testAGroupThatDoesNotExistYetFailsTheResourceSayingSo)
|
||||
t.Run("AGroupAPersonTookTheAccountOutOfSinceIsPutBackWhileDeclared", testAGroupAPersonTookTheAccountOutOfSinceIsPutBackWhileDeclared)
|
||||
}
|
||||
|
||||
@@ -100,7 +100,7 @@ func onAMachine(t *testing.T) {
|
||||
t.Cleanup(func() { unitDir, daemonRoot = wasUnits, wasBundles })
|
||||
}
|
||||
|
||||
func TestAContainerAProcessReplacesGoesOnlyOnceTheProcessRuns(t *testing.T) {
|
||||
func testAContainerAProcessReplacesGoesOnlyOnceTheProcessRuns(t *testing.T) {
|
||||
onAMachine(t)
|
||||
body, digest := anArchive(t, map[string]string{"mesh-controller": "#!/bin/sh\n"})
|
||||
known, raw := theController(t, digest, serving(t, body), `,"replaces":["mesh-controller.server"]`)
|
||||
@@ -135,7 +135,7 @@ func TestAContainerAProcessReplacesGoesOnlyOnceTheProcessRuns(t *testing.T) {
|
||||
|
||||
// The case the handover exists for: the replacement does not stay up. The container keeps
|
||||
// answering, stays recorded so a later apply hands it over, and the apply says why it failed.
|
||||
func TestAContainerIsKeptWhenItsReplacementDoesNotRun(t *testing.T) {
|
||||
func testAContainerIsKeptWhenItsReplacementDoesNotRun(t *testing.T) {
|
||||
onAMachine(t)
|
||||
body, digest := anArchive(t, map[string]string{"mesh-controller": "#!/bin/sh\n"})
|
||||
known, raw := theController(t, digest, serving(t, body), `,"replaces":["mesh-controller.server"]`)
|
||||
@@ -176,7 +176,7 @@ func TestAContainerIsKeptWhenItsReplacementDoesNotRun(t *testing.T) {
|
||||
|
||||
// A replacement that never applied — its bundle is not what was declared — touches nothing, and
|
||||
// what it replaces keeps running.
|
||||
func TestAContainerIsKeptWhenItsReplacementFailsToApply(t *testing.T) {
|
||||
func testAContainerIsKeptWhenItsReplacementFailsToApply(t *testing.T) {
|
||||
onAMachine(t)
|
||||
body, _ := anArchive(t, map[string]string{"mesh-controller": "#!/bin/sh\n"})
|
||||
known, raw := theController(t, "sha256:"+strings.Repeat("b", 64), serving(t, body),
|
||||
@@ -201,7 +201,7 @@ func TestAContainerIsKeptWhenItsReplacementFailsToApply(t *testing.T) {
|
||||
|
||||
// Without `replaces` nothing changes: an orphan goes before anything is applied, as it always has.
|
||||
// Kept as a test because it is the window the field exists to close.
|
||||
func TestWithoutReplacesAnOrphanStillGoesFirst(t *testing.T) {
|
||||
func testWithoutReplacesAnOrphanStillGoesFirst(t *testing.T) {
|
||||
onAMachine(t)
|
||||
body, digest := anArchive(t, map[string]string{"mesh-controller": "#!/bin/sh\n"})
|
||||
known, raw := theController(t, digest, serving(t, body), ``)
|
||||
@@ -218,7 +218,7 @@ func TestWithoutReplacesAnOrphanStillGoesFirst(t *testing.T) {
|
||||
// novox/hq issue 213, beyond what the oneshot unit (process_step_test.go) already holds: a step
|
||||
// written `./name` runs its own bundle's binary — the controller's preparation is its own binary —
|
||||
// and a step is started, never enabled.
|
||||
func TestAStepRunsItsOwnBundlesBinaryAndIsNotEnabled(t *testing.T) {
|
||||
func testAStepRunsItsOwnBundlesBinaryAndIsNotEnabled(t *testing.T) {
|
||||
onAMachine(t)
|
||||
body, digest := anArchive(t, map[string]string{"mesh-controller": "#!/bin/sh\n"})
|
||||
m := &aMachine{running: true}
|
||||
@@ -242,7 +242,7 @@ func TestAStepRunsItsOwnBundlesBinaryAndIsNotEnabled(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAStepThatFailsGatesItsModule(t *testing.T) {
|
||||
func testAStepThatFailsGatesItsModule(t *testing.T) {
|
||||
onAMachine(t)
|
||||
body, digest := anArchive(t, map[string]string{"mesh-controller": "#!/bin/sh\n"})
|
||||
src := serving(t, body)
|
||||
@@ -272,7 +272,7 @@ func TestAStepThatFailsGatesItsModule(t *testing.T) {
|
||||
// A completed step is done: applied again unchanged, it is not run again — its service is never up
|
||||
// between runs, and reading that as "a daemon that stopped" re-ran the controller's preparation on
|
||||
// every apply. Nor is a scheduled run started off its cadence; its timer is what is kept up.
|
||||
func TestACompletedStepIsNotRunAgainAndAScheduleIsItsTimer(t *testing.T) {
|
||||
func testACompletedStepIsNotRunAgainAndAScheduleIsItsTimer(t *testing.T) {
|
||||
onAMachine(t)
|
||||
body, digest := anArchive(t, map[string]string{"job": "#!/bin/sh\n"})
|
||||
src := serving(t, body)
|
||||
@@ -302,7 +302,7 @@ func TestACompletedStepIsNotRunAgainAndAScheduleIsItsTimer(t *testing.T) {
|
||||
// A replacement crash-looping between its restarts is not up, though the service manager calls it
|
||||
// "activating" — the state the host's ordinary second look accepts as running. Removing the
|
||||
// container on that reading would leave nothing answering.
|
||||
func TestAContainerIsKeptWhenItsReplacementIsCrashLooping(t *testing.T) {
|
||||
func testAContainerIsKeptWhenItsReplacementIsCrashLooping(t *testing.T) {
|
||||
onAMachine(t)
|
||||
body, digest := anArchive(t, map[string]string{"mesh-controller": "#!/bin/sh\n"})
|
||||
known, raw := theController(t, digest, serving(t, body), `,"replaces":["mesh-controller.server"]`)
|
||||
@@ -319,3 +319,15 @@ func TestAContainerIsKeptWhenItsReplacementIsCrashLooping(t *testing.T) {
|
||||
t.Fatal("the container was forgotten")
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandover runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestHandover(t *testing.T) {
|
||||
t.Run("AContainerAProcessReplacesGoesOnlyOnceTheProcessRuns", testAContainerAProcessReplacesGoesOnlyOnceTheProcessRuns)
|
||||
t.Run("AContainerIsKeptWhenItsReplacementDoesNotRun", testAContainerIsKeptWhenItsReplacementDoesNotRun)
|
||||
t.Run("AContainerIsKeptWhenItsReplacementFailsToApply", testAContainerIsKeptWhenItsReplacementFailsToApply)
|
||||
t.Run("WithoutReplacesAnOrphanStillGoesFirst", testWithoutReplacesAnOrphanStillGoesFirst)
|
||||
t.Run("AStepRunsItsOwnBundlesBinaryAndIsNotEnabled", testAStepRunsItsOwnBundlesBinaryAndIsNotEnabled)
|
||||
t.Run("AStepThatFailsGatesItsModule", testAStepThatFailsGatesItsModule)
|
||||
t.Run("ACompletedStepIsNotRunAgainAndAScheduleIsItsTimer", testACompletedStepIsNotRunAgainAndAScheduleIsItsTimer)
|
||||
t.Run("AContainerIsKeptWhenItsReplacementIsCrashLooping", testAContainerIsKeptWhenItsReplacementIsCrashLooping)
|
||||
}
|
||||
|
||||
@@ -72,7 +72,7 @@ func modeOfPath(t *testing.T, p string) os.FileMode {
|
||||
return info.Mode().Perm()
|
||||
}
|
||||
|
||||
func TestADirectoryUnderAHomeThatIsALinkIsRefusedAndItsTargetUntouched(t *testing.T) {
|
||||
func testADirectoryUnderAHomeThatIsALinkIsRefusedAndItsTargetUntouched(t *testing.T) {
|
||||
home, outside := aLinkedHome(t)
|
||||
link(t, outside, filepath.Join(home, ".claude"))
|
||||
err := applyOneResource(t, `{"id":"claude-code.agent-home","type":"directory","path":"`+
|
||||
@@ -83,7 +83,7 @@ func TestADirectoryUnderAHomeThatIsALinkIsRefusedAndItsTargetUntouched(t *testin
|
||||
}
|
||||
}
|
||||
|
||||
func TestAFileThroughALinkedParentUnderAHomeIsRefused(t *testing.T) {
|
||||
func testAFileThroughALinkedParentUnderAHomeIsRefused(t *testing.T) {
|
||||
home, outside := aLinkedHome(t)
|
||||
link(t, outside, filepath.Join(home, ".claude"))
|
||||
err := applyOneResource(t, `{"id":"m.f","type":"file","path":"`+filepath.Join(home, ".claude", "shadow")+
|
||||
@@ -97,7 +97,7 @@ func TestAFileThroughALinkedParentUnderAHomeIsRefused(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAFileThatIsItselfALinkUnderAHomeIsRefused(t *testing.T) {
|
||||
func testAFileThatIsItselfALinkUnderAHomeIsRefused(t *testing.T) {
|
||||
home, outside := aLinkedHome(t)
|
||||
link(t, filepath.Join(outside, "shadow"), filepath.Join(home, ".zshrc"))
|
||||
err := applyOneResource(t, `{"id":"m.f","type":"file","path":"`+filepath.Join(home, ".zshrc")+
|
||||
@@ -108,7 +108,7 @@ func TestAFileThatIsItselfALinkUnderAHomeIsRefused(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestADirectoryAndAFileUnderAHomeAreMadeAsBefore(t *testing.T) {
|
||||
func testADirectoryAndAFileUnderAHomeAreMadeAsBefore(t *testing.T) {
|
||||
home, _ := aLinkedHome(t)
|
||||
dir := filepath.Join(home, ".claude")
|
||||
if err := applyOneResource(t, `{"id":"m.d","type":"directory","path":"`+dir+`","mode":"0700"}`); err != nil {
|
||||
@@ -127,7 +127,7 @@ func TestADirectoryAndAFileUnderAHomeAreMadeAsBefore(t *testing.T) {
|
||||
}
|
||||
|
||||
// The descriptor half: a link put in place after any check is still not followed.
|
||||
func TestTheDescriptorCallsFollowNoLinkBelowAHome(t *testing.T) {
|
||||
func testTheDescriptorCallsFollowNoLinkBelowAHome(t *testing.T) {
|
||||
home, outside := aLinkedHome(t)
|
||||
link(t, outside, filepath.Join(home, ".claude"))
|
||||
mustBeLinkRefusal(t, chmodPath(filepath.Join(home, ".claude"), 0o777))
|
||||
@@ -155,7 +155,7 @@ func TestTheDescriptorCallsFollowNoLinkBelowAHome(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemovalThroughALinkUnderAHomeIsRefused(t *testing.T) {
|
||||
func testRemovalThroughALinkUnderAHomeIsRefused(t *testing.T) {
|
||||
home, outside := aLinkedHome(t)
|
||||
link(t, outside, filepath.Join(home, ".claude"))
|
||||
_, _, err := remove(context.Background(), archHost(t), store.Applied{ID: "m.f", Type: "file",
|
||||
@@ -166,7 +166,7 @@ func TestRemovalThroughALinkUnderAHomeIsRefused(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAPathOutsideEveryHomeIsHandledAsBefore(t *testing.T) {
|
||||
func testAPathOutsideEveryHomeIsHandledAsBefore(t *testing.T) {
|
||||
_, outside := aLinkedHome(t)
|
||||
elsewhere := filepath.Join(filepath.Dir(outside), "srv")
|
||||
if err := os.MkdirAll(elsewhere, 0o755); err != nil {
|
||||
@@ -181,7 +181,7 @@ func TestAPathOutsideEveryHomeIsHandledAsBefore(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestHomesAreAPersonsOrAnAgentsNotAServicesOrRoots(t *testing.T) {
|
||||
func testHomesAreAPersonsOrAnAgentsNotAServicesOrRoots(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
passwd := filepath.Join(dir, "passwd")
|
||||
if err := os.WriteFile(passwd, []byte("root:x:0:0::/root:/bin/bash\n"+
|
||||
@@ -207,7 +207,7 @@ func TestHomesAreAPersonsOrAnAgentsNotAServicesOrRoots(t *testing.T) {
|
||||
|
||||
// A hard link below a home to a file the home's account does not own is never owned, chmodded or read by
|
||||
// name: fstat on the opened descriptor counts its links first (the re-review of 2026-10-08).
|
||||
func TestAHardLinkedFileBelowAHomeIsRefused(t *testing.T) {
|
||||
func testAHardLinkedFileBelowAHomeIsRefused(t *testing.T) {
|
||||
home, outside := aLinkedHome(t)
|
||||
shadow := filepath.Join(outside, "shadow")
|
||||
linked := filepath.Join(home, ".claude")
|
||||
@@ -233,7 +233,7 @@ func TestAHardLinkedFileBelowAHomeIsRefused(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestADirectoryWhereAFileWasExpectedAndAFifoAreRefused(t *testing.T) {
|
||||
func testADirectoryWhereAFileWasExpectedAndAFifoAreRefused(t *testing.T) {
|
||||
home, _ := aLinkedHome(t)
|
||||
dir := filepath.Join(home, "d")
|
||||
if err := os.Mkdir(dir, 0o755); err != nil {
|
||||
@@ -253,3 +253,17 @@ func TestADirectoryWhereAFileWasExpectedAndAFifoAreRefused(t *testing.T) {
|
||||
t.Fatalf("a directory as a directory passes: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHomeLinks runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestHomeLinks(t *testing.T) {
|
||||
t.Run("ADirectoryUnderAHomeThatIsALinkIsRefusedAndItsTargetUntouched", testADirectoryUnderAHomeThatIsALinkIsRefusedAndItsTargetUntouched)
|
||||
t.Run("AFileThroughALinkedParentUnderAHomeIsRefused", testAFileThroughALinkedParentUnderAHomeIsRefused)
|
||||
t.Run("AFileThatIsItselfALinkUnderAHomeIsRefused", testAFileThatIsItselfALinkUnderAHomeIsRefused)
|
||||
t.Run("ADirectoryAndAFileUnderAHomeAreMadeAsBefore", testADirectoryAndAFileUnderAHomeAreMadeAsBefore)
|
||||
t.Run("TheDescriptorCallsFollowNoLinkBelowAHome", testTheDescriptorCallsFollowNoLinkBelowAHome)
|
||||
t.Run("RemovalThroughALinkUnderAHomeIsRefused", testRemovalThroughALinkUnderAHomeIsRefused)
|
||||
t.Run("APathOutsideEveryHomeIsHandledAsBefore", testAPathOutsideEveryHomeIsHandledAsBefore)
|
||||
t.Run("HomesAreAPersonsOrAnAgentsNotAServicesOrRoots", testHomesAreAPersonsOrAnAgentsNotAServicesOrRoots)
|
||||
t.Run("AHardLinkedFileBelowAHomeIsRefused", testAHardLinkedFileBelowAHomeIsRefused)
|
||||
t.Run("ADirectoryWhereAFileWasExpectedAndAFifoAreRefused", testADirectoryWhereAFileWasExpectedAndAFifoAreRefused)
|
||||
}
|
||||
|
||||
@@ -50,7 +50,7 @@ func givenPaths(given map[string]string) []string {
|
||||
return paths
|
||||
}
|
||||
|
||||
func TestAFileUnderAHomeGivesTheParentsItMadeToItsOwner(t *testing.T) {
|
||||
func testAFileUnderAHomeGivesTheParentsItMadeToItsOwner(t *testing.T) {
|
||||
home, owner, given := aHome(t)
|
||||
target := filepath.Join(home, ".config", "mesh", "environment.sh")
|
||||
d := parse(t, `{"declaration":1,"resources":[{"id":"shell.env","type":"file","path":"`+target+
|
||||
@@ -70,7 +70,7 @@ func TestAFileUnderAHomeGivesTheParentsItMadeToItsOwner(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnArchiveUnderAHomeGivesTheParentsItMadeToItsOwner(t *testing.T) {
|
||||
func testAnArchiveUnderAHomeGivesTheParentsItMadeToItsOwner(t *testing.T) {
|
||||
home, owner, given := aHome(t)
|
||||
body, digest := anArchive(t, map[string]string{"p10k.zsh": "theme"})
|
||||
target := filepath.Join(home, ".local", "share", "powerlevel10k")
|
||||
@@ -87,7 +87,7 @@ func TestAnArchiveUnderAHomeGivesTheParentsItMadeToItsOwner(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAParentThatWasThereIsHeldAsFound(t *testing.T) {
|
||||
func testAParentThatWasThereIsHeldAsFound(t *testing.T) {
|
||||
home, owner, given := aHome(t)
|
||||
config := filepath.Join(home, ".config")
|
||||
if err := os.Mkdir(config, 0o700); err != nil {
|
||||
@@ -111,7 +111,7 @@ func TestAParentThatWasThereIsHeldAsFound(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAParentOutsideTheHomeIsMadeAsBefore(t *testing.T) {
|
||||
func testAParentOutsideTheHomeIsMadeAsBefore(t *testing.T) {
|
||||
_, owner, given := aHome(t)
|
||||
target := filepath.Join(t.TempDir(), "var", "lib", "module", "settings.conf")
|
||||
d := parse(t, `{"declaration":1,"resources":[{"id":"module.conf","type":"file","path":"`+target+
|
||||
@@ -124,3 +124,11 @@ func TestAParentOutsideTheHomeIsMadeAsBefore(t *testing.T) {
|
||||
t.Errorf("parents outside the owner's home were given to it: %v", givenPaths(given))
|
||||
}
|
||||
}
|
||||
|
||||
// TestHomeParents runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestHomeParents(t *testing.T) {
|
||||
t.Run("AFileUnderAHomeGivesTheParentsItMadeToItsOwner", testAFileUnderAHomeGivesTheParentsItMadeToItsOwner)
|
||||
t.Run("AnArchiveUnderAHomeGivesTheParentsItMadeToItsOwner", testAnArchiveUnderAHomeGivesTheParentsItMadeToItsOwner)
|
||||
t.Run("AParentThatWasThereIsHeldAsFound", testAParentThatWasThereIsHeldAsFound)
|
||||
t.Run("AParentOutsideTheHomeIsMadeAsBefore", testAParentOutsideTheHomeIsMadeAsBefore)
|
||||
}
|
||||
|
||||
@@ -155,7 +155,7 @@ func withIdentities(t *testing.T, identities, resources string) *declaration.Dec
|
||||
|
||||
// Row 3: the account made as a system account with exactly its numbers, recorded, and removed — only what was
|
||||
// made — when no longer declared.
|
||||
func TestAModulesIdentityIsMadeWithItsNumbersAndRemovedWhenUndeclared(t *testing.T) {
|
||||
func testAModulesIdentityIsMadeWithItsNumbersAndRemovedWhenUndeclared(t *testing.T) {
|
||||
m := &accountsMachine{users: map[string][2]int{}, groups: map[string][2]int{}}
|
||||
dir := t.TempDir()
|
||||
d := withIdentities(t, `{"module":"radarr","name":"mesh-radarr","uid":61001,"gid":61001}`,
|
||||
@@ -207,7 +207,7 @@ func TestAModulesIdentityIsMadeWithItsNumbersAndRemovedWhenUndeclared(t *testing
|
||||
|
||||
// Row 3: a name that exists with other numbers, or numbers another name holds, is refused naming whose, and the
|
||||
// module is not attempted; the rest of the machine is.
|
||||
func TestAnIdentityWhoseNameOrNumbersAreAnothersIsRefused(t *testing.T) {
|
||||
func testAnIdentityWhoseNameOrNumbersAreAnothersIsRefused(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
for _, tc := range []struct {
|
||||
users, groups map[string][2]int
|
||||
@@ -240,7 +240,7 @@ func TestAnIdentityWhoseNameOrNumbersAreAnothersIsRefused(t *testing.T) {
|
||||
|
||||
// Row 11: a declaration naming a root group for an account or an image is refused with its reason, and nothing is
|
||||
// made or started. A number 0 is refused on arrival, by the parser.
|
||||
func TestNoModuleIdentityIsRoot(t *testing.T) {
|
||||
func testNoModuleIdentityIsRoot(t *testing.T) {
|
||||
was := RootGroupIDs
|
||||
RootGroupIDs = func() map[int]string { return map[int]string{10: "wheel"} }
|
||||
defer func() { RootGroupIDs = was }()
|
||||
@@ -279,7 +279,7 @@ func TestNoModuleIdentityIsRoot(t *testing.T) {
|
||||
|
||||
// Row 3: a container declaring identity is told it — by the variables its image reads, or the runtime's user
|
||||
// option — and a changed identity is a container recreated.
|
||||
func TestAContainerIsToldItsModulesIdentity(t *testing.T) {
|
||||
func testAContainerIsToldItsModulesIdentity(t *testing.T) {
|
||||
env := &declaration.Container{ID: "radarr.app", Name: "radarr", Image: pinned, RunAs: &declaration.ContainerIdentity{
|
||||
Mode: declaration.IdentityByEnv, UserEnv: "PUID", GroupEnv: "PGID", UID: 61001, GID: 61001}}
|
||||
run := &declaration.Container{ID: "plex.app", Name: "plex", Image: pinned, RunAs: &declaration.ContainerIdentity{
|
||||
@@ -303,7 +303,7 @@ func TestAContainerIsToldItsModulesIdentity(t *testing.T) {
|
||||
|
||||
// ADR 0325 §5 supersedes ADR 0312's group grant: what a grant put an account in is taken back on the first apply of
|
||||
// the access, and nothing is granted again.
|
||||
func TestWhatAGroupGrantPutAnAccountInIsTakenBack(t *testing.T) {
|
||||
func testWhatAGroupGrantPutAnAccountInIsTakenBack(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
groups := "nox media"
|
||||
var ran []string
|
||||
@@ -336,7 +336,7 @@ func TestWhatAGroupGrantPutAnAccountInIsTakenBack(t *testing.T) {
|
||||
}
|
||||
|
||||
// Review L7: a group the grant put an account in that could not be left stays recorded, and is tried again.
|
||||
func TestAGrantsGroupThatCouldNotBeLeftIsTriedAgain(t *testing.T) {
|
||||
func testAGrantsGroupThatCouldNotBeLeftIsTriedAgain(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
refuse := true
|
||||
groups := "nox media"
|
||||
@@ -372,7 +372,7 @@ func TestAGrantsGroupThatCouldNotBeLeftIsTriedAgain(t *testing.T) {
|
||||
}
|
||||
|
||||
// Every system the engine runs on that makes accounts makes module identities: arch and alpine alike.
|
||||
func TestArchAndAlpineMakeModuleIdentities(t *testing.T) {
|
||||
func testArchAndAlpineMakeModuleIdentities(t *testing.T) {
|
||||
for _, name := range []string{"arch", "alpine"} {
|
||||
sys, err := system.For(name)
|
||||
if err != nil {
|
||||
@@ -383,3 +383,14 @@ func TestArchAndAlpineMakeModuleIdentities(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestIdentities runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestIdentities(t *testing.T) {
|
||||
t.Run("AModulesIdentityIsMadeWithItsNumbersAndRemovedWhenUndeclared", testAModulesIdentityIsMadeWithItsNumbersAndRemovedWhenUndeclared)
|
||||
t.Run("AnIdentityWhoseNameOrNumbersAreAnothersIsRefused", testAnIdentityWhoseNameOrNumbersAreAnothersIsRefused)
|
||||
t.Run("NoModuleIdentityIsRoot", testNoModuleIdentityIsRoot)
|
||||
t.Run("AContainerIsToldItsModulesIdentity", testAContainerIsToldItsModulesIdentity)
|
||||
t.Run("WhatAGroupGrantPutAnAccountInIsTakenBack", testWhatAGroupGrantPutAnAccountInIsTakenBack)
|
||||
t.Run("AGrantsGroupThatCouldNotBeLeftIsTriedAgain", testAGrantsGroupThatCouldNotBeLeftIsTriedAgain)
|
||||
t.Run("ArchAndAlpineMakeModuleIdentities", testArchAndAlpineMakeModuleIdentities)
|
||||
}
|
||||
|
||||
@@ -39,7 +39,7 @@ func dockerLikeByKind(containers map[string]bool) func(context.Context, string,
|
||||
}
|
||||
}
|
||||
|
||||
func TestContainerStateAsksTheContainerNamespaceNotTheBareForm(t *testing.T) {
|
||||
func testContainerStateAsksTheContainerNamespaceNotTheBareForm(t *testing.T) {
|
||||
// "minio" exists only as a network in this scenario — never in `containers` — matching the
|
||||
// live failure this guards: a module's network and its container share a name, and the
|
||||
// container does not exist yet.
|
||||
@@ -55,7 +55,7 @@ func TestContainerStateAsksTheContainerNamespaceNotTheBareForm(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestInspectFoundAsksTheContainerNamespaceNotTheBareForm(t *testing.T) {
|
||||
func testInspectFoundAsksTheContainerNamespaceNotTheBareForm(t *testing.T) {
|
||||
run := dockerLikeByKind(map[string]bool{"keycloak": true})
|
||||
|
||||
if _, exists, err := inspectFound(context.Background(), "minio", run); err != nil || exists {
|
||||
@@ -65,3 +65,9 @@ func TestInspectFoundAsksTheContainerNamespaceNotTheBareForm(t *testing.T) {
|
||||
t.Fatalf("a container that does exist should be found: exists=%v err=%v", exists, err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestInspectScope runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestInspectScope(t *testing.T) {
|
||||
t.Run("ContainerStateAsksTheContainerNamespaceNotTheBareForm", testContainerStateAsksTheContainerNamespaceNotTheBareForm)
|
||||
t.Run("InspectFoundAsksTheContainerNamespaceNotTheBareForm", testInspectFoundAsksTheContainerNamespaceNotTheBareForm)
|
||||
}
|
||||
|
||||
@@ -39,7 +39,7 @@ func runtimeDecl(t *testing.T, path string, network bool) *declaration.Declarati
|
||||
return parse(t, `{"declaration":1,"resources":[`+strings.Join(resources, ",")+`]}`)
|
||||
}
|
||||
|
||||
func TestTheRegistryMovesToTheRuntimesModuleWithoutLeavingTheList(t *testing.T) {
|
||||
func testTheRegistryMovesToTheRuntimesModuleWithoutLeavingTheList(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "daemon.json")
|
||||
if err := os.WriteFile(path, []byte(`{"insecure-registries":["192.0.2.7:5000"]}`), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -115,7 +115,7 @@ func TestTheRegistryMovesToTheRuntimesModuleWithoutLeavingTheList(t *testing.T)
|
||||
// A unit two records name, under opposite conditions, passes between them (design 42 zfs-owns-zfs §2, answer A-21): the
|
||||
// going record is forgotten, the preview says so before it happens, and what it found of the unit before the mesh is what
|
||||
// the staying record gives back when its module leaves, not what the mesh made of it.
|
||||
func TestARecordOfAUnitStillHeldIsForgottenAndPassesWhatItFound(t *testing.T) {
|
||||
func testARecordOfAUnitStillHeldIsForgottenAndPassesWhatItFound(t *testing.T) {
|
||||
t.Run("the preview forgets it", func(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "daemon.json")
|
||||
var commands []string
|
||||
@@ -186,3 +186,9 @@ func TestARecordOfAUnitStillHeldIsForgottenAndPassesWhatItFound(t *testing.T) {
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestIntoHandover runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestIntoHandover(t *testing.T) {
|
||||
t.Run("TheRegistryMovesToTheRuntimesModuleWithoutLeavingTheList", testTheRegistryMovesToTheRuntimesModuleWithoutLeavingTheList)
|
||||
t.Run("ARecordOfAUnitStillHeldIsForgottenAndPassesWhatItFound", testARecordOfAUnitStillHeldIsForgottenAndPassesWhatItFound)
|
||||
}
|
||||
|
||||
+24
-10
@@ -39,7 +39,7 @@ func readObject(t *testing.T, path string) map[string]any {
|
||||
// The machine's own runtime settings, the way a predecessor leaves them.
|
||||
const machinesOwn = `{"data-root":"/srv/docker","log-opts":{"max-size":"10m"},"insecure-registries":["192.0.2.7:5000"]}`
|
||||
|
||||
func TestWritingIntoKeepsEveryKeyTheMachineHad(t *testing.T) {
|
||||
func testWritingIntoKeepsEveryKeyTheMachineHad(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "daemon.json")
|
||||
if err := os.WriteFile(path, []byte(machinesOwn), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -90,7 +90,7 @@ func TestWritingIntoKeepsEveryKeyTheMachineHad(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAFileWrittenIntoThatWasNotThereIsRemovedWhenOnlyTheMeshsKeysAreLeft(t *testing.T) {
|
||||
func testAFileWrittenIntoThatWasNotThereIsRemovedWhenOnlyTheMeshsKeysAreLeft(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "daemon.json")
|
||||
d := parse(t, intoDecl(t, path, `{"insecure-registries":["10.42.0.1:5000"]}`))
|
||||
report, state, err := Apply(context.Background(), archHost(t), d, store.State{}, store.OriginDeclared, nil, nil, nil)
|
||||
@@ -130,7 +130,7 @@ func TestAFileWrittenIntoThatWasNotThereIsRemovedWhenOnlyTheMeshsKeysAreLeft(t *
|
||||
}
|
||||
}
|
||||
|
||||
func TestAKeyNoLongerDeclaredGoesBackAndANewOneIsRemembered(t *testing.T) {
|
||||
func testAKeyNoLongerDeclaredGoesBackAndANewOneIsRemembered(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "daemon.json")
|
||||
_ = os.WriteFile(path, []byte(machinesOwn), 0o644)
|
||||
first := parse(t, intoDecl(t, path, `{"insecure-registries":["10.42.0.1:5000"]}`))
|
||||
@@ -151,7 +151,7 @@ func TestAKeyNoLongerDeclaredGoesBackAndANewOneIsRemembered(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAFileThatIsNotAnObjectIsRefusedAndLeftAlone(t *testing.T) {
|
||||
func testAFileThatIsNotAnObjectIsRefusedAndLeftAlone(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "daemon.json")
|
||||
_ = os.WriteFile(path, []byte("# not json at all\n"), 0o644)
|
||||
d := parse(t, intoDecl(t, path, `{"insecure-registries":["10.42.0.1:5000"]}`))
|
||||
@@ -164,7 +164,7 @@ func TestAFileThatIsNotAnObjectIsRefusedAndLeftAlone(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAFileWrittenIntoIsNeverHeldOnAnAdoptedNode(t *testing.T) {
|
||||
func testAFileWrittenIntoIsNeverHeldOnAnAdoptedNode(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "daemon.json")
|
||||
_ = os.WriteFile(path, []byte(machinesOwn), 0o644)
|
||||
d := adopted(t, `{"taken":[],"untaken":{"networking":["networking.registry-trust"]}}`,
|
||||
@@ -184,7 +184,7 @@ func TestAFileWrittenIntoIsNeverHeldOnAnAdoptedNode(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAServiceIsReloadedNotRestartedForWhatItReloadsOn(t *testing.T) {
|
||||
func testAServiceIsReloadedNotRestartedForWhatItReloadsOn(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "daemon.json")
|
||||
d := parse(t, fmt.Sprintf(`{"declaration":1,"resources":[
|
||||
{"id":"trust","type":"file","path":%q,"into":"json","content":%q},
|
||||
@@ -212,7 +212,7 @@ func somethingElse(t *testing.T) *declaration.Declaration {
|
||||
]}`, filepath.Join(t.TempDir(), "other")))
|
||||
}
|
||||
|
||||
func TestAListIsAddedToNeverReplaced(t *testing.T) {
|
||||
func testAListIsAddedToNeverReplaced(t *testing.T) {
|
||||
// The predecessor's own trusted registries are kept; the mesh adds its own and, undeclared,
|
||||
// takes back only what it added (novox/hq ADR 0102).
|
||||
path := filepath.Join(t.TempDir(), "daemon.json")
|
||||
@@ -272,7 +272,7 @@ func TestAListIsAddedToNeverReplaced(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAListTheMeshCreatedGoesWhenEmptied(t *testing.T) {
|
||||
func testAListTheMeshCreatedGoesWhenEmptied(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "daemon.json")
|
||||
_ = os.WriteFile(path, []byte(`{"data-root":"/srv/docker"}`), 0o644)
|
||||
d := parse(t, intoDecl(t, path, `{"insecure-registries":["10.42.0.1:5000"]}`))
|
||||
@@ -288,7 +288,7 @@ func TestAListTheMeshCreatedGoesWhenEmptied(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAHoldFromAWholeFileDoesNotKeepOutAnIntoWrite(t *testing.T) {
|
||||
func testAHoldFromAWholeFileDoesNotKeepOutAnIntoWrite(t *testing.T) {
|
||||
// Declared whole before, the runtime's file was held; declared into now, it is written into.
|
||||
path := filepath.Join(t.TempDir(), "daemon.json")
|
||||
_ = os.WriteFile(path, []byte(machinesOwn), 0o644)
|
||||
@@ -309,7 +309,7 @@ func TestAHoldFromAWholeFileDoesNotKeepOutAnIntoWrite(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAWriteWithNoRecordOfItIsTheMeshsOwn(t *testing.T) {
|
||||
func testAWriteWithNoRecordOfItIsTheMeshsOwn(t *testing.T) {
|
||||
// A host that wrote into the file and died before saving its state comes back with no record
|
||||
// of it. What is there is then exactly what the mesh declares — and remembered as the
|
||||
// machine's it would never be given back (novox/hq ADR 0102).
|
||||
@@ -340,3 +340,17 @@ func TestAWriteWithNoRecordOfItIsTheMeshsOwn(t *testing.T) {
|
||||
t.Errorf("the machine did not get its file back: %v", o)
|
||||
}
|
||||
}
|
||||
|
||||
// TestInto runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestInto(t *testing.T) {
|
||||
t.Run("WritingIntoKeepsEveryKeyTheMachineHad", testWritingIntoKeepsEveryKeyTheMachineHad)
|
||||
t.Run("AFileWrittenIntoThatWasNotThereIsRemovedWhenOnlyTheMeshsKeysAreLeft", testAFileWrittenIntoThatWasNotThereIsRemovedWhenOnlyTheMeshsKeysAreLeft)
|
||||
t.Run("AKeyNoLongerDeclaredGoesBackAndANewOneIsRemembered", testAKeyNoLongerDeclaredGoesBackAndANewOneIsRemembered)
|
||||
t.Run("AFileThatIsNotAnObjectIsRefusedAndLeftAlone", testAFileThatIsNotAnObjectIsRefusedAndLeftAlone)
|
||||
t.Run("AFileWrittenIntoIsNeverHeldOnAnAdoptedNode", testAFileWrittenIntoIsNeverHeldOnAnAdoptedNode)
|
||||
t.Run("AServiceIsReloadedNotRestartedForWhatItReloadsOn", testAServiceIsReloadedNotRestartedForWhatItReloadsOn)
|
||||
t.Run("AListIsAddedToNeverReplaced", testAListIsAddedToNeverReplaced)
|
||||
t.Run("AListTheMeshCreatedGoesWhenEmptied", testAListTheMeshCreatedGoesWhenEmptied)
|
||||
t.Run("AHoldFromAWholeFileDoesNotKeepOutAnIntoWrite", testAHoldFromAWholeFileDoesNotKeepOutAnIntoWrite)
|
||||
t.Run("AWriteWithNoRecordOfItIsTheMeshsOwn", testAWriteWithNoRecordOfItIsTheMeshsOwn)
|
||||
}
|
||||
|
||||
@@ -14,7 +14,7 @@ import (
|
||||
// changed. Who could replace the link is "every account", "the account X" or "the group X", by the account and the
|
||||
// directories the test runs as: the checker's isolated step runs as the account nobody, which owns / there (issue 1919,
|
||||
// R4g), so the test demands a who in any of the forms couldReplace and linkReplacer produce, not "every account" alone.
|
||||
func TestJudgeDirectoriesSaysWhatTheWalkWouldRefuseAndChangesNothing(t *testing.T) {
|
||||
func testJudgeDirectoriesSaysWhatTheWalkWouldRefuseAndChangesNothing(t *testing.T) {
|
||||
base := t.TempDir()
|
||||
plain := filepath.Join(base, "plain")
|
||||
if err := os.Mkdir(plain, 0o755); err != nil {
|
||||
@@ -56,7 +56,7 @@ func TestJudgeDirectoriesSaysWhatTheWalkWouldRefuseAndChangesNothing(t *testing.
|
||||
}
|
||||
|
||||
// A link only root could have made is followed by the judgement as by the apply.
|
||||
func TestJudgeDirectoriesFollowsARootOnlyLink(t *testing.T) {
|
||||
func testJudgeDirectoriesFollowsARootOnlyLink(t *testing.T) {
|
||||
wasDirs, wasLinks := couldReplace, linkReplacer
|
||||
couldReplace = func(string, uint32, uint32, uint32) string { return "" }
|
||||
linkReplacer = func(string, uint32) string { return "" }
|
||||
@@ -73,3 +73,9 @@ func TestJudgeDirectoriesFollowsARootOnlyLink(t *testing.T) {
|
||||
t.Fatalf("a directory behind a root-only link is not said placed: %q", said)
|
||||
}
|
||||
}
|
||||
|
||||
// TestJudgeDirectories runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestJudgeDirectories(t *testing.T) {
|
||||
t.Run("JudgeDirectoriesSaysWhatTheWalkWouldRefuseAndChangesNothing", testJudgeDirectoriesSaysWhatTheWalkWouldRefuseAndChangesNothing)
|
||||
t.Run("JudgeDirectoriesFollowsARootOnlyLink", testJudgeDirectoriesFollowsARootOnlyLink)
|
||||
}
|
||||
|
||||
@@ -137,7 +137,7 @@ func statOf(t *testing.T, path string) unix.Stat_t {
|
||||
|
||||
// Row 6: the root and every requested sub-path kept in the library's group with group rwx and setgid on every apply —
|
||||
// those folders alone, never what is in them; owner, owner's and others' bits unchanged.
|
||||
func TestALibraryIsKeptInItsGroup(t *testing.T) {
|
||||
func testALibraryIsKeptInItsGroup(t *testing.T) {
|
||||
gid := testGID(t)
|
||||
canSetGroups(t, gid)
|
||||
libraries(t, nil, nil)
|
||||
@@ -187,7 +187,7 @@ func TestALibraryIsKeptInItsGroup(t *testing.T) {
|
||||
}
|
||||
|
||||
// Row 9: a missing sub-path is made with the root's owner, the library's group, group rwx and setgid.
|
||||
func TestAMissingSubPathIsMadeAsTheRootIs(t *testing.T) {
|
||||
func testAMissingSubPathIsMadeAsTheRootIs(t *testing.T) {
|
||||
gid := testGID(t)
|
||||
canSetGroups(t, gid)
|
||||
libraries(t, nil, nil)
|
||||
@@ -216,7 +216,7 @@ func TestAMissingSubPathIsMadeAsTheRootIs(t *testing.T) {
|
||||
}
|
||||
|
||||
// Row 7 (keep wait) and §8: a root that holds data not in the group waits with reason keep, and nothing is changed.
|
||||
func TestARootThatHoldsDataWaitsForTheOperatorsWord(t *testing.T) {
|
||||
func testARootThatHoldsDataWaitsForTheOperatorsWord(t *testing.T) {
|
||||
gid := testGID(t)
|
||||
libraries(t, nil, nil)
|
||||
root := filepath.Join(t.TempDir(), "media")
|
||||
@@ -244,7 +244,7 @@ func TestARootThatHoldsDataWaitsForTheOperatorsWord(t *testing.T) {
|
||||
// Row 7, the act: group, group write and setgid set under the root; no link followed; no other filesystem entered;
|
||||
// a file with another name elsewhere left; owner, owner's and others' bits unchanged; nothing without a warrant
|
||||
// (the act's ask, internal/link); an undeclared library refused; a walk over its bound goes on from its cursor.
|
||||
func TestTheTakeActSetsTheGroupUnderTheRoot(t *testing.T) {
|
||||
func testTheTakeActSetsTheGroupUnderTheRoot(t *testing.T) {
|
||||
gid := testGID(t)
|
||||
canSetGroups(t, gid)
|
||||
libraries(t, nil, nil)
|
||||
@@ -330,7 +330,7 @@ func TestTheTakeActSetsTheGroupUnderTheRoot(t *testing.T) {
|
||||
}
|
||||
|
||||
// Row 7, the act: another filesystem is not entered — a folder whose device is not the root's is passed by.
|
||||
func TestTheTakeActEntersNoOtherFilesystem(t *testing.T) {
|
||||
func testTheTakeActEntersNoOtherFilesystem(t *testing.T) {
|
||||
gid := testGID(t)
|
||||
root := t.TempDir()
|
||||
mount := filepath.Join(root, "elsewhere")
|
||||
@@ -358,7 +358,7 @@ func TestTheTakeActEntersNoOtherFilesystem(t *testing.T) {
|
||||
|
||||
// Row 9: a root that is absent, or whose disk is not mounted, makes nothing, holds the containers that mount it,
|
||||
// and waits with reason disk; off its home, a mount that is not there holds them too.
|
||||
func TestALibraryWhoseDiskIsNotThereHoldsItsContainers(t *testing.T) {
|
||||
func testALibraryWhoseDiskIsNotThereHoldsItsContainers(t *testing.T) {
|
||||
gid := testGID(t)
|
||||
base := t.TempDir()
|
||||
disk := filepath.Join(base, "disk")
|
||||
@@ -409,7 +409,7 @@ func TestALibraryWhoseDiskIsNotThereHoldsItsContainers(t *testing.T) {
|
||||
|
||||
// Row 3: the library's group made with its number; a name or number that is another's refused; what was made, and
|
||||
// only that, removed when no longer declared.
|
||||
func TestALibrarysGroupIsMadeWithItsNumber(t *testing.T) {
|
||||
func testALibrarysGroupIsMadeWithItsNumber(t *testing.T) {
|
||||
m := &accountsMachine{users: map[string][2]int{}, groups: map[string][2]int{"media": {2000, 0}}}
|
||||
d := withGroups(t, `{"name":"mesh-media","gid":62000}`, ``, ``)
|
||||
report, known, err := Apply(context.Background(), archHost(t), d, store.State{}, store.OriginDeclared, m.run, nil, nil)
|
||||
@@ -442,7 +442,7 @@ func TestALibrarysGroupIsMadeWithItsNumber(t *testing.T) {
|
||||
|
||||
// Row 4: a module's user with its own group (its uid's number), its first library's group as primary and its other
|
||||
// libraries' as added groups.
|
||||
func TestAModulesUserIsInItsLibrariesGroups(t *testing.T) {
|
||||
func testAModulesUserIsInItsLibrariesGroups(t *testing.T) {
|
||||
m := &accountsMachine{users: map[string][2]int{}, groups: map[string][2]int{}}
|
||||
d := withGroups(t, `{"name":"mesh-media","gid":62000},{"name":"mesh-books","gid":62001}`,
|
||||
`{"module":"radarr","name":"mesh-radarr","uid":61001,"gid":62000,"groups":[62001]}`, ``)
|
||||
@@ -466,7 +466,7 @@ func TestAModulesUserIsInItsLibrariesGroups(t *testing.T) {
|
||||
|
||||
// Row 11: the tool runner's account is put in each library's group once, its unit restarted for it (a change of
|
||||
// library:<name>), and taken out once no library puts it there.
|
||||
func TestTheToolRunnerIsInItsLibrariesGroups(t *testing.T) {
|
||||
func testTheToolRunnerIsInItsLibrariesGroups(t *testing.T) {
|
||||
gid := testGID(t)
|
||||
libraries(t, []string{"/srv/media"}, nil)
|
||||
m := &accountsMachine{users: map[string][2]int{"nox": {1003, 1003}}, groups: map[string][2]int{"nox": {1003, 0}}}
|
||||
@@ -501,7 +501,7 @@ func TestTheToolRunnerIsInItsLibrariesGroups(t *testing.T) {
|
||||
|
||||
// Row 15: a library group, an identity's added group or an image told a root group's number is refused with its
|
||||
// reason, and nothing is made or started.
|
||||
func TestNoLibraryGroupIsRoot(t *testing.T) {
|
||||
func testNoLibraryGroupIsRoot(t *testing.T) {
|
||||
was := RootGroupIDs
|
||||
RootGroupIDs = func() map[int]string { return map[int]string{10: "wheel"} }
|
||||
defer func() { RootGroupIDs = was }()
|
||||
@@ -531,7 +531,7 @@ func TestNoLibraryGroupIsRoot(t *testing.T) {
|
||||
}
|
||||
|
||||
// A library's filesystem that cannot be named this time is unknown, never a move; another filesystem at the root is.
|
||||
func TestALibraryNotNamedIsUnknownAndAnotherFilesystemIsAMove(t *testing.T) {
|
||||
func testALibraryNotNamedIsUnknownAndAnotherFilesystemIsAMove(t *testing.T) {
|
||||
gid := testGID(t)
|
||||
canSetGroups(t, gid)
|
||||
base := t.TempDir()
|
||||
@@ -589,7 +589,7 @@ func TestALibraryNotNamedIsUnknownAndAnotherFilesystemIsAMove(t *testing.T) {
|
||||
|
||||
// Old-shape parity: a controller older than ADR 0328 sends no groups, identities or libraries, and an access is
|
||||
// applied exactly as before ADR 0325 — mounted when present, refused when absent, nothing kept, made or held.
|
||||
func TestAnOlderControllersDeclarationIsAppliedAsBefore(t *testing.T) {
|
||||
func testAnOlderControllersDeclarationIsAppliedAsBefore(t *testing.T) {
|
||||
libraries(t, nil, nil)
|
||||
dir := t.TempDir()
|
||||
present := filepath.Join(dir, "library")
|
||||
@@ -628,7 +628,7 @@ func jsonInto(raw string, into any) error { return json.Unmarshal([]byte(raw), i
|
||||
|
||||
// Row 4: a module that joins a library later is given its group as primary on the account the mesh made; an account
|
||||
// the mesh did not make is never changed, and is refused if it is not as declared.
|
||||
func TestAModuleThatJoinsALibraryLaterIsGivenItsGroup(t *testing.T) {
|
||||
func testAModuleThatJoinsALibraryLaterIsGivenItsGroup(t *testing.T) {
|
||||
m := &accountsMachine{users: map[string][2]int{}, groups: map[string][2]int{}}
|
||||
own := withGroups(t, `{"name":"mesh-media","gid":62000}`,
|
||||
`{"module":"radarr","name":"mesh-radarr","uid":61001,"gid":61001}`, ``)
|
||||
@@ -654,7 +654,7 @@ func TestAModuleThatJoinsALibraryLaterIsGivenItsGroup(t *testing.T) {
|
||||
}
|
||||
|
||||
// A library's root is never in the machine's own trees, as an access's never is (novox/hq issue 339).
|
||||
func TestALibraryIsNeverTheMachinesOwnTree(t *testing.T) {
|
||||
func testALibraryIsNeverTheMachinesOwnTree(t *testing.T) {
|
||||
gid := testGID(t)
|
||||
libraries(t, nil, nil)
|
||||
for _, root := range []string{"/etc", "/usr/share", "/var/lib/mesh-host/x"} {
|
||||
@@ -670,7 +670,7 @@ func TestALibraryIsNeverTheMachinesOwnTree(t *testing.T) {
|
||||
|
||||
// §7: a root in shape with old data beneath it not in the group is asked about, never kept without a warrant; a root
|
||||
// and sample all in shape are kept; once taken, never asked again on that filesystem.
|
||||
func TestARootInShapeWithDataBelowNotInTheGroupWaits(t *testing.T) {
|
||||
func testARootInShapeWithDataBelowNotInTheGroupWaits(t *testing.T) {
|
||||
gid := testGID(t)
|
||||
canSetGroups(t, gid)
|
||||
libraries(t, nil, nil)
|
||||
@@ -720,7 +720,7 @@ func TestARootInShapeWithDataBelowNotInTheGroupWaits(t *testing.T) {
|
||||
|
||||
// Review: a file with another name that root owns is left as it is (its other name may be anywhere), and a setgid
|
||||
// file never keeps its setgid bit once regrouped.
|
||||
func TestRootsLinkedFilesAreLeftAndSetgidIsNeverKept(t *testing.T) {
|
||||
func testRootsLinkedFilesAreLeftAndSetgidIsNeverKept(t *testing.T) {
|
||||
gid := testGID(t)
|
||||
canSetGroups(t, gid)
|
||||
f, err := os.CreateTemp(t.TempDir(), "file")
|
||||
@@ -751,7 +751,7 @@ func TestRootsLinkedFilesAreLeftAndSetgidIsNeverKept(t *testing.T) {
|
||||
|
||||
// Review: a sub-path asked for after the library was kept without a warrant, which holds data not in the group,
|
||||
// waits for the operator's word as the root would, and nothing of it is changed; an empty one is kept.
|
||||
func TestASubPathHoldingOldDataWaitsForTheOperatorsWord(t *testing.T) {
|
||||
func testASubPathHoldingOldDataWaitsForTheOperatorsWord(t *testing.T) {
|
||||
gid := testGID(t)
|
||||
canSetGroups(t, gid)
|
||||
libraries(t, nil, nil)
|
||||
@@ -789,7 +789,7 @@ func TestASubPathHoldingOldDataWaitsForTheOperatorsWord(t *testing.T) {
|
||||
}
|
||||
|
||||
// Review: an apply does not wait for a take walk that is running: it leaves the library to it.
|
||||
func TestAnApplyDoesNotWaitForATakeWalk(t *testing.T) {
|
||||
func testAnApplyDoesNotWaitForATakeWalk(t *testing.T) {
|
||||
gid := testGID(t)
|
||||
libraries(t, nil, nil)
|
||||
root := filepath.Join(t.TempDir(), "media")
|
||||
@@ -818,7 +818,7 @@ func TestAnApplyDoesNotWaitForATakeWalk(t *testing.T) {
|
||||
|
||||
// Review: a root in shape whose data beneath — in no requested sub-path — is not in the group waits: the sample, not
|
||||
// the root alone, says whether the data is the library's already (§7).
|
||||
func TestTheSampleBeneathARootInShapeIsJudged(t *testing.T) {
|
||||
func testTheSampleBeneathARootInShapeIsJudged(t *testing.T) {
|
||||
gid := testGID(t)
|
||||
canSetGroups(t, gid)
|
||||
libraries(t, nil, nil)
|
||||
@@ -846,7 +846,7 @@ func TestTheSampleBeneathARootInShapeIsJudged(t *testing.T) {
|
||||
|
||||
// Review: an apply that finds the library's lock held by something that is no take walk (a take act about to be
|
||||
// refused) waits for it and judges the library as always: a library whose disk is not there still holds.
|
||||
func TestAnApplyWaitsForALockThatIsNoWalk(t *testing.T) {
|
||||
func testAnApplyWaitsForALockThatIsNoWalk(t *testing.T) {
|
||||
gid := testGID(t)
|
||||
libraries(t, nil, nil)
|
||||
root := filepath.Join(t.TempDir(), "gone", "media")
|
||||
@@ -861,7 +861,7 @@ func TestAnApplyWaitsForALockThatIsNoWalk(t *testing.T) {
|
||||
|
||||
// ADR 0334 §2: the tool runner's account joins a module's own group once, its unit restarted for it (a change of
|
||||
// identity:<module>), and is taken out once no identity names it; an account not here, or root's, is refused.
|
||||
func TestTheToolRunnerJoinsAModulesOwnGroup(t *testing.T) {
|
||||
func testTheToolRunnerJoinsAModulesOwnGroup(t *testing.T) {
|
||||
m := &accountsMachine{users: map[string][2]int{"nox": {1003, 1003}}, groups: map[string][2]int{"nox": {1003, 0}}}
|
||||
d := withGroups(t, ``, `{"module":"radarr","name":"mesh-radarr","uid":61001,"gid":61001,"runner":"nox"}`, ``)
|
||||
report, known, err := Apply(context.Background(), archHost(t), d, store.State{}, store.OriginDeclared, m.run, nil, nil)
|
||||
@@ -918,7 +918,7 @@ func TestTheToolRunnerJoinsAModulesOwnGroup(t *testing.T) {
|
||||
|
||||
// ADR 0334 §2: a service naming identity:<module> under restart-on is restarted when the tool runner joins the
|
||||
// module's own group, and not on an apply where nothing moved.
|
||||
func TestTheToolRunnerIsRestartedOnceForTheOwnGroup(t *testing.T) {
|
||||
func testTheToolRunnerIsRestartedOnceForTheOwnGroup(t *testing.T) {
|
||||
m := &accountsMachine{users: map[string][2]int{"nox": {1003, 1003}}, groups: map[string][2]int{"nox": {1003, 0}}}
|
||||
d := withGroups(t, ``, `{"module":"radarr","name":"mesh-radarr","uid":61001,"gid":61001,"runner":"nox"}`,
|
||||
`{"id":"node-tools.unit","type":"service","unit":"node-tools.service","state":"running",`+
|
||||
@@ -958,7 +958,7 @@ func TestTheToolRunnerIsRestartedOnceForTheOwnGroup(t *testing.T) {
|
||||
|
||||
// Review: a library's runner that is refused keeps the library's outcome, is said as runner:library:<name>, and never
|
||||
// fails the apply; a runner that leaves a group restarts the tool runner once, in the apply it leaves.
|
||||
func TestARefusedLibraryRunnerIsAWarningAndLeavingRestarts(t *testing.T) {
|
||||
func testARefusedLibraryRunnerIsAWarningAndLeavingRestarts(t *testing.T) {
|
||||
gid := testGID(t)
|
||||
libraries(t, []string{"/srv/media"}, nil)
|
||||
m := &accountsMachine{users: map[string][2]int{"nox": {1003, 1003}}, groups: map[string][2]int{"nox": {1003, 0}}}
|
||||
@@ -1011,7 +1011,7 @@ func TestARefusedLibraryRunnerIsAWarningAndLeavingRestarts(t *testing.T) {
|
||||
|
||||
// ADR 0334 §1: a module's own directory may carry the setgid bit, so what is made beneath it keeps its own group;
|
||||
// it is set, held across applies, put back and said when it is taken off. Setuid and sticky are refused.
|
||||
func TestADirectorysSetgidBitIsKept(t *testing.T) {
|
||||
func testADirectorysSetgidBitIsKept(t *testing.T) {
|
||||
dir := filepath.Join(t.TempDir(), "state")
|
||||
d := declare(t, `{"id":"radarr.state","type":"directory","path":"`+dir+`","mode":"2750"}`)
|
||||
if _, _, err := Apply(context.Background(), archHost(t), d, store.State{}, store.OriginDeclared, noServices, nil,
|
||||
@@ -1048,3 +1048,31 @@ func TestADirectorysSetgidBitIsKept(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestLibrary runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestLibrary(t *testing.T) {
|
||||
t.Run("ALibraryIsKeptInItsGroup", testALibraryIsKeptInItsGroup)
|
||||
t.Run("AMissingSubPathIsMadeAsTheRootIs", testAMissingSubPathIsMadeAsTheRootIs)
|
||||
t.Run("ARootThatHoldsDataWaitsForTheOperatorsWord", testARootThatHoldsDataWaitsForTheOperatorsWord)
|
||||
t.Run("TheTakeActSetsTheGroupUnderTheRoot", testTheTakeActSetsTheGroupUnderTheRoot)
|
||||
t.Run("TheTakeActEntersNoOtherFilesystem", testTheTakeActEntersNoOtherFilesystem)
|
||||
t.Run("ALibraryWhoseDiskIsNotThereHoldsItsContainers", testALibraryWhoseDiskIsNotThereHoldsItsContainers)
|
||||
t.Run("ALibrarysGroupIsMadeWithItsNumber", testALibrarysGroupIsMadeWithItsNumber)
|
||||
t.Run("AModulesUserIsInItsLibrariesGroups", testAModulesUserIsInItsLibrariesGroups)
|
||||
t.Run("TheToolRunnerIsInItsLibrariesGroups", testTheToolRunnerIsInItsLibrariesGroups)
|
||||
t.Run("NoLibraryGroupIsRoot", testNoLibraryGroupIsRoot)
|
||||
t.Run("ALibraryNotNamedIsUnknownAndAnotherFilesystemIsAMove", testALibraryNotNamedIsUnknownAndAnotherFilesystemIsAMove)
|
||||
t.Run("AnOlderControllersDeclarationIsAppliedAsBefore", testAnOlderControllersDeclarationIsAppliedAsBefore)
|
||||
t.Run("AModuleThatJoinsALibraryLaterIsGivenItsGroup", testAModuleThatJoinsALibraryLaterIsGivenItsGroup)
|
||||
t.Run("ALibraryIsNeverTheMachinesOwnTree", testALibraryIsNeverTheMachinesOwnTree)
|
||||
t.Run("ARootInShapeWithDataBelowNotInTheGroupWaits", testARootInShapeWithDataBelowNotInTheGroupWaits)
|
||||
t.Run("RootsLinkedFilesAreLeftAndSetgidIsNeverKept", testRootsLinkedFilesAreLeftAndSetgidIsNeverKept)
|
||||
t.Run("ASubPathHoldingOldDataWaitsForTheOperatorsWord", testASubPathHoldingOldDataWaitsForTheOperatorsWord)
|
||||
t.Run("AnApplyDoesNotWaitForATakeWalk", testAnApplyDoesNotWaitForATakeWalk)
|
||||
t.Run("TheSampleBeneathARootInShapeIsJudged", testTheSampleBeneathARootInShapeIsJudged)
|
||||
t.Run("AnApplyWaitsForALockThatIsNoWalk", testAnApplyWaitsForALockThatIsNoWalk)
|
||||
t.Run("TheToolRunnerJoinsAModulesOwnGroup", testTheToolRunnerJoinsAModulesOwnGroup)
|
||||
t.Run("TheToolRunnerIsRestartedOnceForTheOwnGroup", testTheToolRunnerIsRestartedOnceForTheOwnGroup)
|
||||
t.Run("ARefusedLibraryRunnerIsAWarningAndLeavingRestarts", testARefusedLibraryRunnerIsAWarningAndLeavingRestarts)
|
||||
t.Run("ADirectorysSetgidBitIsKept", testADirectorysSetgidBitIsKept)
|
||||
}
|
||||
|
||||
@@ -78,7 +78,7 @@ func fireOnce(t *testing.T, d *declaration.Declaration, w *windowRun) {
|
||||
s.Wait()
|
||||
}
|
||||
|
||||
func TestAScheduledStepHoldsItsModulesContainerStillAndStartsItAgain(t *testing.T) {
|
||||
func testAScheduledStepHoldsItsModulesContainerStillAndStartsItAgain(t *testing.T) {
|
||||
w := &windowRun{}
|
||||
fireOnce(t, aStoreWithACollector(t), w)
|
||||
|
||||
@@ -103,7 +103,7 @@ func TestAScheduledStepHoldsItsModulesContainerStillAndStartsItAgain(t *testing.
|
||||
}
|
||||
|
||||
// The one that matters: a step that fails must leave the service running.
|
||||
func TestAFailedStepStillClosesTheWindow(t *testing.T) {
|
||||
func testAFailedStepStillClosesTheWindow(t *testing.T) {
|
||||
w := &windowRun{failAt: "run"}
|
||||
fireOnce(t, aStoreWithACollector(t), w)
|
||||
|
||||
@@ -120,7 +120,7 @@ func TestAFailedStepStillClosesTheWindow(t *testing.T) {
|
||||
|
||||
// A container that will not come back is said loudly: it is down, and nothing else notices until
|
||||
// the next apply compares it.
|
||||
func TestAContainerThatWillNotStartAgainIsSaidLoudly(t *testing.T) {
|
||||
func testAContainerThatWillNotStartAgainIsSaidLoudly(t *testing.T) {
|
||||
w := &windowRun{wontGo: "mesh-registry"}
|
||||
var said []string
|
||||
clock := &fixedClock{now: time.Date(2026, 10, 2, 3, 29, 0, 0, time.UTC)}
|
||||
@@ -142,7 +142,7 @@ func TestAContainerThatWillNotStartAgainIsSaidLoudly(t *testing.T) {
|
||||
|
||||
// Several containers come back in the reverse of the order they were stopped: a module names the
|
||||
// dependant first, and starting it before what it depends on is not bringing it back.
|
||||
func TestTheWindowClosesInTheReverseOfTheOrderItOpened(t *testing.T) {
|
||||
func testTheWindowClosesInTheReverseOfTheOrderItOpened(t *testing.T) {
|
||||
d := parseTrusted(t, `{"declaration":1,"resources":[
|
||||
{"id":"web","type":"container","name":"web","image":"`+pinned+`"},
|
||||
{"id":"db","type":"container","name":"db","image":"`+pinned+`"},
|
||||
@@ -170,7 +170,7 @@ func TestTheWindowClosesInTheReverseOfTheOrderItOpened(t *testing.T) {
|
||||
}
|
||||
|
||||
// And the refusals, each for what it says rather than that it says something.
|
||||
func TestAMaintenanceWindowIsRefusedWhereItCannotMean(t *testing.T) {
|
||||
func testAMaintenanceWindowIsRefusedWhereItCannotMean(t *testing.T) {
|
||||
for _, c := range []struct{ name, body, says string }{
|
||||
{
|
||||
"a window with no schedule",
|
||||
@@ -205,7 +205,7 @@ func TestAMaintenanceWindowIsRefusedWhereItCannotMean(t *testing.T) {
|
||||
// the install is reported updated and re-established" (containerSpec). Which containers are held
|
||||
// still for the run is the same kind of statement, and a declaration that changed it while the
|
||||
// machine reported no change would be a machine quietly running the old window.
|
||||
func TestAChangedWindowMovesTheSpec(t *testing.T) {
|
||||
func testAChangedWindowMovesTheSpec(t *testing.T) {
|
||||
one := parseTrusted(t, `{"declaration":1,"resources":[
|
||||
{"id":"store","type":"container","name":"mesh-registry","image":"`+pinned+`"},
|
||||
{"id":"other","type":"container","name":"other","image":"`+pinned+`"},
|
||||
@@ -379,7 +379,7 @@ func openAWindow(t *testing.T, d *declaration.Declaration, m *aRegistryMachine,
|
||||
return s
|
||||
}
|
||||
|
||||
func TestAnApplyDuringAWindowLeavesWhatItHoldsAlone(t *testing.T) {
|
||||
func testAnApplyDuringAWindowLeavesWhatItHoldsAlone(t *testing.T) {
|
||||
d := aStoreWithACollector(t)
|
||||
want := containerSpec(d.Resources[0].(*declaration.Container), inputs{})
|
||||
m := newRegistryMachine(want)
|
||||
@@ -446,7 +446,7 @@ func TestAnApplyDuringAWindowLeavesWhatItHoldsAlone(t *testing.T) {
|
||||
// A step that fails releases its hold like one that succeeds: the record is erased in the same
|
||||
// defer that starts the server again, and an apply afterwards does what it always did — here, to a
|
||||
// registry that would not come back, the one thing that brings it back.
|
||||
func TestAFailedStepReleasesItsHold(t *testing.T) {
|
||||
func testAFailedStepReleasesItsHold(t *testing.T) {
|
||||
d := aStoreWithACollector(t)
|
||||
m := newRegistryMachine(containerSpec(d.Resources[0].(*declaration.Container), inputs{}))
|
||||
m.failRun, m.wontGo = true, true
|
||||
@@ -479,7 +479,7 @@ func TestAFailedStepReleasesItsHold(t *testing.T) {
|
||||
// A window whose host died mid-step — crashed, or stood aside for a successor — holds nothing:
|
||||
// the process that would start the server again is gone, so the apply must be free to. And a window
|
||||
// nothing closed ends on its own.
|
||||
func TestAWindowNothingClosesDoesNotHoldForEver(t *testing.T) {
|
||||
func testAWindowNothingClosesDoesNotHoldForEver(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
alive := true
|
||||
windows := &Windows{dir: dir, alive: func(int) bool { return alive }}
|
||||
@@ -514,7 +514,7 @@ func TestAWindowNothingClosesDoesNotHoldForEver(t *testing.T) {
|
||||
|
||||
// A window that cannot be recorded is not opened: an apply would not know, and would recreate the
|
||||
// server under the step. One night's collection is the cheaper loss.
|
||||
func TestAWindowThatCannotBeRecordedIsNotOpened(t *testing.T) {
|
||||
func testAWindowThatCannotBeRecordedIsNotOpened(t *testing.T) {
|
||||
notADir := filepath.Join(t.TempDir(), "state")
|
||||
if err := os.WriteFile(notADir, nil, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -541,3 +541,17 @@ func TestAWindowThatCannotBeRecordedIsNotOpened(t *testing.T) {
|
||||
t.Errorf("the step not running was not said: %v", said)
|
||||
}
|
||||
}
|
||||
|
||||
// TestMaintenanceWindow runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestMaintenanceWindow(t *testing.T) {
|
||||
t.Run("AScheduledStepHoldsItsModulesContainerStillAndStartsItAgain", testAScheduledStepHoldsItsModulesContainerStillAndStartsItAgain)
|
||||
t.Run("AFailedStepStillClosesTheWindow", testAFailedStepStillClosesTheWindow)
|
||||
t.Run("AContainerThatWillNotStartAgainIsSaidLoudly", testAContainerThatWillNotStartAgainIsSaidLoudly)
|
||||
t.Run("TheWindowClosesInTheReverseOfTheOrderItOpened", testTheWindowClosesInTheReverseOfTheOrderItOpened)
|
||||
t.Run("AMaintenanceWindowIsRefusedWhereItCannotMean", testAMaintenanceWindowIsRefusedWhereItCannotMean)
|
||||
t.Run("AChangedWindowMovesTheSpec", testAChangedWindowMovesTheSpec)
|
||||
t.Run("AnApplyDuringAWindowLeavesWhatItHoldsAlone", testAnApplyDuringAWindowLeavesWhatItHoldsAlone)
|
||||
t.Run("AFailedStepReleasesItsHold", testAFailedStepReleasesItsHold)
|
||||
t.Run("AWindowNothingClosesDoesNotHoldForEver", testAWindowNothingClosesDoesNotHoldForEver)
|
||||
t.Run("AWindowThatCannotBeRecordedIsNotOpened", testAWindowThatCannotBeRecordedIsNotOpened)
|
||||
}
|
||||
|
||||
@@ -60,7 +60,7 @@ func holdsTheGate(t *testing.T, target, other string, report Report, err error)
|
||||
}
|
||||
|
||||
// The link there when the apply begins: refused by the guard before anything is applied.
|
||||
func TestADirectoryBehindALinkGatesItsModuleThroughApply(t *testing.T) {
|
||||
func testADirectoryBehindALinkGatesItsModuleThroughApply(t *testing.T) {
|
||||
target, other, decl := aLinkedModule(t)
|
||||
report, _, err := Apply(context.Background(), archHost(t), declare(t, decl), store.State{}, store.OriginDeclared,
|
||||
noServices, nil, nil)
|
||||
@@ -70,7 +70,7 @@ func TestADirectoryBehindALinkGatesItsModuleThroughApply(t *testing.T) {
|
||||
// The link found only at the moment of use: refused by the walk during the apply, and still a refusal that gates its
|
||||
// module and what is below it. Simulated by trusting / for the guard's walk (two walks of /: one to the link, one
|
||||
// from its target) and not for the apply's.
|
||||
func TestADirectoryRefusedDuringTheApplyGatesItsModule(t *testing.T) {
|
||||
func testADirectoryRefusedDuringTheApplyGatesItsModule(t *testing.T) {
|
||||
target, other, decl := aLinkedModule(t)
|
||||
wasDirs, wasLinks := couldReplace, linkReplacer
|
||||
walksOfRoot := 0
|
||||
@@ -93,3 +93,9 @@ func TestADirectoryRefusedDuringTheApplyGatesItsModule(t *testing.T) {
|
||||
}
|
||||
holdsTheGate(t, target, other, report, err)
|
||||
}
|
||||
|
||||
// TestMeshDirsGate runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestMeshDirsGate(t *testing.T) {
|
||||
t.Run("ADirectoryBehindALinkGatesItsModuleThroughApply", testADirectoryBehindALinkGatesItsModuleThroughApply)
|
||||
t.Run("ADirectoryRefusedDuringTheApplyGatesItsModule", testADirectoryRefusedDuringTheApplyGatesItsModule)
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@ import (
|
||||
|
||||
// A link only root could have made — itself root's, in directories no other account may write — is followed, as
|
||||
// /var/run to /run is on every node; relative or absolute.
|
||||
func TestALinkOnlyRootCouldMakeIsFollowed(t *testing.T) {
|
||||
func testALinkOnlyRootCouldMakeIsFollowed(t *testing.T) {
|
||||
for name, to := range map[string]func(base string) string{
|
||||
"absolute": func(base string) string { return filepath.Join(base, "elsewhere") },
|
||||
"relative": func(string) string { return "elsewhere" },
|
||||
@@ -43,7 +43,7 @@ func TestALinkOnlyRootCouldMakeIsFollowed(t *testing.T) {
|
||||
}
|
||||
|
||||
// A link another account owns refuses the directory even in directories root alone may write, naming the account.
|
||||
func TestALinkAnotherAccountOwnsIsRefused(t *testing.T) {
|
||||
func testALinkAnotherAccountOwnsIsRefused(t *testing.T) {
|
||||
rootAlone(t, "the account mallory (it owns the link)")
|
||||
base, r, previous := aMeshDirectory(t)
|
||||
target := swapParentForLink(t, base, filepath.Join(base, "elsewhere"))
|
||||
@@ -58,7 +58,7 @@ func TestALinkAnotherAccountOwnsIsRefused(t *testing.T) {
|
||||
}
|
||||
|
||||
// A directory that is missing is made through the walk, below a link root alone could make.
|
||||
func TestAMissingDirectoryIsMadeBehindARootOnlyLink(t *testing.T) {
|
||||
func testAMissingDirectoryIsMadeBehindARootOnlyLink(t *testing.T) {
|
||||
rootAlone(t, "")
|
||||
base := t.TempDir()
|
||||
if err := os.Mkdir(filepath.Join(base, "real"), 0o755); err != nil {
|
||||
@@ -89,3 +89,10 @@ func rootAlone(t *testing.T, linkOwner string) {
|
||||
linkReplacer = func(string, uint32) string { return linkOwner }
|
||||
t.Cleanup(func() { couldReplace, linkReplacer = wasDirs, wasLinks })
|
||||
}
|
||||
|
||||
// TestMeshDirs runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestMeshDirs(t *testing.T) {
|
||||
t.Run("ALinkOnlyRootCouldMakeIsFollowed", testALinkOnlyRootCouldMakeIsFollowed)
|
||||
t.Run("ALinkAnotherAccountOwnsIsRefused", testALinkAnotherAccountOwnsIsRefused)
|
||||
t.Run("AMissingDirectoryIsMadeBehindARootOnlyLink", testAMissingDirectoryIsMadeBehindARootOnlyLink)
|
||||
}
|
||||
|
||||
@@ -19,7 +19,7 @@ import (
|
||||
// directory in a tree that is the engine's (0755, root); on ace and novox /var/lib/mesh/postgres was there as
|
||||
// root:root 0700 before postgres's data directory was applied, and the engine left it to root, so the postgres
|
||||
// provider, running as the operator's account, could not reach its own files.
|
||||
func TestADirectoryInTheMeshsOwnTreeMadeByTheEngineIsTheMeshs(t *testing.T) {
|
||||
func testADirectoryInTheMeshsOwnTreeMadeByTheEngineIsTheMeshs(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
before := meshDataRoot
|
||||
meshDataRoot = filepath.Join(root, "mesh")
|
||||
@@ -47,27 +47,55 @@ func TestADirectoryInTheMeshsOwnTreeMadeByTheEngineIsTheMeshs(t *testing.T) {
|
||||
if info, _ := os.Stat(made); info.Mode().Perm() != 0o750 {
|
||||
t.Errorf("it was not given its declared mode: %04o", info.Mode().Perm())
|
||||
}
|
||||
// H-A-374, H-A-392: a record-held directory whose mode drifted on disk is set right at the engine's start, with one
|
||||
// line, though its composition is unchanged; as declared, it says nothing.
|
||||
if err := os.Chmod(made, 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
postgres := declare(t, `{"id":"postgres.data","type":"directory","path":"`+made+`","mode":"0750"}`)
|
||||
if drifts := DirectoryDrifts(postgres, state); len(drifts) != 1 || drifts[0].Drift != "mode 0700, 0750 declared" {
|
||||
t.Errorf("the drift read is %+v", drifts)
|
||||
}
|
||||
if lines := ConvergeDirectories(postgres, state); len(lines) != 1 || !strings.Contains(lines[0], "was mode 0700, 0750 declared, and is set right") {
|
||||
t.Errorf("a drifted directory the mesh made was converged as %q", lines)
|
||||
}
|
||||
if info, _ := os.Stat(made); info.Mode().Perm() != 0o750 {
|
||||
t.Errorf("it was not set right at the start: %04o", info.Mode().Perm())
|
||||
}
|
||||
if lines := ConvergeDirectories(postgres, state); len(lines) != 0 {
|
||||
t.Errorf("a directory as declared was said at the start: %q", lines)
|
||||
}
|
||||
|
||||
// Outside the mesh's tree the rule of issue 339 stands: found, used as found.
|
||||
// Outside the mesh's tree the rule of issue 339 stands: found, used as found; and left so at a start, said.
|
||||
other := filepath.Join(root, "var-lib", "notes")
|
||||
if err := os.MkdirAll(other, 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
said = nil
|
||||
decl = `{"id":"notes.data","type":"directory","path":"` + other + `","mode":"0750"}`
|
||||
if _, _, err := Apply(context.Background(), archHost(t), declare(t, decl), store.State{}, store.OriginDeclared,
|
||||
noServices, func(line string) { said = append(said, line) }, nil); err != nil {
|
||||
_, found, err := Apply(context.Background(), archHost(t), declare(t, decl), store.State{}, store.OriginDeclared,
|
||||
noServices, func(line string) { said = append(said, line) }, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(strings.Join(said, "\n"), "WARNING notes.data") {
|
||||
t.Errorf("a directory found outside the mesh's tree was not used as found: %q", said)
|
||||
}
|
||||
if lines := ConvergeDirectories(declare(t, decl), found); len(lines) != 1 || !strings.Contains(lines[0], "left as found") {
|
||||
t.Errorf("a directory the mesh never made was converged as %q", lines)
|
||||
}
|
||||
if drifts := DirectoryDrifts(declare(t, decl), found); len(drifts) != 0 {
|
||||
t.Errorf("a directory the mesh never made is named as drift: %+v", drifts)
|
||||
}
|
||||
if info, _ := os.Stat(other); info.Mode().Perm() != 0o700 {
|
||||
t.Errorf("a directory the mesh never made was changed at the start: %04o", info.Mode().Perm())
|
||||
}
|
||||
}
|
||||
|
||||
// Review of issue 1873's fix: the tree is judged by where the path leads, not by its text. A root-only link inside the
|
||||
// mesh's tree pointing out of it (to /var/lib/systemd, say) would otherwise make a directory outside the tree, owned by
|
||||
// the engine's account, the mesh's to chown: issue 1873's fault again. It is used as found.
|
||||
func TestALinkInTheMeshsTreeLeadingOutOfItIsNotTheTree(t *testing.T) {
|
||||
func testALinkInTheMeshsTreeLeadingOutOfItIsNotTheTree(t *testing.T) {
|
||||
rootAlone(t, "")
|
||||
root := t.TempDir()
|
||||
before := meshDataRoot
|
||||
@@ -98,3 +126,9 @@ func TestALinkInTheMeshsTreeLeadingOutOfItIsNotTheTree(t *testing.T) {
|
||||
t.Errorf("the directory outside the tree was given mode %o (was 700)", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestMeshTreeFound runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestMeshTreeFound(t *testing.T) {
|
||||
t.Run("ADirectoryInTheMeshsOwnTreeMadeByTheEngineIsTheMeshs", testADirectoryInTheMeshsOwnTreeMadeByTheEngineIsTheMeshs)
|
||||
t.Run("ALinkInTheMeshsTreeLeadingOutOfItIsNotTheTree", testALinkInTheMeshsTreeLeadingOutOfItIsNotTheTree)
|
||||
}
|
||||
|
||||
@@ -23,7 +23,7 @@ func twoModules(t *testing.T) *declaration.Declaration {
|
||||
|
||||
// 1132/AC3: every resource of module A applied and one of module B failed: A is a success, B failed with the failing
|
||||
// resource and its error named; a module gated by another's failure is failed too.
|
||||
func TestAnApplyIsGroupedPerModule(t *testing.T) {
|
||||
func testAnApplyIsGroupedPerModule(t *testing.T) {
|
||||
d := twoModules(t)
|
||||
done := Report{Outcomes: []Outcome{
|
||||
{ID: "a.dir", Action: "created"},
|
||||
@@ -51,7 +51,7 @@ func TestAnApplyIsGroupedPerModule(t *testing.T) {
|
||||
}
|
||||
|
||||
// 1132/AC3: an apply that did not fail is a success for every module the declaration names.
|
||||
func TestACleanApplyIsASuccessForEveryModule(t *testing.T) {
|
||||
func testACleanApplyIsASuccessForEveryModule(t *testing.T) {
|
||||
got := ModuleResults(twoModules(t), Report{}, nil)
|
||||
for _, m := range []string{"a", "b", "c"} {
|
||||
if r, ok := got[m]; !ok || r.Failed {
|
||||
@@ -62,7 +62,7 @@ func TestACleanApplyIsASuccessForEveryModule(t *testing.T) {
|
||||
|
||||
// 1132/AC3: a step that belongs to no module stops the apply there; a module with a resource not attempted is not a
|
||||
// success.
|
||||
func TestAModuleNotAttemptedIsNotASuccess(t *testing.T) {
|
||||
func testAModuleNotAttemptedIsNotASuccess(t *testing.T) {
|
||||
d := twoModules(t)
|
||||
err := &Error{Resource: "boot", Err: errors.New("boom"), Stopped: true, Failures: []Failure{{Resource: "boot", Err: errors.New("boom")}},
|
||||
Done: Report{Outcomes: []Outcome{{ID: "a.dir", Action: "created"}}}}
|
||||
@@ -74,3 +74,10 @@ func TestAModuleNotAttemptedIsNotASuccess(t *testing.T) {
|
||||
t.Errorf("b was not attempted: %+v", got["b"])
|
||||
}
|
||||
}
|
||||
|
||||
// TestModuleResults runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestModuleResults(t *testing.T) {
|
||||
t.Run("AnApplyIsGroupedPerModule", testAnApplyIsGroupedPerModule)
|
||||
t.Run("ACleanApplyIsASuccessForEveryModule", testACleanApplyIsASuccessForEveryModule)
|
||||
t.Run("AModuleNotAttemptedIsNotASuccess", testAModuleNotAttemptedIsNotASuccess)
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ import (
|
||||
|
||||
// R6-A AC3: given two modules declaring one path, when one module's want changes, the shared path is neither removed
|
||||
// nor taken from the other module (novox/hq ADR 0539 §9).
|
||||
func TestASharedPathIsNeitherRemovedNorTakenFromTheOtherModule(t *testing.T) {
|
||||
func testASharedPathIsNeitherRemovedNorTakenFromTheOtherModule(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
shared := filepath.Join(dir, "shared.conf")
|
||||
own := filepath.Join(dir, "a-own.conf")
|
||||
@@ -56,7 +56,7 @@ func TestASharedPathIsNeitherRemovedNorTakenFromTheOtherModule(t *testing.T) {
|
||||
|
||||
// R6-A AC4: given modules A and B on a node, when A's want is removed, only A's resources are removed and B is
|
||||
// untouched.
|
||||
func TestARemovedModuleTakesOnlyItsOwnResources(t *testing.T) {
|
||||
func testARemovedModuleTakesOnlyItsOwnResources(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
fa, fb := filepath.Join(dir, "a.conf"), filepath.Join(dir, "b.conf")
|
||||
d := declare(t, `{"id":"a.conf","type":"file","path":"`+fa+`","content":"a\n","module":"a"},
|
||||
@@ -91,7 +91,7 @@ func TestARemovedModuleTakesOnlyItsOwnResources(t *testing.T) {
|
||||
}
|
||||
|
||||
// A record from before the owner was kept is read by its id, so the first removal after the switch is the module's too.
|
||||
func TestARecordWithoutAnOwnerBelongsToTheModuleItsIdNames(t *testing.T) {
|
||||
func testARecordWithoutAnOwnerBelongsToTheModuleItsIdNames(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
fa, fb := filepath.Join(dir, "a.conf"), filepath.Join(dir, "b.conf")
|
||||
d := declare(t, `{"id":"a.conf","type":"file","path":"`+fa+`","content":"a\n"},
|
||||
@@ -123,7 +123,7 @@ func TestARecordWithoutAnOwnerBelongsToTheModuleItsIdNames(t *testing.T) {
|
||||
// says why (issue 774, live on 2026-10-29 at 07:54 UTC on the bus node: the node's own composition, composed without what
|
||||
// it ran once the kept declaration was read no more, removed the bus server, the proxy and three held modules). Only its
|
||||
// want's removal lets it go.
|
||||
func TestAResourceThatMovedToItsModulesCompositionIsLeftByTheNodesOwnApply(t *testing.T) {
|
||||
func testAResourceThatMovedToItsModulesCompositionIsLeftByTheNodesOwnApply(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
id string // the resource the node's own composition carried, and no longer does
|
||||
@@ -222,3 +222,11 @@ func TestAResourceThatMovedToItsModulesCompositionIsLeftByTheNodesOwnApply(t *te
|
||||
}
|
||||
|
||||
func state0() store.State { return store.State{} }
|
||||
|
||||
// TestModuleScope runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestModuleScope(t *testing.T) {
|
||||
t.Run("ASharedPathIsNeitherRemovedNorTakenFromTheOtherModule", testASharedPathIsNeitherRemovedNorTakenFromTheOtherModule)
|
||||
t.Run("ARemovedModuleTakesOnlyItsOwnResources", testARemovedModuleTakesOnlyItsOwnResources)
|
||||
t.Run("ARecordWithoutAnOwnerBelongsToTheModuleItsIdNames", testARecordWithoutAnOwnerBelongsToTheModuleItsIdNames)
|
||||
t.Run("AResourceThatMovedToItsModulesCompositionIsLeftByTheNodesOwnApply", testAResourceThatMovedToItsModulesCompositionIsLeftByTheNodesOwnApply)
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ import (
|
||||
// a directory, and every fill after it failed with "is a directory". A container whose mount source is a file the
|
||||
// declaration declares, not yet there, is not created or replaced: it waits, and the write of that file (WriteFilled)
|
||||
// applies what reads it, the container among them (readsChange), once the file is there.
|
||||
func TestAContainerWaitsForAFileItMountsAndIsMadeWhenTheFillLands(t *testing.T) {
|
||||
func testAContainerWaitsForAFileItMountsAndIsMadeWhenTheFillLands(t *testing.T) {
|
||||
secret := filepath.Join(t.TempDir(), "postgres", "superuser.secret")
|
||||
d := filledDecl(t, secret, `"content":"","mode":"0600","owner-at-runtime":"owned"`,
|
||||
`{"id":"postgres.server","type":"container","name":"postgres","image":"`+pinned+`","volumes":["`+
|
||||
@@ -54,7 +54,7 @@ func TestAContainerWaitsForAFileItMountsAndIsMadeWhenTheFillLands(t *testing.T)
|
||||
// directory in the mesh's own tree, the engine's account's, is the runtime's missing mount source: the engine
|
||||
// removes that empty directory and writes the file, and says so. A directory with anything in it, or one outside the
|
||||
// tree, is never removed: the write fails as before.
|
||||
func TestAnEmptyDirectoryTheRuntimeLeftAtAFilesPathIsReplacedByTheFile(t *testing.T) {
|
||||
func testAnEmptyDirectoryTheRuntimeLeftAtAFilesPathIsReplacedByTheFile(t *testing.T) {
|
||||
rootAlone(t, "")
|
||||
root := t.TempDir()
|
||||
before := meshDataRoot
|
||||
@@ -119,3 +119,9 @@ func TestAnEmptyDirectoryTheRuntimeLeftAtAFilesPathIsReplacedByTheFile(t *testin
|
||||
t.Errorf("a directory outside the tree, reached through a link in it, was replaced: %v %v", info, err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestMountWaits runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestMountWaits(t *testing.T) {
|
||||
t.Run("AContainerWaitsForAFileItMountsAndIsMadeWhenTheFillLands", testAContainerWaitsForAFileItMountsAndIsMadeWhenTheFillLands)
|
||||
t.Run("AnEmptyDirectoryTheRuntimeLeftAtAFilesPathIsReplacedByTheFile", testAnEmptyDirectoryTheRuntimeLeftAtAFilesPathIsReplacedByTheFile)
|
||||
}
|
||||
|
||||
@@ -77,7 +77,7 @@ func readList(t *testing.T, path string) []movedEntry {
|
||||
return list
|
||||
}
|
||||
|
||||
func TestAMoveOutDirectoryMovesOnlyWhatIsNotKnown(t *testing.T) {
|
||||
func testAMoveOutDirectoryMovesOnlyWhatIsNotKnown(t *testing.T) {
|
||||
home := aMoveOutHome(t)
|
||||
dir := filepath.Join(home, ".ssh")
|
||||
outside := filepath.Join(t.TempDir(), "target")
|
||||
@@ -162,7 +162,7 @@ func TestAMoveOutDirectoryMovesOnlyWhatIsNotKnown(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAMoveOutListIsWrittenBeforeTheMove(t *testing.T) {
|
||||
func testAMoveOutListIsWrittenBeforeTheMove(t *testing.T) {
|
||||
home := aMoveOutHome(t)
|
||||
dir := filepath.Join(home, "d")
|
||||
put(t, filepath.Join(dir, "a"), "a", time.Hour)
|
||||
@@ -195,7 +195,7 @@ func TestAMoveOutListIsWrittenBeforeTheMove(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAMoveOutThatMovedNothingMakesNothing(t *testing.T) {
|
||||
func testAMoveOutThatMovedNothingMakesNothing(t *testing.T) {
|
||||
home := aMoveOutHome(t)
|
||||
dir := filepath.Join(home, "d")
|
||||
put(t, filepath.Join(dir, "known"), "k", time.Hour)
|
||||
@@ -222,7 +222,7 @@ func TestAMoveOutThatMovedNothingMakesNothing(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAMoveOutOfANestedStrayThatFailsLeavesNoKeptFolder(t *testing.T) {
|
||||
func testAMoveOutOfANestedStrayThatFailsLeavesNoKeptFolder(t *testing.T) {
|
||||
home := aMoveOutHome(t)
|
||||
dir := filepath.Join(home, "d")
|
||||
put(t, filepath.Join(dir, "x", "f"), "declared", time.Hour)
|
||||
@@ -242,7 +242,7 @@ func TestAMoveOutOfANestedStrayThatFailsLeavesNoKeptFolder(t *testing.T) {
|
||||
}
|
||||
|
||||
// A link swapped into a parent folder, on either side, between the look and the move, is not followed.
|
||||
func TestAMoveOutDoesNotFollowALinkSwappedIntoAParent(t *testing.T) {
|
||||
func testAMoveOutDoesNotFollowALinkSwappedIntoAParent(t *testing.T) {
|
||||
for _, side := range []string{"from", "to"} {
|
||||
t.Run(side, func(t *testing.T) {
|
||||
home := aMoveOutHome(t)
|
||||
@@ -286,7 +286,7 @@ func TestAMoveOutDoesNotFollowALinkSwappedIntoAParent(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestOtherUnknownValuesAndNoValueMoveNothing(t *testing.T) {
|
||||
func testOtherUnknownValuesAndNoValueMoveNothing(t *testing.T) {
|
||||
home := aMoveOutHome(t)
|
||||
for _, v := range []string{`,"unknown":"program"`, `,"unknown":"module"`, ``} {
|
||||
dir := filepath.Join(home, "d")
|
||||
@@ -300,7 +300,7 @@ func TestOtherUnknownValuesAndNoValueMoveNothing(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAMoveOutArchiveKeepsWhatItUnpackedAndMovesAStray(t *testing.T) {
|
||||
func testAMoveOutArchiveKeepsWhatItUnpackedAndMovesAStray(t *testing.T) {
|
||||
home := aMoveOutHome(t)
|
||||
dir := filepath.Join(home, "theme")
|
||||
put(t, filepath.Join(dir, "stray"), "s", time.Hour)
|
||||
@@ -320,7 +320,7 @@ func TestAMoveOutArchiveKeepsWhatItUnpackedAndMovesAStray(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestMoveOutNeedsAHome(t *testing.T) {
|
||||
func testMoveOutNeedsAHome(t *testing.T) {
|
||||
aMoveOutHome(t)
|
||||
dir := filepath.Join(t.TempDir(), "elsewhere")
|
||||
put(t, filepath.Join(dir, "stray"), "s", time.Hour)
|
||||
@@ -333,7 +333,7 @@ func TestMoveOutNeedsAHome(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestMoveOutRefusesAnotherFileSystem(t *testing.T) {
|
||||
func testMoveOutRefusesAnotherFileSystem(t *testing.T) {
|
||||
home := aMoveOutHome(t)
|
||||
dir := filepath.Join(home, "d")
|
||||
put(t, filepath.Join(dir, "stray"), "s", time.Hour)
|
||||
@@ -353,3 +353,16 @@ func TestMoveOutRefusesAnotherFileSystem(t *testing.T) {
|
||||
t.Error("something moved or was made")
|
||||
}
|
||||
}
|
||||
|
||||
// TestMoveOut runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestMoveOut(t *testing.T) {
|
||||
t.Run("AMoveOutDirectoryMovesOnlyWhatIsNotKnown", testAMoveOutDirectoryMovesOnlyWhatIsNotKnown)
|
||||
t.Run("AMoveOutListIsWrittenBeforeTheMove", testAMoveOutListIsWrittenBeforeTheMove)
|
||||
t.Run("AMoveOutThatMovedNothingMakesNothing", testAMoveOutThatMovedNothingMakesNothing)
|
||||
t.Run("AMoveOutOfANestedStrayThatFailsLeavesNoKeptFolder", testAMoveOutOfANestedStrayThatFailsLeavesNoKeptFolder)
|
||||
t.Run("AMoveOutDoesNotFollowALinkSwappedIntoAParent", testAMoveOutDoesNotFollowALinkSwappedIntoAParent)
|
||||
t.Run("OtherUnknownValuesAndNoValueMoveNothing", testOtherUnknownValuesAndNoValueMoveNothing)
|
||||
t.Run("AMoveOutArchiveKeepsWhatItUnpackedAndMovesAStray", testAMoveOutArchiveKeepsWhatItUnpackedAndMovesAStray)
|
||||
t.Run("MoveOutNeedsAHome", testMoveOutNeedsAHome)
|
||||
t.Run("MoveOutRefusesAnotherFileSystem", testMoveOutRefusesAnotherFileSystem)
|
||||
}
|
||||
|
||||
@@ -119,7 +119,7 @@ func applyWith(t *testing.T, d *declaration.Declaration, known store.State, run
|
||||
KeepIn(t.TempDir()))
|
||||
}
|
||||
|
||||
func TestAnOpeningOnAMachineWithNoFirewallChangesNothing(t *testing.T) {
|
||||
func testAnOpeningOnAMachineWithNoFirewallChangesNothing(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
u := &ufwMachine{}
|
||||
report, state, err := applyWith(t, adopted(t, `{"taken":[]}`, busOpening+","+withConf(dir)), store.State{}, u.run)
|
||||
@@ -135,7 +135,7 @@ func TestAnOpeningOnAMachineWithNoFirewallChangesNothing(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnUnsupportedFirewallRefusesTheWholeDeclaration(t *testing.T) {
|
||||
func testAnUnsupportedFirewallRefusesTheWholeDeclaration(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
u := &ufwMachine{ruleset: "table inet filter {\n\tchain input {\n\t\ttype filter hook input priority filter; policy drop;\n\t}\n}\n"}
|
||||
_, state, err := applyWith(t, adopted(t, `{"taken":[]}`, busOpening+","+withConf(dir)), store.State{}, u.run)
|
||||
@@ -150,7 +150,7 @@ func TestAnUnsupportedFirewallRefusesTheWholeDeclaration(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestConvergingRetiresTheFoundFirewallAndReturningRestoresIt(t *testing.T) {
|
||||
func testConvergingRetiresTheFoundFirewallAndReturningRestoresIt(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
u := &ufwMachine{installed: true, active: true, rules: []string{"allow 22/tcp"}}
|
||||
|
||||
@@ -238,7 +238,7 @@ func TestConvergingRetiresTheFoundFirewallAndReturningRestoresIt(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAConvergedNodeThatWasNeverAdoptedNeverAsksAboutAFirewall(t *testing.T) {
|
||||
func testAConvergedNodeThatWasNeverAdoptedNeverAsksAboutAFirewall(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
u := &ufwMachine{installed: true, active: true}
|
||||
if _, _, err := applyWith(t, parse(t, `{"declaration":1,"resources":[`+withConf(dir)+`]}`), store.State{}, u.run); err != nil {
|
||||
@@ -249,13 +249,13 @@ func TestAConvergedNodeThatWasNeverAdoptedNeverAsksAboutAFirewall(t *testing.T)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnOpeningOnAConvergedNodeIsRefused(t *testing.T) {
|
||||
func testAnOpeningOnAConvergedNodeIsRefused(t *testing.T) {
|
||||
if _, err := declaration.Parse([]byte(`{"declaration":1,"resources":[` + busOpening + `]}`)); err == nil {
|
||||
t.Error("an opening was accepted on a node the declaration does not say is adopted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestACarriedApplyOnAnAdoptedNodeLeavesItsFirewallInForce(t *testing.T) {
|
||||
func testACarriedApplyOnAnAdoptedNodeLeavesItsFirewallInForce(t *testing.T) {
|
||||
// The bundle, re-applied by the installer or the one-shot CLI, never says a node is adopted.
|
||||
// That is not the controller converging it, so ufw must stay enabled (novox/hq ADR 0100).
|
||||
dir := t.TempDir()
|
||||
@@ -277,7 +277,7 @@ func TestACarriedApplyOnAnAdoptedNodeLeavesItsFirewallInForce(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAFlipThatFailsKeepsTheGuardAndTheOpenings(t *testing.T) {
|
||||
func testAFlipThatFailsKeepsTheGuardAndTheOpenings(t *testing.T) {
|
||||
// Converging a node removes its openings and its guard only once everything else applied and
|
||||
// the found firewall is retired. A flip that fails part-way keeps them, so the store is never
|
||||
// left unguarded behind a filter that did not load (novox/hq ADR 0103).
|
||||
@@ -339,7 +339,7 @@ func TestAFlipThatFailsKeepsTheGuardAndTheOpenings(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnOpeningAFoundRuleAnswersIsReportedSatisfied(t *testing.T) {
|
||||
func testAnOpeningAFoundRuleAnswersIsReportedSatisfied(t *testing.T) {
|
||||
// novox/hq ADR 0103: the mesh adds nothing beside a rule ufw would take for the same one.
|
||||
dir := t.TempDir()
|
||||
u := &ufwMachine{installed: true, active: true, rules: []string{"allow 22/tcp", "allow 5671/tcp"}}
|
||||
@@ -358,7 +358,7 @@ func TestAnOpeningAFoundRuleAnswersIsReportedSatisfied(t *testing.T) {
|
||||
|
||||
// Defends novox/hq ADR 0103: returned to adopted, the guard is up before the derived filter's
|
||||
// orphans go, and stays up if removing them fails.
|
||||
func TestReturningToAdoptedLoadsTheGuardBeforeRemovingTheFilter(t *testing.T) {
|
||||
func testReturningToAdoptedLoadsTheGuardBeforeRemovingTheFilter(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
guard := filepath.Join(dir, "guard.nft")
|
||||
guardFile := `{"id":"adoption.guard","type":"file","path":"` + guard + `","content":"table inet mesh_guard {}\n"}`
|
||||
@@ -419,7 +419,7 @@ func TestReturningToAdoptedLoadsTheGuardBeforeRemovingTheFilter(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAStaleOpeningOnAnAdoptedNodeIsRemovedAsAnyOrphan(t *testing.T) {
|
||||
func testAStaleOpeningOnAnAdoptedNodeIsRemovedAsAnyOrphan(t *testing.T) {
|
||||
// Only the flip defers the adoption's own orphans; an adopted node drops a stale opening at
|
||||
// once, before what replaces it is applied.
|
||||
dir := t.TempDir()
|
||||
@@ -438,7 +438,7 @@ func TestAStaleOpeningOnAnAdoptedNodeIsRemovedAsAnyOrphan(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestARetiredFirewallRetriedStillPutsBackTheForwardPolicy(t *testing.T) {
|
||||
func testARetiredFirewallRetriedStillPutsBackTheForwardPolicy(t *testing.T) {
|
||||
// The forward policy is recorded before ufw is disabled, so a retirement that failed after
|
||||
// the disable restores what the machine had, not what the disable left (novox/hq ADR 0100).
|
||||
dir := t.TempDir()
|
||||
@@ -462,7 +462,7 @@ func TestARetiredFirewallRetriedStillPutsBackTheForwardPolicy(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAGuardThatFailsLeavesTheDerivedFilterInForce(t *testing.T) {
|
||||
func testAGuardThatFailsLeavesTheDerivedFilterInForce(t *testing.T) {
|
||||
// Returning to adopted: if the guard cannot be raised, the filter it replaces must not be
|
||||
// stopped — its stop deletes the mesh's table, and the node would have neither (novox/hq ADR 0103).
|
||||
dir := t.TempDir()
|
||||
@@ -500,7 +500,7 @@ func TestAGuardThatFailsLeavesTheDerivedFilterInForce(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestUfwIsNotRetiredUntilTheMeshsOwnFilterIsLoaded(t *testing.T) {
|
||||
func testUfwIsNotRetiredUntilTheMeshsOwnFilterIsLoaded(t *testing.T) {
|
||||
// The flip retires the found firewall because the mesh's derived filter takes its place. If
|
||||
// that table is not loaded, retiring would leave the machine filtering nothing (novox/hq ADR 0100).
|
||||
dir := t.TempDir()
|
||||
@@ -530,7 +530,7 @@ func TestUfwIsNotRetiredUntilTheMeshsOwnFilterIsLoaded(t *testing.T) {
|
||||
|
||||
// A front end that is no longer installed is recorded as removed, said once, and asked nothing of
|
||||
// (novox/hq ADR 0180).
|
||||
func TestAnUninstalledFrontEndIsRetiredForGood(t *testing.T) {
|
||||
func testAnUninstalledFrontEndIsRetiredForGood(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
u := &ufwMachine{installed: false, ruleset: "table inet mesh\n"}
|
||||
known := store.State{Firewall: &store.FoundFirewall{Kind: "ufw", WasActive: true, DisabledByMesh: true,
|
||||
@@ -557,3 +557,21 @@ func TestAnUninstalledFrontEndIsRetiredForGood(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestOpening runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestOpening(t *testing.T) {
|
||||
t.Run("AnOpeningOnAMachineWithNoFirewallChangesNothing", testAnOpeningOnAMachineWithNoFirewallChangesNothing)
|
||||
t.Run("AnUnsupportedFirewallRefusesTheWholeDeclaration", testAnUnsupportedFirewallRefusesTheWholeDeclaration)
|
||||
t.Run("ConvergingRetiresTheFoundFirewallAndReturningRestoresIt", testConvergingRetiresTheFoundFirewallAndReturningRestoresIt)
|
||||
t.Run("AConvergedNodeThatWasNeverAdoptedNeverAsksAboutAFirewall", testAConvergedNodeThatWasNeverAdoptedNeverAsksAboutAFirewall)
|
||||
t.Run("AnOpeningOnAConvergedNodeIsRefused", testAnOpeningOnAConvergedNodeIsRefused)
|
||||
t.Run("ACarriedApplyOnAnAdoptedNodeLeavesItsFirewallInForce", testACarriedApplyOnAnAdoptedNodeLeavesItsFirewallInForce)
|
||||
t.Run("AFlipThatFailsKeepsTheGuardAndTheOpenings", testAFlipThatFailsKeepsTheGuardAndTheOpenings)
|
||||
t.Run("AnOpeningAFoundRuleAnswersIsReportedSatisfied", testAnOpeningAFoundRuleAnswersIsReportedSatisfied)
|
||||
t.Run("ReturningToAdoptedLoadsTheGuardBeforeRemovingTheFilter", testReturningToAdoptedLoadsTheGuardBeforeRemovingTheFilter)
|
||||
t.Run("AStaleOpeningOnAnAdoptedNodeIsRemovedAsAnyOrphan", testAStaleOpeningOnAnAdoptedNodeIsRemovedAsAnyOrphan)
|
||||
t.Run("ARetiredFirewallRetriedStillPutsBackTheForwardPolicy", testARetiredFirewallRetriedStillPutsBackTheForwardPolicy)
|
||||
t.Run("AGuardThatFailsLeavesTheDerivedFilterInForce", testAGuardThatFailsLeavesTheDerivedFilterInForce)
|
||||
t.Run("UfwIsNotRetiredUntilTheMeshsOwnFilterIsLoaded", testUfwIsNotRetiredUntilTheMeshsOwnFilterIsLoaded)
|
||||
t.Run("AnUninstalledFrontEndIsRetiredForGood", testAnUninstalledFrontEndIsRetiredForGood)
|
||||
}
|
||||
|
||||
@@ -28,7 +28,7 @@ type ownershipCase struct {
|
||||
first, second string
|
||||
}
|
||||
|
||||
func TestEachOwnershipBehavesAsItsOldForm(t *testing.T) {
|
||||
func testEachOwnershipBehavesAsItsOldForm(t *testing.T) {
|
||||
for _, c := range []ownershipCase{
|
||||
{
|
||||
name: "owned is a whole file whose drift is written back",
|
||||
@@ -104,7 +104,7 @@ func applyThroughDrift(t *testing.T, c ownershipCase, fields string) (string, st
|
||||
|
||||
// A seed said by the word alone, with no create-once beside it, is still kept once present: the word is
|
||||
// enough, and the file the program grew is not written back.
|
||||
func TestASeedByTheWordAloneKeepsWhatGrew(t *testing.T) {
|
||||
func testASeedByTheWordAloneKeepsWhatGrew(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "acl.conf")
|
||||
d := parse(t, fmt.Sprintf(`{"declaration":1,"resources":[
|
||||
{"id":"acl","type":"file","path":%q,"content":"user default on\n","owner-at-runtime":"seed"}
|
||||
@@ -127,3 +127,9 @@ func TestASeedByTheWordAloneKeepsWhatGrew(t *testing.T) {
|
||||
t.Errorf("what grew in the seed was written over: %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestOwnership runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestOwnership(t *testing.T) {
|
||||
t.Run("EachOwnershipBehavesAsItsOldForm", testEachOwnershipBehavesAsItsOldForm)
|
||||
t.Run("ASeedByTheWordAloneKeepsWhatGrew", testASeedByTheWordAloneKeepsWhatGrew)
|
||||
}
|
||||
|
||||
@@ -30,7 +30,7 @@ func refusedFor339(t *testing.T, what string, err error) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestNoDirectoryIsPlacedAtTheMachinesOwn(t *testing.T) {
|
||||
func testNoDirectoryIsPlacedAtTheMachinesOwn(t *testing.T) {
|
||||
for _, path := range []string{"/", "/etc", "/etc/", "/usr", "/var", "/var/lib", "/home", "/run", "/boot", "/root",
|
||||
"/var/lib/mesh-host", "/var/lib/mesh-host/identity", "/proc/1/task", "/sys/kernel", "/dev/shm", "/root/.ssh",
|
||||
"/srv/../etc"} {
|
||||
@@ -46,7 +46,7 @@ func TestNoDirectoryIsPlacedAtTheMachinesOwn(t *testing.T) {
|
||||
refusedFor339(t, "a drop-in directory owned by another account", err)
|
||||
}
|
||||
|
||||
func TestNoAccessIsAtTheMachinesOwn(t *testing.T) {
|
||||
func testNoAccessIsAtTheMachinesOwn(t *testing.T) {
|
||||
for _, path := range []string{"/", "/etc", "/etc/ssl", "/usr", "/var/lib", "/home", "/root", "/proc",
|
||||
"/var/lib/mesh-host", "/run/docker"} {
|
||||
_, _, err := applyOnce(t, `{"id":"notes.media","type":"access","path":"`+path+`"}`, nil, store.State{})
|
||||
@@ -55,7 +55,7 @@ func TestNoAccessIsAtTheMachinesOwn(t *testing.T) {
|
||||
}
|
||||
|
||||
// A container is never handed the machine's own as a mount, nor a directory or access the engine refused.
|
||||
func TestNoContainerMountsTheMachinesOwn(t *testing.T) {
|
||||
func testNoContainerMountsTheMachinesOwn(t *testing.T) {
|
||||
ran := false
|
||||
run := func(ctx context.Context, name string, args ...string) (string, error) {
|
||||
args = oldShape(name, args)
|
||||
@@ -85,7 +85,7 @@ func TestNoContainerMountsTheMachinesOwn(t *testing.T) {
|
||||
|
||||
// The path is not followed: a link where a directory is declared, or a link on the way to it, is judged where
|
||||
// it leads.
|
||||
func TestALinkIsNotFollowedToTheMachinesOwn(t *testing.T) {
|
||||
func testALinkIsNotFollowedToTheMachinesOwn(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
target := filepath.Join(dir, "target")
|
||||
if err := os.Mkdir(target, 0o700); err != nil {
|
||||
@@ -113,7 +113,7 @@ func TestALinkIsNotFollowedToTheMachinesOwn(t *testing.T) {
|
||||
|
||||
// A directory found here, that the mesh did not make, keeps its owner and mode; one the mesh made keeps the
|
||||
// declared mode, as before.
|
||||
func TestAFoundDirectoryIsUsedAsFound(t *testing.T) {
|
||||
func testAFoundDirectoryIsUsedAsFound(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
found := filepath.Join(dir, "found")
|
||||
if err := os.Mkdir(found, 0o700); err != nil {
|
||||
@@ -177,7 +177,7 @@ func TestAFoundDirectoryIsUsedAsFound(t *testing.T) {
|
||||
|
||||
// The module's own directories keep being placed: below /var/lib, below /etc as root's, a container's mount of
|
||||
// the machine's docker socket.
|
||||
func TestAModulesOwnPlacesAreStillPlaced(t *testing.T) {
|
||||
func testAModulesOwnPlacesAreStillPlaced(t *testing.T) {
|
||||
// The paths below are judged as written: no link of them is followed on the machine the test runs on, whose mounts of them
|
||||
// (a share that does not answer) it does not depend on.
|
||||
was := evalSymlinks
|
||||
@@ -219,3 +219,13 @@ func TestAModulesOwnPlacesAreStillPlaced(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestPlacementGuard runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestPlacementGuard(t *testing.T) {
|
||||
t.Run("NoDirectoryIsPlacedAtTheMachinesOwn", testNoDirectoryIsPlacedAtTheMachinesOwn)
|
||||
t.Run("NoAccessIsAtTheMachinesOwn", testNoAccessIsAtTheMachinesOwn)
|
||||
t.Run("NoContainerMountsTheMachinesOwn", testNoContainerMountsTheMachinesOwn)
|
||||
t.Run("ALinkIsNotFollowedToTheMachinesOwn", testALinkIsNotFollowedToTheMachinesOwn)
|
||||
t.Run("AFoundDirectoryIsUsedAsFound", testAFoundDirectoryIsUsedAsFound)
|
||||
t.Run("AModulesOwnPlacesAreStillPlaced", testAModulesOwnPlacesAreStillPlaced)
|
||||
}
|
||||
|
||||
@@ -32,7 +32,7 @@ func verbs(steps []Step) string {
|
||||
return strings.Join(out, ", ")
|
||||
}
|
||||
|
||||
func TestAPlanNamesAnActionAsAnAction(t *testing.T) {
|
||||
func testAPlanNamesAnActionAsAnAction(t *testing.T) {
|
||||
d := trusted(t, `{"declaration":1,"resources":[
|
||||
{"id":"init","type":"action","command":["createdb","mesh"],"verify":["psql","-c","select 1"]}]}`)
|
||||
steps := Plan(d, store.State{}, store.OriginCarried)
|
||||
@@ -44,7 +44,7 @@ func TestAPlanNamesAnActionAsAnAction(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAPlanSaysWhatIsRecordedAndWhatIsNot(t *testing.T) {
|
||||
func testAPlanSaysWhatIsRecordedAndWhatIsNot(t *testing.T) {
|
||||
d := parse(t, `{"declaration":1,"resources":[
|
||||
{"id":"new","type":"file","path":"/tmp/new","content":"a\n"},
|
||||
{"id":"same","type":"file","path":"/tmp/same","content":"b\n"},
|
||||
@@ -63,7 +63,7 @@ func TestAPlanSaysWhatIsRecordedAndWhatIsNot(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAPlanSaysTheFirewallAConvergingNodeRetires(t *testing.T) {
|
||||
func testAPlanSaysTheFirewallAConvergingNodeRetires(t *testing.T) {
|
||||
d := parse(t, `{"declaration":1,"resources":[{"id":"a","type":"file","path":"/tmp/a","content":"x\n"}]}`)
|
||||
known := store.State{Firewall: &store.FoundFirewall{Kind: "ufw", WasActive: true, FoundAt: time.Now()}}
|
||||
known.Record(store.Applied{ID: "adoption.guard.table", Type: "file", Target: "/etc/guard", Origin: store.OriginDeclared})
|
||||
@@ -79,7 +79,7 @@ func TestAPlanSaysTheFirewallAConvergingNodeRetires(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAPlanHoldsWhatAnAdoptedNodeFound(t *testing.T) {
|
||||
func testAPlanHoldsWhatAnAdoptedNodeFound(t *testing.T) {
|
||||
d := parse(t, `{"declaration":1,"adoption":{"taken":[],"untaken":{"hello-web":["hello-web.page","hello-web.server"]}},
|
||||
"resources":[
|
||||
{"id":"hello-web.page","type":"file","path":"/srv/index.html","content":"x\n"},
|
||||
@@ -140,7 +140,7 @@ func write(t *testing.T, path, content string) {
|
||||
|
||||
// Defends novox/hq issue 104: the plan is the apply, said first — the same resources in the same
|
||||
// order, and the one cutover ADR 0100 says must be previewed said as a cutover, not a hold.
|
||||
func TestThePlanIsTheApplyInOrder(t *testing.T) {
|
||||
func testThePlanIsTheApplyInOrder(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
guard, page, keep, old := filepath.Join(dir, "guard.nft"), filepath.Join(dir, "index.html"),
|
||||
filepath.Join(dir, "keep.html"), filepath.Join(dir, "old.conf")
|
||||
@@ -209,7 +209,7 @@ func TestThePlanIsTheApplyInOrder(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAResourceRunInAHeldContainerIsPlannedAsItIsApplied(t *testing.T) {
|
||||
func testAResourceRunInAHeldContainerIsPlannedAsItIsApplied(t *testing.T) {
|
||||
// A run-once step sharing a container's namespace runs in it, as an action's `in` does.
|
||||
img := "example/x@sha256:0000000000000000000000000000000000000000000000000000000000000000"
|
||||
d := parse(t, `{"declaration":1,"adoption":{"taken":["web"],"untaken":{"db":["db.server"]}},"resources":[
|
||||
@@ -228,7 +228,7 @@ func TestAResourceRunInAHeldContainerIsPlannedAsItIsApplied(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAPlanSaysAContainerIsRecreatedWhenAFileItReadsChanged(t *testing.T) {
|
||||
func testAPlanSaysAContainerIsRecreatedWhenAFileItReadsChanged(t *testing.T) {
|
||||
// The apply recreates a container when the content of a file it reads at creation changed
|
||||
// (novox/hq 04-ISSUES/103); the plan says so from the record alone — what the container was
|
||||
// created reading, against what this apply will write. And a container recorded before the
|
||||
@@ -264,7 +264,7 @@ func TestAPlanSaysAContainerIsRecreatedWhenAFileItReadsChanged(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAPlanSaysWhichUnitsAnUndeclareGivesBackAndWhichItLeaves(t *testing.T) {
|
||||
func testAPlanSaysWhichUnitsAnUndeclareGivesBackAndWhichItLeaves(t *testing.T) {
|
||||
// novox/hq ADR 0118, said before it is done: "restore" only where removal may stop or disable
|
||||
// something, and a unit whose file the mesh wrote named as the mesh's.
|
||||
known := store.State{}
|
||||
@@ -302,3 +302,15 @@ func TestAPlanSaysWhichUnitsAnUndeclareGivesBackAndWhichItLeaves(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestPlan runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestPlan(t *testing.T) {
|
||||
t.Run("APlanNamesAnActionAsAnAction", testAPlanNamesAnActionAsAnAction)
|
||||
t.Run("APlanSaysWhatIsRecordedAndWhatIsNot", testAPlanSaysWhatIsRecordedAndWhatIsNot)
|
||||
t.Run("APlanSaysTheFirewallAConvergingNodeRetires", testAPlanSaysTheFirewallAConvergingNodeRetires)
|
||||
t.Run("APlanHoldsWhatAnAdoptedNodeFound", testAPlanHoldsWhatAnAdoptedNodeFound)
|
||||
t.Run("ThePlanIsTheApplyInOrder", testThePlanIsTheApplyInOrder)
|
||||
t.Run("AResourceRunInAHeldContainerIsPlannedAsItIsApplied", testAResourceRunInAHeldContainerIsPlannedAsItIsApplied)
|
||||
t.Run("APlanSaysAContainerIsRecreatedWhenAFileItReadsChanged", testAPlanSaysAContainerIsRecreatedWhenAFileItReadsChanged)
|
||||
t.Run("APlanSaysWhichUnitsAnUndeclareGivesBackAndWhichItLeaves", testAPlanSaysWhichUnitsAnUndeclareGivesBackAndWhichItLeaves)
|
||||
}
|
||||
|
||||
@@ -293,6 +293,10 @@ func withNode(r *declaration.Process, node string) *declaration.Process {
|
||||
return &p
|
||||
}
|
||||
|
||||
// drainStopMargin is the seconds a draining process's stop timeout lies above its drain bound: the time it takes to stop
|
||||
// its children after its drain (H-A-358).
|
||||
const drainStopMargin = 15
|
||||
|
||||
// unitFor is the unit the mesh writes for a daemon.
|
||||
//
|
||||
// **Generated whole and never edited in place**, the same rule as every other managed file: an
|
||||
@@ -333,7 +337,15 @@ func unitFor(r *declaration.Process) string {
|
||||
}
|
||||
// Restarted when it exits, because something that stops is not something that stays up.
|
||||
// Delayed, so a process that fails at once does not spin the machine.
|
||||
b.WriteString("Restart=always\nRestartSec=5\n\n")
|
||||
b.WriteString("Restart=always\nRestartSec=5\n")
|
||||
// **A process that drains is stopped alone** (design 47 H2 §813 (12), H-A-353, H-A-358): the stop signal reaches it
|
||||
// and not its children, so the calls in flight finish within its drain bound and it stops its children itself; the
|
||||
// service manager waits the bound and the time they take before it kills what is left, so the new process starts only
|
||||
// after the old one exits or that bound passes.
|
||||
if r.DrainBound > 0 {
|
||||
fmt.Fprintf(&b, "KillMode=mixed\nTimeoutStopSec=%ds\n", r.DrainBound+drainStopMargin)
|
||||
}
|
||||
b.WriteString("\n")
|
||||
|
||||
b.WriteString("[Install]\nWantedBy=multi-user.target\n")
|
||||
return b.String()
|
||||
|
||||
@@ -24,7 +24,7 @@ func aProcess() *declaration.Process {
|
||||
// The unit the mesh writes says what it runs, where, and that it comes back — and that it is the
|
||||
// mesh's: **generated whole and saying so**, because an edit that survives until the next declaration
|
||||
// and then vanishes is worse than one that is refused. The long-running mode stays up and is not a step.
|
||||
func TestTheUnitRunsWhatTheDaemonSaid(t *testing.T) {
|
||||
func testTheUnitRunsWhatTheDaemonSaid(t *testing.T) {
|
||||
unit := unitFor(aProcess())
|
||||
if !strings.HasPrefix(unit, "#") {
|
||||
t.Fatalf("the unit does not open saying it is generated:\n%s", unit)
|
||||
@@ -43,12 +43,19 @@ func TestTheUnitRunsWhatTheDaemonSaid(t *testing.T) {
|
||||
if strings.Contains(unit, "Type=oneshot") {
|
||||
t.Fatalf("a process that should stay up is declared a step:\n%s", unit)
|
||||
}
|
||||
}
|
||||
// Design 47 H2 §813 (12), H-A-353, H-A-358: a process that drains is stopped alone, its stop waiting its drain bound and
|
||||
// 15 s for its children; one that does not keeps the service manager's defaults.
|
||||
if strings.Contains(unit, "KillMode=") || strings.Contains(unit, "TimeoutStopSec=") {
|
||||
t.Fatalf("a process with no drain bound has its stop written:\n%s", unit)
|
||||
}
|
||||
draining := aProcess()
|
||||
draining.DrainBound = 30
|
||||
if got := unitFor(draining); !strings.Contains(got, "Restart=always\nRestartSec=5\nKillMode=mixed\nTimeoutStopSec=45s\n\n[Install]") {
|
||||
t.Fatalf("a process with a drain bound of 30 s is not stopped alone within 45 s:\n%s", got)
|
||||
}
|
||||
|
||||
// **Deterministic, because the unit is half the daemon's identity.** Environment held in a map
|
||||
// would be written in Go's iteration order, so every apply would see a different unit and call an
|
||||
// unchanged daemon changed — restarting it on every declaration for ever.
|
||||
func TestTheUnitIsTheSameEveryTime(t *testing.T) {
|
||||
// **Deterministic, because the unit is half the daemon's identity.** Environment held in a map would be written in
|
||||
// Go's iteration order, so every apply would see a different unit and call an unchanged daemon changed.
|
||||
first := unitFor(aProcess())
|
||||
for i := 0; i < 20; i++ {
|
||||
if again := unitFor(aProcess()); again != first {
|
||||
@@ -59,22 +66,18 @@ func TestTheUnitIsTheSameEveryTime(t *testing.T) {
|
||||
if strings.Index(first, "A_FIRST") > strings.Index(first, "MESH_NODE") {
|
||||
t.Fatalf("environment is not in a stable order:\n%s", first)
|
||||
}
|
||||
}
|
||||
|
||||
// **Two daemons from one bundle differing only in their command are different daemons.** Tracking
|
||||
// the digest alone would call the second one unchanged and leave the first one running.
|
||||
func TestAProcesssIdentityIncludesHowItIsRun(t *testing.T) {
|
||||
one := aProcess()
|
||||
// **Two daemons from one bundle differing only in their command are different daemons.** Tracking the digest alone
|
||||
// would call the second one unchanged and leave the first one running.
|
||||
two := aProcess()
|
||||
two.Run = []string{"node", "other.js"}
|
||||
if unitFor(one) == unitFor(two) {
|
||||
if first == unitFor(two) {
|
||||
t.Fatal("two daemons with different commands render one unit, so a change would be missed")
|
||||
}
|
||||
}
|
||||
|
||||
// A process that runs as somebody says so, and one that does not says nothing — rather than naming
|
||||
// root explicitly, which would be a claim the mesh does not need to make.
|
||||
func TestAProcessRunsAsWhoItSaid(t *testing.T) {
|
||||
func testAProcessRunsAsWhoItSaid(t *testing.T) {
|
||||
as := aProcess()
|
||||
as.User = "greeter"
|
||||
if !strings.Contains(unitFor(as), "User=greeter") {
|
||||
@@ -142,7 +145,7 @@ func TestAProcessRunsAsWhoItSaid(t *testing.T) {
|
||||
// **Three modes, one kind.** A scheduled process is a timer plus a unit that finishes, not a unit
|
||||
// that stays up — and the difference has to be in what is written, or a schedule becomes a second
|
||||
// copy running continuously between fires.
|
||||
func TestAScheduledProcessRunsOnItsCadenceRatherThanContinuously(t *testing.T) {
|
||||
func testAScheduledProcessRunsOnItsCadenceRatherThanContinuously(t *testing.T) {
|
||||
every := aProcess()
|
||||
every.Schedule = "0 3 * * *"
|
||||
|
||||
@@ -163,10 +166,7 @@ func TestAScheduledProcessRunsOnItsCadenceRatherThanContinuously(t *testing.T) {
|
||||
if !strings.Contains(timer, "Persistent=true") {
|
||||
t.Fatalf("a missed fire is skipped silently:\n%s", timer)
|
||||
}
|
||||
}
|
||||
|
||||
// Five-field cron becomes what a timer reads, rather than the host waking to decide.
|
||||
func TestACronBecomesATimersCalendar(t *testing.T) {
|
||||
// Five-field cron becomes what a timer reads, rather than the host waking to decide.
|
||||
for cron, want := range map[string]string{
|
||||
"0 3 * * *": "*-*-* 3:0:00",
|
||||
"30 4 1 * *": "*-*-1 4:30:00",
|
||||
@@ -180,7 +180,7 @@ func TestACronBecomesATimersCalendar(t *testing.T) {
|
||||
|
||||
// **A unit file reinterprets a value in three ways nothing else does**, and a module's environment
|
||||
// routinely contains all three — a generated password is arbitrary bytes.
|
||||
func TestAnEnvironmentValueMeansWhatTheDeclarationSaid(t *testing.T) {
|
||||
func testAnEnvironmentValueMeansWhatTheDeclarationSaid(t *testing.T) {
|
||||
// A percent begins a specifier: %H is the hostname. A password containing one would be
|
||||
// silently replaced, failing as an authentication error nobody can explain from the
|
||||
// declaration.
|
||||
@@ -211,7 +211,7 @@ func TestAnEnvironmentValueMeansWhatTheDeclarationSaid(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnUndeclaredProcessIsRemovedWithItsUnitAndBundle(t *testing.T) {
|
||||
func testAnUndeclaredProcessIsRemovedWithItsUnitAndBundle(t *testing.T) {
|
||||
// novox/hq ADR 0118: a process's unit and bundle are the host's own, so they go with the
|
||||
// declaration. Before, there was no way to remove a process at all, and one left undeclared
|
||||
// failed every apply on its node.
|
||||
@@ -269,7 +269,7 @@ func TestAnUndeclaredProcessIsRemovedWithItsUnitAndBundle(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAProcessRecordedUnderAPathlikeNameIsRefusedNotRemoved(t *testing.T) {
|
||||
func testAProcessRecordedUnderAPathlikeNameIsRefusedNotRemoved(t *testing.T) {
|
||||
// filepath.Join(daemonRoot, "..") is the mesh's own directory, and removal deletes what that
|
||||
// names, whole. A record is what some host wrote, perhaps under looser rules than today's, so
|
||||
// the removal holds the name to the declaration's rule again (novox/hq ADR 0118).
|
||||
@@ -304,7 +304,7 @@ func TestAProcessRecordedUnderAPathlikeNameIsRefusedNotRemoved(t *testing.T) {
|
||||
// novox/hq 04-ISSUES/210: the node's runtime was re-created — and restarted — on every reconcile,
|
||||
// because the host did not find what it wrote for a process the cycle before. Applying the same
|
||||
// process declaration twice must do no work the second time.
|
||||
func TestAProcessAppliedAgainIsUnchangedAndNotRestarted(t *testing.T) {
|
||||
func testAProcessAppliedAgainIsUnchangedAndNotRestarted(t *testing.T) {
|
||||
units, bundles := t.TempDir(), t.TempDir()
|
||||
wasUnits, wasBundles := unitDir, daemonRoot
|
||||
unitDir, daemonRoot = units, bundles
|
||||
@@ -415,7 +415,7 @@ func TestAProcessAppliedAgainIsUnchangedAndNotRestarted(t *testing.T) {
|
||||
|
||||
// novox/hq ADR 0193: a bundle compiled to a binary runs itself — `./name` is that file in the
|
||||
// process's own unpacked bundle, made absolute because the service manager takes nothing relative.
|
||||
func TestAProcessRunsItsOwnBundlesBinary(t *testing.T) {
|
||||
func testAProcessRunsItsOwnBundlesBinary(t *testing.T) {
|
||||
unit := unitFor(&declaration.Process{Name: "node-tools", Run: []string{"./node-tools", "serve"}})
|
||||
if !strings.Contains(unit, "ExecStart="+filepath.Join(daemonRoot, "node-tools", "node-tools")+" serve\n") {
|
||||
t.Errorf("the binary is not run from its bundle:\n%s", unit)
|
||||
@@ -425,3 +425,15 @@ func TestAProcessRunsItsOwnBundlesBinary(t *testing.T) {
|
||||
t.Errorf("a command found on the path was changed:\n%s", other)
|
||||
}
|
||||
}
|
||||
|
||||
// TestProcess runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestProcess(t *testing.T) {
|
||||
t.Run("TheUnitRunsWhatTheDaemonSaid", testTheUnitRunsWhatTheDaemonSaid)
|
||||
t.Run("AProcessRunsAsWhoItSaid", testAProcessRunsAsWhoItSaid)
|
||||
t.Run("AScheduledProcessRunsOnItsCadenceRatherThanContinuously", testAScheduledProcessRunsOnItsCadenceRatherThanContinuously)
|
||||
t.Run("AnEnvironmentValueMeansWhatTheDeclarationSaid", testAnEnvironmentValueMeansWhatTheDeclarationSaid)
|
||||
t.Run("AnUndeclaredProcessIsRemovedWithItsUnitAndBundle", testAnUndeclaredProcessIsRemovedWithItsUnitAndBundle)
|
||||
t.Run("AProcessRecordedUnderAPathlikeNameIsRefusedNotRemoved", testAProcessRecordedUnderAPathlikeNameIsRefusedNotRemoved)
|
||||
t.Run("AProcessAppliedAgainIsUnchangedAndNotRestarted", testAProcessAppliedAgainIsUnchangedAndNotRestarted)
|
||||
t.Run("AProcessRunsItsOwnBundlesBinary", testAProcessRunsItsOwnBundlesBinary)
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ import (
|
||||
// A core process keeps the build before it while the new one is judged (novox/hq to-be 45 §8): the
|
||||
// applier places the new build where the unit runs it from, and moves the old one aside rather than
|
||||
// deleting it. A process nobody judges is replaced as ever.
|
||||
func TestACoreProcessKeepsTheBuildBeforeItWhileTheNewOneIsJudged(t *testing.T) {
|
||||
func testACoreProcessKeepsTheBuildBeforeItWhileTheNewOneIsJudged(t *testing.T) {
|
||||
units, bundles := t.TempDir(), t.TempDir()
|
||||
wasUnits, wasBundles := unitDir, daemonRoot
|
||||
unitDir, daemonRoot = units, bundles
|
||||
@@ -65,7 +65,7 @@ func TestACoreProcessKeepsTheBuildBeforeItWhileTheNewOneIsJudged(t *testing.T) {
|
||||
|
||||
// A build rolled back on this machine is not placed again while the mesh still declares it; the
|
||||
// restored build keeps running, and the apply says why.
|
||||
func TestARolledBackBuildIsNotPlacedAgain(t *testing.T) {
|
||||
func testARolledBackBuildIsNotPlacedAgain(t *testing.T) {
|
||||
units, bundles := t.TempDir(), t.TempDir()
|
||||
wasUnits, wasBundles := unitDir, daemonRoot
|
||||
unitDir, daemonRoot = units, bundles
|
||||
@@ -112,7 +112,7 @@ func TestARolledBackBuildIsNotPlacedAgain(t *testing.T) {
|
||||
// process started in it failed with "getwd: no such file or directory". Here a process works in the
|
||||
// build's directory without running from it, as that `go version` did: the apply of a new build leaves
|
||||
// its directory in place, and the retired build goes once nothing works in it.
|
||||
func TestAProcessNobodyJudgesKeepsItsDirectoryUntilItsRestart(t *testing.T) {
|
||||
func testAProcessNobodyJudgesKeepsItsDirectoryUntilItsRestart(t *testing.T) {
|
||||
if _, err := os.Stat("/proc/self/cwd"); err != nil {
|
||||
t.Skip("which process works in a build is read from /proc")
|
||||
}
|
||||
@@ -181,3 +181,10 @@ func TestAProcessNobodyJudgesKeepsItsDirectoryUntilItsRestart(t *testing.T) {
|
||||
t.Fatalf("a retired build nothing works in was kept: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestProcessWitness runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestProcessWitness(t *testing.T) {
|
||||
t.Run("ACoreProcessKeepsTheBuildBeforeItWhileTheNewOneIsJudged", testACoreProcessKeepsTheBuildBeforeItWhileTheNewOneIsJudged)
|
||||
t.Run("ARolledBackBuildIsNotPlacedAgain", testARolledBackBuildIsNotPlacedAgain)
|
||||
t.Run("AProcessNobodyJudgesKeepsItsDirectoryUntilItsRestart", testAProcessNobodyJudgesKeepsItsDirectoryUntilItsRestart)
|
||||
}
|
||||
|
||||
@@ -30,7 +30,7 @@ func applyCarried(t *testing.T, d *declaration.Declaration, known store.State, m
|
||||
return report, state
|
||||
}
|
||||
|
||||
func TestAContainerIsRecreatedWhenItsEnvFileChanged(t *testing.T) {
|
||||
func testAContainerIsRecreatedWhenItsEnvFileChanged(t *testing.T) {
|
||||
// The night of the issue: the store was given a new port, the host rewrote the forge's
|
||||
// environment file with it — and left the forge running with the old one.
|
||||
dir := t.TempDir()
|
||||
@@ -79,7 +79,7 @@ func TestAContainerIsRecreatedWhenItsEnvFileChanged(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnEnvFileTheHostDidNotWriteIsStillReadForWhatItHolds(t *testing.T) {
|
||||
func testAnEnvFileTheHostDidNotWriteIsStillReadForWhatItHolds(t *testing.T) {
|
||||
// The host has no record of this file — a predecessor left it, or something else on the
|
||||
// machine maintains it — and the container still reads it once. Its content is read from the
|
||||
// disk, so a change is a recreate exactly as for a file the host wrote.
|
||||
@@ -107,7 +107,7 @@ func TestAnEnvFileTheHostDidNotWriteIsStillReadForWhatItHolds(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAContainerIsRecreatedWhenAMountedSecretChanged(t *testing.T) {
|
||||
func testAContainerIsRecreatedWhenAMountedSecretChanged(t *testing.T) {
|
||||
// A rotated credential has the same shape as a moved port: the host writes the file the
|
||||
// container mounts, and the process holds the value it was created with.
|
||||
dir := t.TempDir()
|
||||
@@ -132,7 +132,7 @@ func TestAContainerIsRecreatedWhenAMountedSecretChanged(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAMountedDirectoryIsNotLookedInside(t *testing.T) {
|
||||
func testAMountedDirectoryIsNotLookedInside(t *testing.T) {
|
||||
// A bind-mounted directory is not part of what a container is — not the data the service
|
||||
// grows in it, and not the files the host itself writes there either. Whether a service reads
|
||||
// a file under its directory once at start or watches it live is the service's business: the
|
||||
@@ -193,7 +193,7 @@ func TestAMountedDirectoryIsNotLookedInside(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAContainerLabelledBeforeTheHostReadItsFilesIsAcceptedNotRecreated(t *testing.T) {
|
||||
func testAContainerLabelledBeforeTheHostReadItsFilesIsAcceptedNotRecreated(t *testing.T) {
|
||||
// The first apply after the host upgrades finds every container carrying a label computed
|
||||
// without the file lines. Recreating them all would be a restart storm across the mesh in
|
||||
// declaration order, the store first. A label that matches the spec as it used to be computed
|
||||
@@ -247,7 +247,7 @@ func TestAContainerLabelledBeforeTheHostReadItsFilesIsAcceptedNotRecreated(t *te
|
||||
}
|
||||
}
|
||||
|
||||
func TestAContainerAdoptedUnderANewIdStillSaysWhichFileChanged(t *testing.T) {
|
||||
func testAContainerAdoptedUnderANewIdStillSaysWhichFileChanged(t *testing.T) {
|
||||
// The bundle's `store` becomes the postgres module's `postgres.server`: the same container by
|
||||
// name, under a new id with no record of its own. A file change on that day is a real change,
|
||||
// and the record of what it read is under the old id — by name, it is found.
|
||||
@@ -274,7 +274,7 @@ func TestAContainerAdoptedUnderANewIdStillSaysWhichFileChanged(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAHeldContainerIsNotRecreatedByAChangedHeldFile(t *testing.T) {
|
||||
func testAHeldContainerIsNotRecreatedByAChangedHeldFile(t *testing.T) {
|
||||
// On an adopted node the predecessor's container and the file it reads are both held as
|
||||
// found (novox/hq ADR 0100). The predecessor rewriting its own file is reported on the file
|
||||
// — and is nothing to recreate the container for: it is not the host's to recreate.
|
||||
@@ -314,3 +314,14 @@ func TestAHeldContainerIsNotRecreatedByAChangedHeldFile(t *testing.T) {
|
||||
t.Errorf("a file change was charged to the container: %+v", h)
|
||||
}
|
||||
}
|
||||
|
||||
// TestReads runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestReads(t *testing.T) {
|
||||
t.Run("AContainerIsRecreatedWhenItsEnvFileChanged", testAContainerIsRecreatedWhenItsEnvFileChanged)
|
||||
t.Run("AnEnvFileTheHostDidNotWriteIsStillReadForWhatItHolds", testAnEnvFileTheHostDidNotWriteIsStillReadForWhatItHolds)
|
||||
t.Run("AContainerIsRecreatedWhenAMountedSecretChanged", testAContainerIsRecreatedWhenAMountedSecretChanged)
|
||||
t.Run("AMountedDirectoryIsNotLookedInside", testAMountedDirectoryIsNotLookedInside)
|
||||
t.Run("AContainerLabelledBeforeTheHostReadItsFilesIsAcceptedNotRecreated", testAContainerLabelledBeforeTheHostReadItsFilesIsAcceptedNotRecreated)
|
||||
t.Run("AContainerAdoptedUnderANewIdStillSaysWhichFileChanged", testAContainerAdoptedUnderANewIdStillSaysWhichFileChanged)
|
||||
t.Run("AHeldContainerIsNotRecreatedByAChangedHeldFile", testAHeldContainerIsNotRecreatedByAChangedHeldFile)
|
||||
}
|
||||
|
||||
@@ -35,7 +35,7 @@ func objectOf(body []byte) string {
|
||||
}
|
||||
|
||||
// 1695/AC1: both forms apply: a file by reference becomes the inline file, an inline one is left as it is.
|
||||
func TestAFileByReferenceBecomesTheInlineFile(t *testing.T) {
|
||||
func testAFileByReferenceBecomesTheInlineFile(t *testing.T) {
|
||||
body := []byte(strings.Repeat("a line\n", 20000))
|
||||
inline := &declaration.File{ID: "m.small", Type: declaration.TypeFile, Path: "/etc/small", Content: "x"}
|
||||
d := &declaration.Declaration{Resources: []declaration.Resource{inline, referenceTo(t, "/nowhere/big", body)}}
|
||||
@@ -53,7 +53,7 @@ func TestAFileByReferenceBecomesTheInlineFile(t *testing.T) {
|
||||
}
|
||||
|
||||
// 1695/AC2: an object that differs by one byte, or in size, fails the whole resolve and gives no content.
|
||||
func TestAnObjectThatDiffersFailsTheApply(t *testing.T) {
|
||||
func testAnObjectThatDiffersFailsTheApply(t *testing.T) {
|
||||
body := []byte(strings.Repeat("x", 70000))
|
||||
bad := append([]byte(nil), body...)
|
||||
bad[3] ^= 1
|
||||
@@ -71,7 +71,7 @@ func TestAnObjectThatDiffersFailsTheApply(t *testing.T) {
|
||||
}
|
||||
|
||||
// 1695/AC3: a missing object, or a node with no bus, fails the apply naming the file.
|
||||
func TestAMissingObjectFailsTheApply(t *testing.T) {
|
||||
func testAMissingObjectFailsTheApply(t *testing.T) {
|
||||
body := []byte(strings.Repeat("y", 70000))
|
||||
d := &declaration.Declaration{Resources: []declaration.Resource{referenceTo(t, "/nowhere/big", body)}}
|
||||
var asked []string
|
||||
@@ -85,7 +85,7 @@ func TestAMissingObjectFailsTheApply(t *testing.T) {
|
||||
}
|
||||
|
||||
// 1695/AC4: a file already on the machine that verifies is used and nothing is fetched; one that does not is fetched.
|
||||
func TestAVerifiedFileOnTheMachineFetchesNothing(t *testing.T) {
|
||||
func testAVerifiedFileOnTheMachineFetchesNothing(t *testing.T) {
|
||||
body := []byte(strings.Repeat("z", 70000))
|
||||
path := filepath.Join(t.TempDir(), "big")
|
||||
if err := os.WriteFile(path, body, 0o644); err != nil {
|
||||
@@ -106,7 +106,7 @@ func TestAVerifiedFileOnTheMachineFetchesNothing(t *testing.T) {
|
||||
}
|
||||
|
||||
// 1695/AC5: binary content comes back as bytes, and two files naming one digest fetch it once.
|
||||
func TestBinaryContentAndOneFetchPerDigest(t *testing.T) {
|
||||
func testBinaryContentAndOneFetchPerDigest(t *testing.T) {
|
||||
body := append([]byte{0xff, 0xfe, 0x00}, []byte(strings.Repeat("b", 70000))...)
|
||||
d := &declaration.Declaration{Resources: []declaration.Resource{referenceTo(t, "/n/a", body), referenceTo(t, "/n/b", body)}}
|
||||
var asked []string
|
||||
@@ -120,7 +120,7 @@ func TestBinaryContentAndOneFetchPerDigest(t *testing.T) {
|
||||
}
|
||||
|
||||
// 1695/AC9: an unresolved reference reaching the apply is refused, never written as an empty file.
|
||||
func TestAnUnresolvedReferenceIsNeverWrittenEmpty(t *testing.T) {
|
||||
func testAnUnresolvedReferenceIsNeverWrittenEmpty(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "big")
|
||||
f := referenceTo(t, path, []byte(strings.Repeat("q", 70000)))
|
||||
if _, err := applyFile(f, store.Applied{}, nil, nil); err == nil || !strings.Contains(err.Error(), "not written empty") {
|
||||
@@ -130,3 +130,13 @@ func TestAnUnresolvedReferenceIsNeverWrittenEmpty(t *testing.T) {
|
||||
t.Error("1695/AC9: a file was written")
|
||||
}
|
||||
}
|
||||
|
||||
// TestReferences runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestReferences(t *testing.T) {
|
||||
t.Run("AFileByReferenceBecomesTheInlineFile", testAFileByReferenceBecomesTheInlineFile)
|
||||
t.Run("AnObjectThatDiffersFailsTheApply", testAnObjectThatDiffersFailsTheApply)
|
||||
t.Run("AMissingObjectFailsTheApply", testAMissingObjectFailsTheApply)
|
||||
t.Run("AVerifiedFileOnTheMachineFetchesNothing", testAVerifiedFileOnTheMachineFetchesNothing)
|
||||
t.Run("BinaryContentAndOneFetchPerDigest", testBinaryContentAndOneFetchPerDigest)
|
||||
t.Run("AnUnresolvedReferenceIsNeverWrittenEmpty", testAnUnresolvedReferenceIsNeverWrittenEmpty)
|
||||
}
|
||||
|
||||
@@ -45,7 +45,7 @@ func aRuntimeRoot(t *testing.T) string {
|
||||
return root
|
||||
}
|
||||
|
||||
func TestARefusedDirectoryGatesItsModule(t *testing.T) {
|
||||
func testARefusedDirectoryGatesItsModule(t *testing.T) {
|
||||
root := aRuntimeRoot(t)
|
||||
b := newStepBed(t)
|
||||
elsewhere := filepath.Join(b.dir, "other.conf")
|
||||
@@ -86,7 +86,7 @@ func TestARefusedDirectoryGatesItsModule(t *testing.T) {
|
||||
|
||||
// A file is judged as a directory is: refused in a tree nothing is placed in, and below a directory the
|
||||
// engine refused, whichever module declares it and in whatever order.
|
||||
func TestAFileIsJudgedByTheSameGuardAsADirectory(t *testing.T) {
|
||||
func testAFileIsJudgedByTheSameGuardAsADirectory(t *testing.T) {
|
||||
root := aRuntimeRoot(t)
|
||||
_, _, err := applyOnce(t, `{"id":"notes.conf","type":"file","path":"`+root+`/notes.conf","content":"x\n"}`,
|
||||
nil, store.State{})
|
||||
@@ -130,7 +130,7 @@ func TestAFileIsJudgedByTheSameGuardAsADirectory(t *testing.T) {
|
||||
}
|
||||
|
||||
// An archive below a refused path is refused with it, whichever module declares it and in whatever order.
|
||||
func TestAnArchiveBelowARefusedPathIsRefused(t *testing.T) {
|
||||
func testAnArchiveBelowARefusedPathIsRefused(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
home := filepath.Join(dir, "home", "alice")
|
||||
if err := os.MkdirAll(home, 0o755); err != nil {
|
||||
@@ -163,7 +163,7 @@ func TestAnArchiveBelowARefusedPathIsRefused(t *testing.T) {
|
||||
|
||||
// Gated is per apply: a module gated behind its refused directory is tried again by the next apply, gated
|
||||
// again while the directory is refused, and applied whole once it is not.
|
||||
func TestAGatedModuleIsTriedAgainByTheNextApply(t *testing.T) {
|
||||
func testAGatedModuleIsTriedAgainByTheNextApply(t *testing.T) {
|
||||
root := aRuntimeRoot(t)
|
||||
b := newStepBed(t)
|
||||
declared := func() string {
|
||||
@@ -199,7 +199,7 @@ func TestAGatedModuleIsTriedAgainByTheNextApply(t *testing.T) {
|
||||
|
||||
// A module gated behind its refused directory, then a step of no module that stops the machine: the report
|
||||
// names both, and says nothing after the step was attempted (novox/hq issue 495).
|
||||
func TestAMachineStopAfterAGatedModuleSaysBoth(t *testing.T) {
|
||||
func testAMachineStopAfterAGatedModuleSaysBoth(t *testing.T) {
|
||||
root := aRuntimeRoot(t)
|
||||
after := filepath.Join(t.TempDir(), "after.conf")
|
||||
_, _, err := Apply(context.Background(), archHost(t), parseTrusted(t, `{"declaration":1,"resources":[
|
||||
@@ -220,3 +220,12 @@ func TestAMachineStopAfterAGatedModuleSaysBoth(t *testing.T) {
|
||||
t.Errorf("the report does not say both what was gated and that the machine stopped: %s", msg)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRefusedDirectory runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestRefusedDirectory(t *testing.T) {
|
||||
t.Run("ARefusedDirectoryGatesItsModule", testARefusedDirectoryGatesItsModule)
|
||||
t.Run("AFileIsJudgedByTheSameGuardAsADirectory", testAFileIsJudgedByTheSameGuardAsADirectory)
|
||||
t.Run("AnArchiveBelowARefusedPathIsRefused", testAnArchiveBelowARefusedPathIsRefused)
|
||||
t.Run("AGatedModuleIsTriedAgainByTheNextApply", testAGatedModuleIsTriedAgainByTheNextApply)
|
||||
t.Run("AMachineStopAfterAGatedModuleSaysBoth", testAMachineStopAfterAGatedModuleSaysBoth)
|
||||
}
|
||||
|
||||
@@ -16,7 +16,7 @@ import (
|
||||
// its config directory and file, finds the configuration gone when it is stopped on unassignment and
|
||||
// only then removes its export file; on a restart or a push the configuration is still there and it
|
||||
// leaves the exports alone.
|
||||
func TestAnUnassignedModulesProcessIsStoppedAfterTheConfigurationItReads(t *testing.T) {
|
||||
func testAnUnassignedModulesProcessIsStoppedAfterTheConfigurationItReads(t *testing.T) {
|
||||
units, bundles := t.TempDir(), t.TempDir()
|
||||
wasUnits, wasBundles := unitDir, daemonRoot
|
||||
unitDir, daemonRoot = units, bundles
|
||||
@@ -82,7 +82,7 @@ func TestAnUnassignedModulesProcessIsStoppedAfterTheConfigurationItReads(t *test
|
||||
// one added in a later version of the module, or one whose first apply failed — is appended, so it
|
||||
// is removed first. A module that relies on the order declares the process from its first version and
|
||||
// keeps it applying; the test shows the flip so nobody reads the contract as stronger than it is.
|
||||
func TestAProcessRecordedAfterItsConfigurationIsStoppedFirst(t *testing.T) {
|
||||
func testAProcessRecordedAfterItsConfigurationIsStoppedFirst(t *testing.T) {
|
||||
units, bundles := t.TempDir(), t.TempDir()
|
||||
wasUnits, wasBundles := unitDir, daemonRoot
|
||||
unitDir, daemonRoot = units, bundles
|
||||
@@ -118,3 +118,9 @@ func TestAProcessRecordedAfterItsConfigurationIsStoppedFirst(t *testing.T) {
|
||||
t.Errorf("a process recorded after its configuration was not stopped first (seen at each stop: %v)", configAtStop)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRemovalOrder runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestRemovalOrder(t *testing.T) {
|
||||
t.Run("AnUnassignedModulesProcessIsStoppedAfterTheConfigurationItReads", testAnUnassignedModulesProcessIsStoppedAfterTheConfigurationItReads)
|
||||
t.Run("AProcessRecordedAfterItsConfigurationIsStoppedFirst", testAProcessRecordedAfterItsConfigurationIsStoppedFirst)
|
||||
}
|
||||
|
||||
@@ -14,7 +14,7 @@ import (
|
||||
|
||||
// Issue 1742: the engine removed a running container and only then found the replacement image
|
||||
// unobtainable, leaving the service down. The replacement image comes first.
|
||||
func TestARunningContainerIsKeptWhenItsReplacementImageCannotBeObtained(t *testing.T) {
|
||||
func testARunningContainerIsKeptWhenItsReplacementImageCannotBeObtained(t *testing.T) {
|
||||
d := parseTrusted(t, `{"declaration":1,"resources":[
|
||||
{"id":"store","type":"container","name":"store","image":"`+pinned+`","env":{"PGDATA":"/data"}}
|
||||
]}`)
|
||||
@@ -207,7 +207,7 @@ func TestARunningContainerIsKeptWhenItsReplacementImageCannotBeObtained(t *testi
|
||||
}
|
||||
}
|
||||
|
||||
func TestAReplacementImageIsPresentBeforeTheRunningContainerIsRemoved(t *testing.T) {
|
||||
func testAReplacementImageIsPresentBeforeTheRunningContainerIsRemoved(t *testing.T) {
|
||||
d := parseTrusted(t, `{"declaration":1,"resources":[
|
||||
{"id":"store","type":"container","name":"store","image":"`+pinned+`","env":{"PGDATA":"/data"}}
|
||||
]}`)
|
||||
@@ -294,7 +294,7 @@ func asideRun(t *testing.T, want string, failRun bool, order *[]string) Runner {
|
||||
// removed before the new one runs, and started again under its name when the new one fails, the apply failing loudly.
|
||||
// Removed first, the bus's own container left novox without a bus when its replacement was never made (issue 1945,
|
||||
// live on 2026-10-25 at 11:23).
|
||||
func TestAContainerWhoseReplacementFailsIsPutBack(t *testing.T) {
|
||||
func testAContainerWhoseReplacementFailsIsPutBack(t *testing.T) {
|
||||
d := parseTrusted(t, `{"declaration":1,"resources":[
|
||||
{"id":"store","type":"container","name":"store","image":"`+pinned+`","env":{"PGDATA":"/data"}}
|
||||
]}`)
|
||||
@@ -315,7 +315,7 @@ func TestAContainerWhoseReplacementFailsIsPutBack(t *testing.T) {
|
||||
}
|
||||
|
||||
// A replacement that runs removes the container set aside, and only after it runs.
|
||||
func TestAReplacementThatRunsRemovesTheContainerSetAside(t *testing.T) {
|
||||
func testAReplacementThatRunsRemovesTheContainerSetAside(t *testing.T) {
|
||||
d := parseTrusted(t, `{"declaration":1,"resources":[
|
||||
{"id":"store","type":"container","name":"store","image":"`+pinned+`","env":{"PGDATA":"/data"}}
|
||||
]}`)
|
||||
@@ -334,7 +334,7 @@ func TestAReplacementThatRunsRemovesTheContainerSetAside(t *testing.T) {
|
||||
// A container left set aside by an engine that stopped between setting it aside and running its replacement is the
|
||||
// set-aside one of the next apply: put back when the replacement fails, removed once it runs (the review of issue
|
||||
// 1945).
|
||||
func TestAContainerLeftAsideIsPutBackOrRemovedByTheNextApply(t *testing.T) {
|
||||
func testAContainerLeftAsideIsPutBackOrRemovedByTheNextApply(t *testing.T) {
|
||||
d := parseTrusted(t, `{"declaration":1,"resources":[
|
||||
{"id":"store","type":"container","name":"store","image":"`+pinned+`","env":{"PGDATA":"/data"}}
|
||||
]}`)
|
||||
@@ -385,3 +385,12 @@ func TestAContainerLeftAsideIsPutBackOrRemovedByTheNextApply(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestReplaceImage runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestReplaceImage(t *testing.T) {
|
||||
t.Run("ARunningContainerIsKeptWhenItsReplacementImageCannotBeObtained", testARunningContainerIsKeptWhenItsReplacementImageCannotBeObtained)
|
||||
t.Run("AReplacementImageIsPresentBeforeTheRunningContainerIsRemoved", testAReplacementImageIsPresentBeforeTheRunningContainerIsRemoved)
|
||||
t.Run("AContainerWhoseReplacementFailsIsPutBack", testAContainerWhoseReplacementFailsIsPutBack)
|
||||
t.Run("AReplacementThatRunsRemovesTheContainerSetAside", testAReplacementThatRunsRemovesTheContainerSetAside)
|
||||
t.Run("AContainerLeftAsideIsPutBackOrRemovedByTheNextApply", testAContainerLeftAsideIsPutBackOrRemovedByTheNextApply)
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ import (
|
||||
// configuration, the daemon could not read the zones file the same apply had not written yet, and
|
||||
// the apply failed on every machine (novox/hq issue 260). A service is restarted only once every
|
||||
// resource it names under restart-on has been applied.
|
||||
func TestAServiceIsRestartedOnlyOnceEveryFileItNamesIsWritten(t *testing.T) {
|
||||
func testAServiceIsRestartedOnlyOnceEveryFileItNamesIsWritten(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
conf := filepath.Join(dir, "resolver.conf")
|
||||
zones := filepath.Join(dir, "zones.conf")
|
||||
@@ -89,7 +89,7 @@ func TestAServiceIsRestartedOnlyOnceEveryFileItNamesIsWritten(t *testing.T) {
|
||||
// Only a service moves, and only to just after the last resource it names — under restart-on or
|
||||
// reload-on, in its own module or another's. Everything else keeps its declared place, and a name
|
||||
// not in the declaration is no reason to move.
|
||||
func TestAServiceIsOrderedAfterWhatItNamesAndNothingElseMoves(t *testing.T) {
|
||||
func testAServiceIsOrderedAfterWhatItNamesAndNothingElseMoves(t *testing.T) {
|
||||
d := parse(t, `{"declaration":1,"resources":[
|
||||
{"id":"a.dir","type":"directory","path":"/tmp/a"},
|
||||
{"id":"a.runtime","type":"service","unit":"docker.service","state":"running","reload-on":["b.daemon"]},
|
||||
@@ -108,3 +108,9 @@ func TestAServiceIsOrderedAfterWhatItNamesAndNothingElseMoves(t *testing.T) {
|
||||
t.Errorf("ordered\n %s\nwant\n %s", strings.Join(got, " "), want)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRestartOrder runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestRestartOrder(t *testing.T) {
|
||||
t.Run("AServiceIsRestartedOnlyOnceEveryFileItNamesIsWritten", testAServiceIsRestartedOnlyOnceEveryFileItNamesIsWritten)
|
||||
t.Run("AServiceIsOrderedAfterWhatItNamesAndNothingElseMoves", testAServiceIsOrderedAfterWhatItNamesAndNothingElseMoves)
|
||||
}
|
||||
|
||||
@@ -26,7 +26,7 @@ func nameOf(args []string) string {
|
||||
return ""
|
||||
}
|
||||
|
||||
func TestARunOnceStepIsRunToCompletionNotLeftRunning(t *testing.T) {
|
||||
func testARunOnceStepIsRunToCompletionNotLeftRunning(t *testing.T) {
|
||||
// The difference between a step and a service is that a step is run in the foreground and its
|
||||
// exit code is the answer. So the host must not pass --detach (which returns before the
|
||||
// container exits) nor --restart (a step that is restarted is not a step).
|
||||
@@ -75,7 +75,7 @@ func TestARunOnceStepIsRunToCompletionNotLeftRunning(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestARunOnceStepThatExitsNonZeroFailsTheApply(t *testing.T) {
|
||||
func testARunOnceStepThatExitsNonZeroFailsTheApply(t *testing.T) {
|
||||
// Run in the foreground, a non-zero exit is an error the runtime hands back. That must fail
|
||||
// the apply, not be swallowed — a seed that did not happen leaves the machine unready.
|
||||
run := func(ctx context.Context, name string, args ...string) (string, error) {
|
||||
@@ -106,7 +106,7 @@ func TestARunOnceStepThatExitsNonZeroFailsTheApply(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAFailedRunOnceStepGatesWhatFollows(t *testing.T) {
|
||||
func testAFailedRunOnceStepGatesWhatFollows(t *testing.T) {
|
||||
// The whole of how "before the broker starts" is enforced: the step is declared first, and a
|
||||
// step that did not complete stops the apply reaching the container that depends on it — the
|
||||
// mirror of a failed action stopping what follows.
|
||||
@@ -152,7 +152,7 @@ func TestAFailedRunOnceStepGatesWhatFollows(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestARunOnceStepAlreadyCompletedIsNotReRun(t *testing.T) {
|
||||
func testARunOnceStepAlreadyCompletedIsNotReRun(t *testing.T) {
|
||||
// Its record of having happened is the digest of its declaration. A re-apply that finds the
|
||||
// digest already recorded does nothing — a step is not reconciled toward, it is run once.
|
||||
d := parseTrusted(t, `{"declaration":1,"resources":[
|
||||
@@ -189,7 +189,7 @@ func TestARunOnceStepAlreadyCompletedIsNotReRun(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestARunOnceStepReRunsWhenItsDeclarationChanged(t *testing.T) {
|
||||
func testARunOnceStepReRunsWhenItsDeclarationChanged(t *testing.T) {
|
||||
// The marker is the declaration's digest, so a changed image or environment moves it and the
|
||||
// step runs again — a migration or a seed that changed is a different step.
|
||||
d := parseTrusted(t, `{"declaration":1,"resources":[
|
||||
@@ -222,7 +222,7 @@ func TestARunOnceStepReRunsWhenItsDeclarationChanged(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestARunOnceStepRunsAgainWhenWhatItReadsChanged(t *testing.T) {
|
||||
func testARunOnceStepRunsAgainWhenWhatItReadsChanged(t *testing.T) {
|
||||
// A step that fetches a fact from a provider names the binding file it reads. What a
|
||||
// container reads is part of its digest, so when the provider moved and the mesh rewrote the
|
||||
// file, the step's marker no longer matches and it runs again (novox/hq ADR 0099) — the same
|
||||
@@ -277,7 +277,7 @@ func TestARunOnceStepRunsAgainWhenWhatItReadsChanged(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAContainerNamingARunOnceStepIsRecreatedWhenItRan(t *testing.T) {
|
||||
func testAContainerNamingARunOnceStepIsRecreatedWhenItRan(t *testing.T) {
|
||||
// The service that consumes what a step made names the step: when the step ran this pass —
|
||||
// fetched a new root — the running container holds the old one, and its spec did not move,
|
||||
// so restart-on is what brings it back with the new one (novox/hq ADR 0099).
|
||||
@@ -324,7 +324,7 @@ func TestAContainerNamingARunOnceStepIsRecreatedWhenItRan(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAFailedStepGatesItsModuleAndNotTheMachine(t *testing.T) {
|
||||
func testAFailedStepGatesItsModuleAndNotTheMachine(t *testing.T) {
|
||||
// **The blast radius of a step is its module** (novox/hq ADR 0136). A step exists to make
|
||||
// something true before the next thing in its own module needs it — a store seeded before the
|
||||
// broker starts, a schema prepared before the version that needs it runs. Stopping the whole
|
||||
@@ -383,7 +383,7 @@ func TestAFailedStepGatesItsModuleAndNotTheMachine(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAResourcesOwnerIsReadToTheLastDot(t *testing.T) {
|
||||
func testAResourcesOwnerIsReadToTheLastDot(t *testing.T) {
|
||||
// **A module's name may contain a dot.** `novox.be` is one on this mesh, so reading a resource's
|
||||
// owner to the first dot would make its resources belong to something called "novox" — and a gate
|
||||
// would skip whatever else happened to start that way. A resource's own id never contains one,
|
||||
@@ -406,3 +406,16 @@ func TestAResourcesOwnerIsReadToTheLastDot(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestRunonce runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestRunonce(t *testing.T) {
|
||||
t.Run("ARunOnceStepIsRunToCompletionNotLeftRunning", testARunOnceStepIsRunToCompletionNotLeftRunning)
|
||||
t.Run("ARunOnceStepThatExitsNonZeroFailsTheApply", testARunOnceStepThatExitsNonZeroFailsTheApply)
|
||||
t.Run("AFailedRunOnceStepGatesWhatFollows", testAFailedRunOnceStepGatesWhatFollows)
|
||||
t.Run("ARunOnceStepAlreadyCompletedIsNotReRun", testARunOnceStepAlreadyCompletedIsNotReRun)
|
||||
t.Run("ARunOnceStepReRunsWhenItsDeclarationChanged", testARunOnceStepReRunsWhenItsDeclarationChanged)
|
||||
t.Run("ARunOnceStepRunsAgainWhenWhatItReadsChanged", testARunOnceStepRunsAgainWhenWhatItReadsChanged)
|
||||
t.Run("AContainerNamingARunOnceStepIsRecreatedWhenItRan", testAContainerNamingARunOnceStepIsRecreatedWhenItRan)
|
||||
t.Run("AFailedStepGatesItsModuleAndNotTheMachine", testAFailedStepGatesItsModuleAndNotTheMachine)
|
||||
t.Run("AResourcesOwnerIsReadToTheLastDot", testAResourcesOwnerIsReadToTheLastDot)
|
||||
}
|
||||
|
||||
@@ -85,7 +85,7 @@ func scheduledContainer(t *testing.T, schedule string) *declaration.Container {
|
||||
|
||||
// --- Requirement 4: installing a schedule does not run it, and the node is current at once. ---
|
||||
|
||||
func TestInstallingAScheduleDoesNotRunItAndReportsCurrent(t *testing.T) {
|
||||
func testInstallingAScheduleDoesNotRunItAndReportsCurrent(t *testing.T) {
|
||||
// The deliberate inversion of run-once: the schedule is state that is present, so the apply is
|
||||
// current as soon as it is recorded. Installing it ensures the pinned image is present (a
|
||||
// scheduled step is never run at apply, so nothing else pulls it), but it NEVER runs the
|
||||
@@ -147,7 +147,7 @@ func TestInstallingAScheduleDoesNotRunItAndReportsCurrent(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestInstallingAScheduleEnsuresItsImageIsPresentWithoutStartingIt(t *testing.T) {
|
||||
func testInstallingAScheduleEnsuresItsImageIsPresentWithoutStartingIt(t *testing.T) {
|
||||
// A scheduled step is never run at apply, so `docker run` — which is what pulls a service's or a
|
||||
// run-once step's image — never fetches it. Without an explicit pull the image is absent from the
|
||||
// node until the first scheduled fire, which then pays the whole pull latency and, until it runs,
|
||||
@@ -198,7 +198,7 @@ func TestInstallingAScheduleEnsuresItsImageIsPresentWithoutStartingIt(t *testing
|
||||
}
|
||||
}
|
||||
|
||||
func TestAScheduledStepDoesNotGateWhatFollows(t *testing.T) {
|
||||
func testAScheduledStepDoesNotGateWhatFollows(t *testing.T) {
|
||||
// A run-once step gates: a failure halts what follows. A scheduled step is downstream of
|
||||
// convergence, so it never gates — a container declared after it is applied normally.
|
||||
d := parseTrusted(t, `{"declaration":1,"resources":[
|
||||
@@ -241,7 +241,7 @@ func TestAScheduledStepDoesNotGateWhatFollows(t *testing.T) {
|
||||
|
||||
// --- Requirement 5: the host fires the container when the cron is due, and not before. ---
|
||||
|
||||
func TestAScheduledStepRunsWhenDueAndNotBefore(t *testing.T) {
|
||||
func testAScheduledStepRunsWhenDueAndNotBefore(t *testing.T) {
|
||||
clock := &fixedClock{now: time.Date(2026, 9, 7, 12, 0, 30, 0, time.UTC)}
|
||||
rec := &recordingRun{}
|
||||
s := NewScheduler(clock, rec.run, nil)
|
||||
@@ -288,7 +288,7 @@ func TestAScheduledStepRunsWhenDueAndNotBefore(t *testing.T) {
|
||||
|
||||
// --- Requirement 6: a non-zero run is recorded and does not fail the apply or the node. ---
|
||||
|
||||
func TestAFailedRunIsRecordedAndDoesNotFailAnything(t *testing.T) {
|
||||
func testAFailedRunIsRecordedAndDoesNotFailAnything(t *testing.T) {
|
||||
clock := &fixedClock{now: time.Date(2026, 9, 7, 12, 0, 30, 0, time.UTC)}
|
||||
|
||||
var logged []string
|
||||
@@ -342,7 +342,7 @@ func TestAFailedRunIsRecordedAndDoesNotFailAnything(t *testing.T) {
|
||||
|
||||
// --- Requirement 7: runs do not stack. ---
|
||||
|
||||
func TestASlowRunSkipsTheNextDueRunRatherThanStacking(t *testing.T) {
|
||||
func testASlowRunSkipsTheNextDueRunRatherThanStacking(t *testing.T) {
|
||||
clock := &fixedClock{now: time.Date(2026, 9, 7, 12, 0, 30, 0, time.UTC)}
|
||||
|
||||
started := make(chan struct{}) // fire() signals it entered the runner
|
||||
@@ -415,7 +415,7 @@ func TestASlowRunSkipsTheNextDueRunRatherThanStacking(t *testing.T) {
|
||||
|
||||
// --- Sync re-establishes schedules from the declaration (novox/hq ADR 0018, 0053). ---
|
||||
|
||||
func TestSyncForgetsAScheduleTheDeclarationNoLongerNames(t *testing.T) {
|
||||
func testSyncForgetsAScheduleTheDeclarationNoLongerNames(t *testing.T) {
|
||||
clock := &fixedClock{now: time.Date(2026, 9, 7, 12, 0, 30, 0, time.UTC)}
|
||||
rec := &recordingRun{}
|
||||
s := NewScheduler(clock, rec.run, nil)
|
||||
@@ -445,7 +445,7 @@ func TestSyncForgetsAScheduleTheDeclarationNoLongerNames(t *testing.T) {
|
||||
|
||||
// Defends novox/hq ADR 0103: a scheduled step of a module not yet taken is not armed — run on its
|
||||
// cadence it would work on the predecessor's data.
|
||||
func TestAScheduledStepOfAnUntakenModuleIsNotArmed(t *testing.T) {
|
||||
func testAScheduledStepOfAnUntakenModuleIsNotArmed(t *testing.T) {
|
||||
clock := &fixedClock{now: time.Date(2026, 9, 7, 12, 0, 30, 0, time.UTC)}
|
||||
rec := &recordingRun{}
|
||||
var said []string
|
||||
@@ -487,3 +487,15 @@ func TestAScheduledStepOfAnUntakenModuleIsNotArmed(t *testing.T) {
|
||||
t.Error("a taken module's scheduled step never ran")
|
||||
}
|
||||
}
|
||||
|
||||
// TestSchedule runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestSchedule(t *testing.T) {
|
||||
t.Run("InstallingAScheduleDoesNotRunItAndReportsCurrent", testInstallingAScheduleDoesNotRunItAndReportsCurrent)
|
||||
t.Run("InstallingAScheduleEnsuresItsImageIsPresentWithoutStartingIt", testInstallingAScheduleEnsuresItsImageIsPresentWithoutStartingIt)
|
||||
t.Run("AScheduledStepDoesNotGateWhatFollows", testAScheduledStepDoesNotGateWhatFollows)
|
||||
t.Run("AScheduledStepRunsWhenDueAndNotBefore", testAScheduledStepRunsWhenDueAndNotBefore)
|
||||
t.Run("AFailedRunIsRecordedAndDoesNotFailAnything", testAFailedRunIsRecordedAndDoesNotFailAnything)
|
||||
t.Run("ASlowRunSkipsTheNextDueRunRatherThanStacking", testASlowRunSkipsTheNextDueRunRatherThanStacking)
|
||||
t.Run("SyncForgetsAScheduleTheDeclarationNoLongerNames", testSyncForgetsAScheduleTheDeclarationNoLongerNames)
|
||||
t.Run("AScheduledStepOfAnUntakenModuleIsNotArmed", testAScheduledStepOfAnUntakenModuleIsNotArmed)
|
||||
}
|
||||
|
||||
@@ -44,7 +44,7 @@ func sealedFile(t *testing.T, path, sealed string) *declaration.Declaration {
|
||||
return d
|
||||
}
|
||||
|
||||
func TestASealedFileIsOpenedAndWritten(t *testing.T) {
|
||||
func testASealedFileIsOpenedAndWritten(t *testing.T) {
|
||||
key, err := identity.GenerateSealingKey()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -70,7 +70,7 @@ func TestASealedFileIsOpenedAndWritten(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestASecretIsNotWorldReadableByDefault(t *testing.T) {
|
||||
func testASecretIsNotWorldReadableByDefault(t *testing.T) {
|
||||
// An ordinary file defaults to 0644, which for a credential is the whole problem. The default
|
||||
// differs because the consequence differs; an explicit mode still wins, since a module may
|
||||
// need its own user to read it and only the module knows which.
|
||||
@@ -91,7 +91,7 @@ func TestASecretIsNotWorldReadableByDefault(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSomethingSealedToAnotherNodeIsRefused(t *testing.T) {
|
||||
func testSomethingSealedToAnotherNodeIsRefused(t *testing.T) {
|
||||
// Refused, not skipped, and refused before anything is written. A machine that quietly does
|
||||
// not apply the one resource carrying a credential looks configured and cannot connect.
|
||||
mine, _ := identity.GenerateSealingKey()
|
||||
@@ -110,7 +110,7 @@ func TestSomethingSealedToAnotherNodeIsRefused(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestANodeWithNoSealingKeyRefusesRatherThanSkipping(t *testing.T) {
|
||||
func testANodeWithNoSealingKeyRefusesRatherThanSkipping(t *testing.T) {
|
||||
key, _ := identity.GenerateSealingKey()
|
||||
dir := t.TempDir()
|
||||
d := sealedFile(t, dir+"/db.json", sealedTo(t, key, "secret"))
|
||||
@@ -124,7 +124,7 @@ func TestANodeWithNoSealingKeyRefusesRatherThanSkipping(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheSecretIsNeverInWhatTheMeshIsToldBack(t *testing.T) {
|
||||
func testTheSecretIsNeverInWhatTheMeshIsToldBack(t *testing.T) {
|
||||
// The node reports what it applied, and that report goes over the same broker the sealing was
|
||||
// for. A digest is a fact about the file; the file is not.
|
||||
key, _ := identity.GenerateSealingKey()
|
||||
@@ -144,7 +144,7 @@ func TestTheSecretIsNeverInWhatTheMeshIsToldBack(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestASealedFileStillNoticesAHandEdit(t *testing.T) {
|
||||
func testASealedFileStillNoticesAHandEdit(t *testing.T) {
|
||||
// Drift detection must survive not holding the plaintext. It does, because what is recorded
|
||||
// is a digest of what was written rather than what was written.
|
||||
key, _ := identity.GenerateSealingKey()
|
||||
@@ -173,7 +173,7 @@ func TestASealedFileStillNoticesAHandEdit(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestContentAndSealedTogetherIsRefused(t *testing.T) {
|
||||
func testContentAndSealedTogetherIsRefused(t *testing.T) {
|
||||
// Otherwise nobody can tell by looking whether what landed on the machine was the secret or
|
||||
// the placeholder.
|
||||
_, err := declaration.Parse([]byte(`{"declaration":1,"resources":[
|
||||
@@ -185,3 +185,14 @@ func TestContentAndSealedTogetherIsRefused(t *testing.T) {
|
||||
t.Fatalf("unhelpful refusal: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSealed runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestSealed(t *testing.T) {
|
||||
t.Run("ASealedFileIsOpenedAndWritten", testASealedFileIsOpenedAndWritten)
|
||||
t.Run("ASecretIsNotWorldReadableByDefault", testASecretIsNotWorldReadableByDefault)
|
||||
t.Run("SomethingSealedToAnotherNodeIsRefused", testSomethingSealedToAnotherNodeIsRefused)
|
||||
t.Run("ANodeWithNoSealingKeyRefusesRatherThanSkipping", testANodeWithNoSealingKeyRefusesRatherThanSkipping)
|
||||
t.Run("TheSecretIsNeverInWhatTheMeshIsToldBack", testTheSecretIsNeverInWhatTheMeshIsToldBack)
|
||||
t.Run("ASealedFileStillNoticesAHandEdit", testASealedFileStillNoticesAHandEdit)
|
||||
t.Run("ContentAndSealedTogetherIsRefused", testContentAndSealedTogetherIsRefused)
|
||||
}
|
||||
|
||||
@@ -53,7 +53,7 @@ func touched(commands []string) []string {
|
||||
return changing
|
||||
}
|
||||
|
||||
func TestAStatelessServiceRunningIsReloadedForItsTrigger(t *testing.T) {
|
||||
func testAStatelessServiceRunningIsReloadedForItsTrigger(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "mesh.conf")
|
||||
var commands []string
|
||||
report, _, err := Apply(context.Background(), archHost(t),
|
||||
@@ -76,7 +76,7 @@ func TestAStatelessServiceRunningIsReloadedForItsTrigger(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAStatelessServiceNotRunningIsLeftSo(t *testing.T) {
|
||||
func testAStatelessServiceNotRunningIsLeftSo(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "mesh.conf")
|
||||
for _, triggers := range []string{`"reload-on":["uplink.conf"]`, `"restart-on":["uplink.conf"]`} {
|
||||
var commands []string
|
||||
@@ -96,7 +96,7 @@ func TestAStatelessServiceNotRunningIsLeftSo(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAStatelessServiceIsRestartedOnlyForItsRestartTrigger(t *testing.T) {
|
||||
func testAStatelessServiceIsRestartedOnlyForItsRestartTrigger(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "mesh.conf")
|
||||
var commands []string
|
||||
d := parse(t, statelessDecl(path, "x\n", `"restart-on":["uplink.conf"]`))
|
||||
@@ -123,7 +123,7 @@ func TestAStatelessServiceIsRestartedOnlyForItsRestartTrigger(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAStatelessServiceUndeclaredIsForgottenNotStopped(t *testing.T) {
|
||||
func testAStatelessServiceUndeclaredIsForgottenNotStopped(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "mesh.conf")
|
||||
var commands []string
|
||||
_, state, err := Apply(context.Background(), archHost(t),
|
||||
@@ -153,7 +153,7 @@ func TestAStatelessServiceUndeclaredIsForgottenNotStopped(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAStatelessServiceIsNeverHeldOnAnAdoptedNode(t *testing.T) {
|
||||
func testAStatelessServiceIsNeverHeldOnAnAdoptedNode(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "mesh.conf")
|
||||
resources := fmt.Sprintf(`{"id":"uplink.conf","type":"file","path":%q,"into":"block","content":"x\n"},
|
||||
{"id":"uplink.manager","type":"service","unit":"NetworkManager.service","reload-on":["uplink.conf"]}`, path)
|
||||
@@ -190,3 +190,12 @@ func hasStep(steps []Step, verb, id string) bool {
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// TestStateless runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestStateless(t *testing.T) {
|
||||
t.Run("AStatelessServiceRunningIsReloadedForItsTrigger", testAStatelessServiceRunningIsReloadedForItsTrigger)
|
||||
t.Run("AStatelessServiceNotRunningIsLeftSo", testAStatelessServiceNotRunningIsLeftSo)
|
||||
t.Run("AStatelessServiceIsRestartedOnlyForItsRestartTrigger", testAStatelessServiceIsRestartedOnlyForItsRestartTrigger)
|
||||
t.Run("AStatelessServiceUndeclaredIsForgottenNotStopped", testAStatelessServiceUndeclaredIsForgottenNotStopped)
|
||||
t.Run("AStatelessServiceIsNeverHeldOnAnAdoptedNode", testAStatelessServiceIsNeverHeldOnAnAdoptedNode)
|
||||
}
|
||||
|
||||
@@ -92,7 +92,7 @@ func skippedIn(r Report, id string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func TestAStepThatFailedRunsAgainAndKeepsItsModuleGated(t *testing.T) {
|
||||
func testAStepThatFailedRunsAgainAndKeepsItsModuleGated(t *testing.T) {
|
||||
b := newStepBed(t)
|
||||
_, known, err := b.apply(store.State{}, "good")
|
||||
if err != nil || b.starts != 1 || b.after() != "good" {
|
||||
@@ -143,7 +143,7 @@ func TestAStepThatFailedRunsAgainAndKeepsItsModuleGated(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAStepThatNeverFailedRunsNoMoreThanBefore(t *testing.T) {
|
||||
func testAStepThatNeverFailedRunsNoMoreThanBefore(t *testing.T) {
|
||||
// Every node runs many steps: one that passes must run once per change, and not on every apply.
|
||||
b := newStepBed(t)
|
||||
_, known, err := b.apply(store.State{}, "one")
|
||||
@@ -161,7 +161,7 @@ func TestAStepThatNeverFailedRunsNoMoreThanBefore(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAContainerStepThatFailedRunsAgain(t *testing.T) {
|
||||
func testAContainerStepThatFailedRunsAgain(t *testing.T) {
|
||||
// A run-once container gates its module the same way (novox/hq ADR 0052, ADR 0136). It already ran
|
||||
// again before issue 467 was fixed, because what it is declared with is part of what it is run as:
|
||||
// held here so it stays that way.
|
||||
@@ -210,7 +210,7 @@ func TestAContainerStepThatFailedRunsAgain(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAStepWhoseBundleCouldNotBeFetchedIsNotRunAgainForIt(t *testing.T) {
|
||||
func testAStepWhoseBundleCouldNotBeFetchedIsNotRunAgainForIt(t *testing.T) {
|
||||
// A fetch that fails is a failure of the step, and gates its module, but the step was never started:
|
||||
// it did not refuse anything, and its last success stands. Cleared for it, every step on a machine
|
||||
// would run again once the artifact store came back from an outage.
|
||||
@@ -236,7 +236,7 @@ func TestAStepWhoseBundleCouldNotBeFetchedIsNotRunAgainForIt(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAStepPassingAfterAFailureSaysItWasUpdated(t *testing.T) {
|
||||
func testAStepPassingAfterAFailureSaysItWasUpdated(t *testing.T) {
|
||||
b := newStepBed(t)
|
||||
_, known, _ := b.apply(store.State{}, "good")
|
||||
b.refuse = true
|
||||
@@ -252,3 +252,12 @@ func TestAStepPassingAfterAFailureSaysItWasUpdated(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestStepFailed runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestStepFailed(t *testing.T) {
|
||||
t.Run("AStepThatFailedRunsAgainAndKeepsItsModuleGated", testAStepThatFailedRunsAgainAndKeepsItsModuleGated)
|
||||
t.Run("AStepThatNeverFailedRunsNoMoreThanBefore", testAStepThatNeverFailedRunsNoMoreThanBefore)
|
||||
t.Run("AContainerStepThatFailedRunsAgain", testAContainerStepThatFailedRunsAgain)
|
||||
t.Run("AStepWhoseBundleCouldNotBeFetchedIsNotRunAgainForIt", testAStepWhoseBundleCouldNotBeFetchedIsNotRunAgainForIt)
|
||||
t.Run("AStepPassingAfterAFailureSaysItWasUpdated", testAStepPassingAfterAFailureSaysItWasUpdated)
|
||||
}
|
||||
|
||||
@@ -126,7 +126,7 @@ func (s *saying) all() string { s.mu.Lock(); defer s.mu.Unlock(); return str
|
||||
|
||||
// On the store's own machine: an apply that reaches the store's archives while the collector holds the
|
||||
// server still waits for the window, and applies once it closes — no failure, nothing held.
|
||||
func TestAnApplyOnTheStoresMachineWaitsForItsWindow(t *testing.T) {
|
||||
func testAnApplyOnTheStoresMachineWaitsForItsWindow(t *testing.T) {
|
||||
patiently(t, time.Second)
|
||||
body, digest := anArchive(t, map[string]string{"bin/postgres-tools": "#!/bin/sh"})
|
||||
st := newPretendStore(t, body)
|
||||
@@ -180,7 +180,7 @@ func TestAnApplyOnTheStoresMachineWaitsForItsWindow(t *testing.T) {
|
||||
|
||||
// And the order on the store's machine: a collector due while an apply is in flight opens its window only
|
||||
// once the apply ended — so an apply that started before it never finds the server stopped under it.
|
||||
func TestAWindowOpensOnlyOnceTheApplyInFlightEnded(t *testing.T) {
|
||||
func testAWindowOpensOnlyOnceTheApplyInFlightEnded(t *testing.T) {
|
||||
patiently(t, time.Second)
|
||||
d := aStoreWithACollector(t)
|
||||
m := newRegistryMachine(containerSpec(d.Resources[0].(*declaration.Container), inputs{}))
|
||||
@@ -237,7 +237,7 @@ func TestAWindowOpensOnlyOnceTheApplyInFlightEnded(t *testing.T) {
|
||||
|
||||
// On every other machine the store's window is not known: a store that does not answer is fetched again
|
||||
// with backoff, and the bundle arrives once the store is back.
|
||||
func TestAnApplyElsewhereWaitsABoundedWhileForTheStore(t *testing.T) {
|
||||
func testAnApplyElsewhereWaitsABoundedWhileForTheStore(t *testing.T) {
|
||||
patiently(t, 5*time.Second)
|
||||
body, digest := anArchive(t, map[string]string{"bin/tools": "#!/bin/sh"})
|
||||
st := newPretendStore(t, body)
|
||||
@@ -266,7 +266,7 @@ const aDigest = "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
|
||||
|
||||
// A store really down costs one bounded wait per apply, not one per bundle; and an answer — a blob the
|
||||
// store does not have — fails at once, as it always did.
|
||||
func TestAStoreThatStaysAwayCostsOneBoundedWait(t *testing.T) {
|
||||
func testAStoreThatStaysAwayCostsOneBoundedWait(t *testing.T) {
|
||||
patiently(t, 80*time.Millisecond)
|
||||
st := newPretendStore(t, []byte("x"))
|
||||
st.stop()
|
||||
@@ -330,3 +330,11 @@ func TestAStoreThatStaysAwayCostsOneBoundedWait(t *testing.T) {
|
||||
t.Fatalf("other bytes told %q: want the declared digest forgotten once", told)
|
||||
}
|
||||
}
|
||||
|
||||
// TestStoreAway runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestStoreAway(t *testing.T) {
|
||||
t.Run("AnApplyOnTheStoresMachineWaitsForItsWindow", testAnApplyOnTheStoresMachineWaitsForItsWindow)
|
||||
t.Run("AWindowOpensOnlyOnceTheApplyInFlightEnded", testAWindowOpensOnlyOnceTheApplyInFlightEnded)
|
||||
t.Run("AnApplyElsewhereWaitsABoundedWhileForTheStore", testAnApplyElsewhereWaitsABoundedWhileForTheStore)
|
||||
t.Run("AStoreThatStaysAwayCostsOneBoundedWait", testAStoreThatStaysAwayCostsOneBoundedWait)
|
||||
}
|
||||
|
||||
@@ -73,7 +73,7 @@ func aHubInUse(t *testing.T) (dir, config, mesh, keyFile string, m *machine) {
|
||||
return dir, config, mesh, keyFile, m
|
||||
}
|
||||
|
||||
func TestTheFoundTunnelIsStoppedNeverFlushedAndItsConfigurationKept(t *testing.T) {
|
||||
func testTheFoundTunnelIsStoppedNeverFlushedAndItsConfigurationKept(t *testing.T) {
|
||||
dir, config, mesh, keyFile, m := aHubInUse(t)
|
||||
report, state := applyAdopted(t, aTakeover(t, config, mesh, keyFile, "51900", "192.0.2.1"), store.State{}, m, dir)
|
||||
|
||||
@@ -132,7 +132,7 @@ func TestTheFoundTunnelIsStoppedNeverFlushedAndItsConfigurationKept(t *testing.T
|
||||
}
|
||||
}
|
||||
|
||||
func TestNothingIsStoppedUntilTheMeshsInterfaceCanReplaceTheFoundOne(t *testing.T) {
|
||||
func testNothingIsStoppedUntilTheMeshsInterfaceCanReplaceTheFoundOne(t *testing.T) {
|
||||
dir, config, mesh, keyFile, m := aHubInUse(t)
|
||||
otherKey := filepath.Join(dir, "other.key")
|
||||
k, _ := ecdh.X25519().GenerateKey(rand.Reader)
|
||||
@@ -170,7 +170,7 @@ func TestNothingIsStoppedUntilTheMeshsInterfaceCanReplaceTheFoundOne(t *testing.
|
||||
}
|
||||
}
|
||||
|
||||
func TestAMeshInterfaceThatFailsToStartGivesTheFoundOneBack(t *testing.T) {
|
||||
func testAMeshInterfaceThatFailsToStartGivesTheFoundOneBack(t *testing.T) {
|
||||
dir, config, mesh, keyFile, m := aHubInUse(t)
|
||||
m.units["wg-quick@mesh0"].wontStart = true
|
||||
report, _, err := ApplyKeeping(t.Context(), archHost(t), aTakeover(t, config, mesh, keyFile, "51900", "192.0.2.1"),
|
||||
@@ -190,7 +190,7 @@ func TestAMeshInterfaceThatFailsToStartGivesTheFoundOneBack(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestATakeoverIsSteadyAndAFoundUnitUpAgainIsSaidNotStopped(t *testing.T) {
|
||||
func testATakeoverIsSteadyAndAFoundUnitUpAgainIsSaidNotStopped(t *testing.T) {
|
||||
dir, config, mesh, keyFile, m := aHubInUse(t)
|
||||
d := aTakeover(t, config, mesh, keyFile, "51900", "192.0.2.1")
|
||||
_, state := applyAdopted(t, d, store.State{}, m, dir)
|
||||
@@ -223,7 +223,7 @@ func TestATakeoverIsSteadyAndAFoundUnitUpAgainIsSaidNotStopped(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAFoundInterfaceRaisedByHandIsRefusedNamingTheRemedy(t *testing.T) {
|
||||
func testAFoundInterfaceRaisedByHandIsRefusedNamingTheRemedy(t *testing.T) {
|
||||
dir, config, mesh, keyFile, m := aHubInUse(t)
|
||||
// The unit is not running, yet the interface is up: the predecessor raised it by hand.
|
||||
m.units["wg-quick@wg0"].active = "inactive"
|
||||
@@ -254,7 +254,7 @@ func TestAFoundInterfaceRaisedByHandIsRefusedNamingTheRemedy(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestATakeoverIsRefusedOnAConvergedDeclaration(t *testing.T) {
|
||||
func testATakeoverIsRefusedOnAConvergedDeclaration(t *testing.T) {
|
||||
_, err := declaration.Parse([]byte(`{"declaration":1,"resources":[
|
||||
{"id":"up","type":"service","unit":"wg-quick@mesh0","state":"running",
|
||||
"takes-over":{"interface":"wg0","unit":"wg-quick@wg0","config":"/etc/wireguard/wg0.conf"}}]}`))
|
||||
@@ -272,7 +272,7 @@ const takesOverID = "mesh-wireguard.overlay-up.takes-over"
|
||||
// handshaken is `wg show mesh0 latest-handshakes` with one of the two peers through.
|
||||
const handshaken = "PEER-A=\t1790000000\nPEER-B=\t0\n"
|
||||
|
||||
func TestAProvenTakeRetiresTheFoundConfiguration(t *testing.T) {
|
||||
func testAProvenTakeRetiresTheFoundConfiguration(t *testing.T) {
|
||||
dir, config, mesh, keyFile, m := aHubInUse(t)
|
||||
m.handshakes = handshaken
|
||||
report, state := applyAdopted(t, aTakeover(t, config, mesh, keyFile, "51900", "192.0.2.1"), store.State{}, m, dir)
|
||||
@@ -307,7 +307,7 @@ func TestAProvenTakeRetiresTheFoundConfiguration(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestATakeNotProvenKeepsTheFoundConfigurationAndSaysSo(t *testing.T) {
|
||||
func testATakeNotProvenKeepsTheFoundConfigurationAndSaysSo(t *testing.T) {
|
||||
cases := map[string]struct {
|
||||
handshakes string
|
||||
fail error
|
||||
@@ -351,7 +351,7 @@ func TestATakeNotProvenKeepsTheFoundConfigurationAndSaysSo(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAFoundConfigurationWhoseKeptOriginalIsMissingIsNotRetired(t *testing.T) {
|
||||
func testAFoundConfigurationWhoseKeptOriginalIsMissingIsNotRetired(t *testing.T) {
|
||||
dir, config, mesh, keyFile, m := aHubInUse(t)
|
||||
d := aTakeover(t, config, mesh, keyFile, "51900", "192.0.2.1")
|
||||
_, state := applyAdopted(t, d, store.State{}, m, dir)
|
||||
@@ -377,7 +377,7 @@ func TestAFoundConfigurationWhoseKeptOriginalIsMissingIsNotRetired(t *testing.T)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAFoundConfigurationRewrittenSinceItWasFoundIsKeptAgainBeforeItGoes(t *testing.T) {
|
||||
func testAFoundConfigurationRewrittenSinceItWasFoundIsKeptAgainBeforeItGoes(t *testing.T) {
|
||||
dir, config, mesh, keyFile, m := aHubInUse(t)
|
||||
d := aTakeover(t, config, mesh, keyFile, "51900", "192.0.2.1")
|
||||
_, state := applyAdopted(t, d, store.State{}, m, dir)
|
||||
@@ -407,7 +407,7 @@ func TestAFoundConfigurationRewrittenSinceItWasFoundIsKeptAgainBeforeItGoes(t *t
|
||||
}
|
||||
}
|
||||
|
||||
func TestARetiredTakeIsSteadyAndItsFoundUnitFindsNothingToDo(t *testing.T) {
|
||||
func testARetiredTakeIsSteadyAndItsFoundUnitFindsNothingToDo(t *testing.T) {
|
||||
dir, config, mesh, keyFile, m := aHubInUse(t)
|
||||
m.handshakes = handshaken
|
||||
d := aTakeover(t, config, mesh, keyFile, "51900", "192.0.2.1")
|
||||
@@ -449,7 +449,7 @@ func TestARetiredTakeIsSteadyAndItsFoundUnitFindsNothingToDo(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestUndeclaringThePrivateNetworkAfterRetirementBringsNothingBack(t *testing.T) {
|
||||
func testUndeclaringThePrivateNetworkAfterRetirementBringsNothingBack(t *testing.T) {
|
||||
dir, config, mesh, keyFile, m := aHubInUse(t)
|
||||
m.handshakes = handshaken
|
||||
d := aTakeover(t, config, mesh, keyFile, "51900", "192.0.2.1")
|
||||
@@ -481,7 +481,7 @@ func TestUndeclaringThePrivateNetworkAfterRetirementBringsNothingBack(t *testing
|
||||
}
|
||||
}
|
||||
|
||||
func TestAPlanSaysTheFoundConfigurationIsRetiredWhenTheTakeIsProven(t *testing.T) {
|
||||
func testAPlanSaysTheFoundConfigurationIsRetiredWhenTheTakeIsProven(t *testing.T) {
|
||||
dir, config, mesh, keyFile, m := aHubInUse(t)
|
||||
d := aTakeover(t, config, mesh, keyFile, "51900", "192.0.2.1")
|
||||
|
||||
@@ -524,7 +524,7 @@ func keptCopies(t *testing.T, dir string) []string {
|
||||
return kept
|
||||
}
|
||||
|
||||
func TestAConfigurationPutBackIsRetiredAgainOnItsFirstOriginalAndSettles(t *testing.T) {
|
||||
func testAConfigurationPutBackIsRetiredAgainOnItsFirstOriginalAndSettles(t *testing.T) {
|
||||
dir, config, mesh, keyFile, m := aHubInUse(t)
|
||||
m.handshakes = handshaken
|
||||
d := aTakeover(t, config, mesh, keyFile, "51900", "192.0.2.1")
|
||||
@@ -597,7 +597,7 @@ func TestAConfigurationPutBackIsRetiredAgainOnItsFirstOriginalAndSettles(t *test
|
||||
}
|
||||
}
|
||||
|
||||
func TestOnlyWgQuicksOwnConfigurationIsRetired(t *testing.T) {
|
||||
func testOnlyWgQuicksOwnConfigurationIsRetired(t *testing.T) {
|
||||
// Not under the wireguard directory.
|
||||
dir, config, mesh, keyFile, m := aHubInUse(t)
|
||||
wireguardDir = filepath.Join(dir, "elsewhere")
|
||||
@@ -624,7 +624,7 @@ func TestOnlyWgQuicksOwnConfigurationIsRetired(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAFoundConfigurationThatIsALinkIsKeptAndLeftToAPerson(t *testing.T) {
|
||||
func testAFoundConfigurationThatIsALinkIsKeptAndLeftToAPerson(t *testing.T) {
|
||||
dir, config, mesh, keyFile, m := aHubInUse(t)
|
||||
target := filepath.Join(dir, "predecessor", "hub.conf")
|
||||
if err := os.MkdirAll(filepath.Dir(target), 0o700); err != nil {
|
||||
@@ -657,7 +657,7 @@ func TestAFoundConfigurationThatIsALinkIsKeptAndLeftToAPerson(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestARetirementWhoseRecordWasNeverSavedIsRecordedByTheNextApply(t *testing.T) {
|
||||
func testARetirementWhoseRecordWasNeverSavedIsRecordedByTheNextApply(t *testing.T) {
|
||||
dir, config, mesh, keyFile, m := aHubInUse(t)
|
||||
d := aTakeover(t, config, mesh, keyFile, "51900", "192.0.2.1")
|
||||
_, state := applyAdopted(t, d, store.State{}, m, dir)
|
||||
@@ -679,7 +679,7 @@ func TestARetirementWhoseRecordWasNeverSavedIsRecordedByTheNextApply(t *testing.
|
||||
}
|
||||
}
|
||||
|
||||
func TestARemovalThatFailsKeepsTheFileAndTheHold(t *testing.T) {
|
||||
func testARemovalThatFailsKeepsTheFileAndTheHold(t *testing.T) {
|
||||
if os.Geteuid() == 0 {
|
||||
t.Skip("root removes from a directory it may not write to")
|
||||
}
|
||||
@@ -713,3 +713,25 @@ func TestARemovalThatFailsKeepsTheFileAndTheHold(t *testing.T) {
|
||||
t.Errorf("the failed removal is not said: %q", report.Tunnel.Note)
|
||||
}
|
||||
}
|
||||
|
||||
// TestTakeover runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestTakeover(t *testing.T) {
|
||||
t.Run("TheFoundTunnelIsStoppedNeverFlushedAndItsConfigurationKept", testTheFoundTunnelIsStoppedNeverFlushedAndItsConfigurationKept)
|
||||
t.Run("NothingIsStoppedUntilTheMeshsInterfaceCanReplaceTheFoundOne", testNothingIsStoppedUntilTheMeshsInterfaceCanReplaceTheFoundOne)
|
||||
t.Run("AMeshInterfaceThatFailsToStartGivesTheFoundOneBack", testAMeshInterfaceThatFailsToStartGivesTheFoundOneBack)
|
||||
t.Run("ATakeoverIsSteadyAndAFoundUnitUpAgainIsSaidNotStopped", testATakeoverIsSteadyAndAFoundUnitUpAgainIsSaidNotStopped)
|
||||
t.Run("AFoundInterfaceRaisedByHandIsRefusedNamingTheRemedy", testAFoundInterfaceRaisedByHandIsRefusedNamingTheRemedy)
|
||||
t.Run("ATakeoverIsRefusedOnAConvergedDeclaration", testATakeoverIsRefusedOnAConvergedDeclaration)
|
||||
t.Run("AProvenTakeRetiresTheFoundConfiguration", testAProvenTakeRetiresTheFoundConfiguration)
|
||||
t.Run("ATakeNotProvenKeepsTheFoundConfigurationAndSaysSo", testATakeNotProvenKeepsTheFoundConfigurationAndSaysSo)
|
||||
t.Run("AFoundConfigurationWhoseKeptOriginalIsMissingIsNotRetired", testAFoundConfigurationWhoseKeptOriginalIsMissingIsNotRetired)
|
||||
t.Run("AFoundConfigurationRewrittenSinceItWasFoundIsKeptAgainBeforeItGoes", testAFoundConfigurationRewrittenSinceItWasFoundIsKeptAgainBeforeItGoes)
|
||||
t.Run("ARetiredTakeIsSteadyAndItsFoundUnitFindsNothingToDo", testARetiredTakeIsSteadyAndItsFoundUnitFindsNothingToDo)
|
||||
t.Run("UndeclaringThePrivateNetworkAfterRetirementBringsNothingBack", testUndeclaringThePrivateNetworkAfterRetirementBringsNothingBack)
|
||||
t.Run("APlanSaysTheFoundConfigurationIsRetiredWhenTheTakeIsProven", testAPlanSaysTheFoundConfigurationIsRetiredWhenTheTakeIsProven)
|
||||
t.Run("AConfigurationPutBackIsRetiredAgainOnItsFirstOriginalAndSettles", testAConfigurationPutBackIsRetiredAgainOnItsFirstOriginalAndSettles)
|
||||
t.Run("OnlyWgQuicksOwnConfigurationIsRetired", testOnlyWgQuicksOwnConfigurationIsRetired)
|
||||
t.Run("AFoundConfigurationThatIsALinkIsKeptAndLeftToAPerson", testAFoundConfigurationThatIsALinkIsKeptAndLeftToAPerson)
|
||||
t.Run("ARetirementWhoseRecordWasNeverSavedIsRecordedByTheNextApply", testARetirementWhoseRecordWasNeverSavedIsRecordedByTheNextApply)
|
||||
t.Run("ARemovalThatFailsKeepsTheFileAndTheHold", testARemovalThatFailsKeepsTheFileAndTheHold)
|
||||
}
|
||||
|
||||
@@ -97,7 +97,7 @@ func userWith(shell string) string {
|
||||
return `{"id":"shell.login","type":"user","name":"operator","shell":"` + shell + `"}`
|
||||
}
|
||||
|
||||
func TestAnUndeclaredUserNoLongerStopsTheApply(t *testing.T) {
|
||||
func testAnUndeclaredUserNoLongerStopsTheApply(t *testing.T) {
|
||||
// Before issue 228 the host had no removal for a user, the orphan failed with "no way to
|
||||
// remove", and an orphan's failure aborts the apply before its first resource — on every
|
||||
// apply after, since the record stayed.
|
||||
@@ -124,7 +124,7 @@ func TestAnUndeclaredUserNoLongerStopsTheApply(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheShellFoundIsGivenBackWhenTheUserIsUndeclared(t *testing.T) {
|
||||
func testTheShellFoundIsGivenBackWhenTheUserIsUndeclared(t *testing.T) {
|
||||
dir := shellsOn(t, []string{"bash", "zsh"})
|
||||
l := &logins{shells: map[string]string{"operator": dir + "/bash"}}
|
||||
_, state, err := applyUsers(t, l, store.State{}, userWith(dir+"/zsh"))
|
||||
@@ -153,7 +153,7 @@ func TestTheShellFoundIsGivenBackWhenTheUserIsUndeclared(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAShellAPersonChangedSinceIsLeftAlone(t *testing.T) {
|
||||
func testAShellAPersonChangedSinceIsLeftAlone(t *testing.T) {
|
||||
dir := shellsOn(t, []string{"bash", "zsh", "fish"})
|
||||
l := &logins{shells: map[string]string{"operator": dir + "/bash"}}
|
||||
_, state, err := applyUsers(t, l, store.State{}, userWith(dir+"/zsh"))
|
||||
@@ -175,7 +175,7 @@ func TestAShellAPersonChangedSinceIsLeftAlone(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAFoundShellThatIsGoneIsNotGivenBack(t *testing.T) {
|
||||
func testAFoundShellThatIsGoneIsNotGivenBack(t *testing.T) {
|
||||
// Giving back a shell uninstalled since would break the logins the giving back is for.
|
||||
dir := shellsOn(t, []string{"bash", "zsh"})
|
||||
l := &logins{shells: map[string]string{"operator": dir + "/bash"}}
|
||||
@@ -199,7 +199,7 @@ func TestAFoundShellThatIsGoneIsNotGivenBack(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAShellThatIsMissingOrUnlistedIsRefusedBeforeItIsSet(t *testing.T) {
|
||||
func testAShellThatIsMissingOrUnlistedIsRefusedBeforeItIsSet(t *testing.T) {
|
||||
dir := shellsOn(t, []string{"bash"}, "unlisted")
|
||||
for name, shell := range map[string]string{
|
||||
"missing": dir + "/zsh",
|
||||
@@ -235,7 +235,7 @@ func TestAShellThatIsMissingOrUnlistedIsRefusedBeforeItIsSet(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
func TestAnAccountThatRefusesLoginsNeedNotBeListed(t *testing.T) {
|
||||
func testAnAccountThatRefusesLoginsNeedNotBeListed(t *testing.T) {
|
||||
// A service's account has nologin, which no distribution lists among its shells; refusing it
|
||||
// would refuse the controller's own account.
|
||||
dir := shellsOn(t, []string{"bash"}, "nologin")
|
||||
@@ -248,7 +248,7 @@ func TestAnAccountThatRefusesLoginsNeedNotBeListed(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestACreatedAccountSurvivesItsRemoval(t *testing.T) {
|
||||
func testACreatedAccountSurvivesItsRemoval(t *testing.T) {
|
||||
dir := shellsOn(t, []string{"zsh"})
|
||||
l := &logins{shells: map[string]string{}}
|
||||
report, state, err := applyUsers(t, l, store.State{}, userWith(dir+"/zsh"))
|
||||
@@ -271,7 +271,7 @@ func TestACreatedAccountSurvivesItsRemoval(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheFoundShellIsNotOverwrittenByASecondChange(t *testing.T) {
|
||||
func testTheFoundShellIsNotOverwrittenByASecondChange(t *testing.T) {
|
||||
// The holding moves from one shell module to another: what is given back in the end is the
|
||||
// shell from before the mesh, not the first module's.
|
||||
dir := shellsOn(t, []string{"bash", "zsh", "fish"})
|
||||
@@ -297,7 +297,7 @@ func TestTheFoundShellIsNotOverwrittenByASecondChange(t *testing.T) {
|
||||
|
||||
// An account declared never to become root is never a system account taken over (novox/hq ADR 0266): the
|
||||
// controller cannot tell a service's account from a free name, so the node-engine refuses it, touching nothing.
|
||||
func TestARootNeverAccountIsNotASystemAccountTakenOver(t *testing.T) {
|
||||
func testARootNeverAccountIsNotASystemAccountTakenOver(t *testing.T) {
|
||||
l := &logins{shells: map[string]string{}}
|
||||
run := func(ctx context.Context, name string, args ...string) (string, error) {
|
||||
if name == "getent" && args[len(args)-1] == "postgres" {
|
||||
@@ -323,3 +323,16 @@ func TestARootNeverAccountIsNotASystemAccountTakenOver(t *testing.T) {
|
||||
t.Fatalf("a login's account is taken: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestUser runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestUser(t *testing.T) {
|
||||
t.Run("AnUndeclaredUserNoLongerStopsTheApply", testAnUndeclaredUserNoLongerStopsTheApply)
|
||||
t.Run("TheShellFoundIsGivenBackWhenTheUserIsUndeclared", testTheShellFoundIsGivenBackWhenTheUserIsUndeclared)
|
||||
t.Run("AShellAPersonChangedSinceIsLeftAlone", testAShellAPersonChangedSinceIsLeftAlone)
|
||||
t.Run("AFoundShellThatIsGoneIsNotGivenBack", testAFoundShellThatIsGoneIsNotGivenBack)
|
||||
t.Run("AShellThatIsMissingOrUnlistedIsRefusedBeforeItIsSet", testAShellThatIsMissingOrUnlistedIsRefusedBeforeItIsSet)
|
||||
t.Run("AnAccountThatRefusesLoginsNeedNotBeListed", testAnAccountThatRefusesLoginsNeedNotBeListed)
|
||||
t.Run("ACreatedAccountSurvivesItsRemoval", testACreatedAccountSurvivesItsRemoval)
|
||||
t.Run("TheFoundShellIsNotOverwrittenByASecondChange", testTheFoundShellIsNotOverwrittenByASecondChange)
|
||||
t.Run("ARootNeverAccountIsNotASystemAccountTakenOver", testARootNeverAccountIsNotASystemAccountTakenOver)
|
||||
}
|
||||
|
||||
@@ -157,7 +157,7 @@ func outcomeFor(r Report, id string) Outcome {
|
||||
return Outcome{}
|
||||
}
|
||||
|
||||
func TestAUserScopedUnitIsAppliedThroughTheAccountsManager(t *testing.T) {
|
||||
func testAUserScopedUnitIsAppliedThroughTheAccountsManager(t *testing.T) {
|
||||
a := newAccount(t, true)
|
||||
report, known, err := applyAccount(t, declaring(watcher), store.State{}, a)
|
||||
if err != nil {
|
||||
@@ -179,7 +179,7 @@ func TestAUserScopedUnitIsAppliedThroughTheAccountsManager(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestASystemUnitIsUntouchedByTheScope(t *testing.T) {
|
||||
func testASystemUnitIsUntouchedByTheScope(t *testing.T) {
|
||||
var commands []string
|
||||
decl := `{"declaration":1,"resources":[
|
||||
{"id":"x.daemon","type":"service","unit":"sshd.service","state":"running","boot":"enabled"}
|
||||
@@ -197,7 +197,7 @@ func TestASystemUnitIsUntouchedByTheScope(t *testing.T) {
|
||||
|
||||
// With nobody logged in and no lingering, the unit waits: not a failure, nothing recorded, and the
|
||||
// account's manager never asked — asking it would log the account in.
|
||||
func TestAUserUnitWaitsForItsAccountsManagerAndIsAppliedWhenItRuns(t *testing.T) {
|
||||
func testAUserUnitWaitsForItsAccountsManagerAndIsAppliedWhenItRuns(t *testing.T) {
|
||||
a := newAccount(t, false)
|
||||
report, known, err := applyAccount(t, declaring(watcher), store.State{}, a)
|
||||
if err != nil {
|
||||
@@ -233,7 +233,7 @@ func TestAUserUnitWaitsForItsAccountsManagerAndIsAppliedWhenItRuns(t *testing.T)
|
||||
|
||||
// A unit applied before, its account since logged out: the record stays exactly as it was, what
|
||||
// was found included, so a later removal still gives back what was there before the mesh.
|
||||
func TestAWaitingUnitKeepsItsRecord(t *testing.T) {
|
||||
func testAWaitingUnitKeepsItsRecord(t *testing.T) {
|
||||
a := newAccount(t, true)
|
||||
_, known, err := applyAccount(t, declaring(watcher), store.State{}, a)
|
||||
if err != nil {
|
||||
@@ -253,7 +253,7 @@ func TestAWaitingUnitKeepsItsRecord(t *testing.T) {
|
||||
|
||||
// A manager that says it runs and then does not answer — the person logged out mid-apply — is the
|
||||
// same absence, and is said the same way.
|
||||
func TestAManagerThatStopsDuringTheApplyIsWaitedFor(t *testing.T) {
|
||||
func testAManagerThatStopsDuringTheApplyIsWaitedFor(t *testing.T) {
|
||||
a := newAccount(t, true)
|
||||
a.busDown = true
|
||||
calls := 0
|
||||
@@ -277,7 +277,7 @@ func TestAManagerThatStopsDuringTheApplyIsWaitedFor(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAUserUnitOfAnAccountTheMachineDoesNotHaveIsRefused(t *testing.T) {
|
||||
func testAUserUnitOfAnAccountTheMachineDoesNotHaveIsRefused(t *testing.T) {
|
||||
a := newAccount(t, true)
|
||||
a.name = "someone-else"
|
||||
_, _, err := applyAccount(t, declaring(watcher), store.State{}, a)
|
||||
@@ -288,7 +288,7 @@ func TestAUserUnitOfAnAccountTheMachineDoesNotHaveIsRefused(t *testing.T) {
|
||||
|
||||
// Without a manager per account — OpenRC — a user-scoped unit would otherwise be applied as the
|
||||
// machine's service of the same name. Refused instead.
|
||||
func TestAUserUnitIsRefusedWhereTheServiceManagerHasNoAccounts(t *testing.T) {
|
||||
func testAUserUnitIsRefusedWhereTheServiceManagerHasNoAccounts(t *testing.T) {
|
||||
alpine, err := system.For("alpine")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -306,7 +306,7 @@ func TestAUserUnitIsRefusedWhereTheServiceManagerHasNoAccounts(t *testing.T) {
|
||||
|
||||
// **Removal is never fatal** (the issue 162/228 wedge): with the manager away the record stays and
|
||||
// the outcome says it waits; the first apply that finds the manager gives the unit back.
|
||||
func TestRemovingAUserUnitWithItsManagerAwayWaitsAndIsNeverFatal(t *testing.T) {
|
||||
func testRemovingAUserUnitWithItsManagerAwayWaitsAndIsNeverFatal(t *testing.T) {
|
||||
a := newAccount(t, true)
|
||||
_, known, err := applyAccount(t, declaring(watcher), store.State{}, a)
|
||||
if err != nil {
|
||||
@@ -342,7 +342,7 @@ func TestRemovingAUserUnitWithItsManagerAwayWaitsAndIsNeverFatal(t *testing.T) {
|
||||
}
|
||||
|
||||
// "Failed to connect to bus" from a manager that said it ran is said and retried, never fatal.
|
||||
func TestRemovingAUserUnitWhoseBusDoesNotAnswerIsNotFatal(t *testing.T) {
|
||||
func testRemovingAUserUnitWhoseBusDoesNotAnswerIsNotFatal(t *testing.T) {
|
||||
a := newAccount(t, true)
|
||||
_, known, err := applyAccount(t, declaring(watcher), store.State{}, a)
|
||||
if err != nil {
|
||||
@@ -361,7 +361,7 @@ func TestRemovingAUserUnitWhoseBusDoesNotAnswerIsNotFatal(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemovingAUserUnitOfAnAccountThatIsGoneForgetsIt(t *testing.T) {
|
||||
func testRemovingAUserUnitOfAnAccountThatIsGoneForgetsIt(t *testing.T) {
|
||||
a := newAccount(t, true)
|
||||
_, known, err := applyAccount(t, declaring(watcher), store.State{}, a)
|
||||
if err != nil {
|
||||
@@ -382,7 +382,7 @@ func TestRemovingAUserUnitOfAnAccountThatIsGoneForgetsIt(t *testing.T) {
|
||||
|
||||
// A unit file the mesh wrote under the account's own unit directory makes the unit the mesh's — and
|
||||
// only the account's unit of that name, never the machine's.
|
||||
func TestAUserUnitsFileTheMeshWroteMakesThatUnitAndNoOtherTheMeshs(t *testing.T) {
|
||||
func testAUserUnitsFileTheMeshWroteMakesThatUnitAndNoOtherTheMeshs(t *testing.T) {
|
||||
home := t.TempDir()
|
||||
was := homeOf
|
||||
homeOf = func(name string) (string, error) {
|
||||
@@ -427,7 +427,7 @@ func TestAUserUnitsFileTheMeshWroteMakesThatUnitAndNoOtherTheMeshs(t *testing.T)
|
||||
|
||||
// Undeclared together, the account's unit whose file the mesh wrote is stopped and disabled in the
|
||||
// account's manager — whatever was found — and a system unit of the same name is not touched.
|
||||
func TestAMeshMadeUserUnitIsStoppedInItsAccountAndTheMachinesNamesakeIsNot(t *testing.T) {
|
||||
func testAMeshMadeUserUnitIsStoppedInItsAccountAndTheMachinesNamesakeIsNot(t *testing.T) {
|
||||
a := newAccount(t, true)
|
||||
home := t.TempDir()
|
||||
was := homeOf
|
||||
@@ -460,7 +460,7 @@ func TestAMeshMadeUserUnitIsStoppedInItsAccountAndTheMachinesNamesakeIsNot(t *te
|
||||
|
||||
// A service moved from the machine's manager into an account's is two units: the machine's is given
|
||||
// back as it was found, through the machine's manager, and the account's is read afresh.
|
||||
func TestAServiceMovedIntoAnAccountGivesTheMachinesUnitBack(t *testing.T) {
|
||||
func testAServiceMovedIntoAnAccountGivesTheMachinesUnitBack(t *testing.T) {
|
||||
a := newAccount(t, true)
|
||||
a.system["i3-reload-watcher.service"] = &fakeUnit{active: "active", enabled: "enabled"}
|
||||
known := store.State{Resources: []store.Applied{
|
||||
@@ -485,7 +485,7 @@ func TestAServiceMovedIntoAnAccountGivesTheMachinesUnitBack(t *testing.T) {
|
||||
|
||||
// Lingering is the account's (novox/hq ADR 0177): declared, set and read back; recorded with what
|
||||
// was found; given back on removal while the account still has what the mesh set.
|
||||
func TestLingeringIsDeclaredOnTheAccountAndGivenBack(t *testing.T) {
|
||||
func testLingeringIsDeclaredOnTheAccountAndGivenBack(t *testing.T) {
|
||||
a := newAccount(t, false)
|
||||
user := `{"id":"ops.login","type":"user","name":"ops","linger":true}`
|
||||
report, known, err := applyAccount(t, declaring(user), store.State{}, a)
|
||||
@@ -529,7 +529,7 @@ func TestLingeringIsDeclaredOnTheAccountAndGivenBack(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestLingeringTheOperatorChangedSinceIsLeft(t *testing.T) {
|
||||
func testLingeringTheOperatorChangedSinceIsLeft(t *testing.T) {
|
||||
a := newAccount(t, false)
|
||||
known := store.State{Resources: []store.Applied{{ID: "ops.login", Type: "user", Target: "ops",
|
||||
Origin: store.OriginDeclared, Linger: &store.Lingering{Found: false, Set: true}}}}
|
||||
@@ -546,7 +546,7 @@ func TestLingeringTheOperatorChangedSinceIsLeft(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestLingeringIsRefusedWhereTheServiceManagerHasNoAccounts(t *testing.T) {
|
||||
func testLingeringIsRefusedWhereTheServiceManagerHasNoAccounts(t *testing.T) {
|
||||
alpine, err := system.For("alpine")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -559,3 +559,23 @@ func TestLingeringIsRefusedWhereTheServiceManagerHasNoAccounts(t *testing.T) {
|
||||
t.Fatalf("not refused: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestUserscope runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestUserscope(t *testing.T) {
|
||||
t.Run("AUserScopedUnitIsAppliedThroughTheAccountsManager", testAUserScopedUnitIsAppliedThroughTheAccountsManager)
|
||||
t.Run("ASystemUnitIsUntouchedByTheScope", testASystemUnitIsUntouchedByTheScope)
|
||||
t.Run("AUserUnitWaitsForItsAccountsManagerAndIsAppliedWhenItRuns", testAUserUnitWaitsForItsAccountsManagerAndIsAppliedWhenItRuns)
|
||||
t.Run("AWaitingUnitKeepsItsRecord", testAWaitingUnitKeepsItsRecord)
|
||||
t.Run("AManagerThatStopsDuringTheApplyIsWaitedFor", testAManagerThatStopsDuringTheApplyIsWaitedFor)
|
||||
t.Run("AUserUnitOfAnAccountTheMachineDoesNotHaveIsRefused", testAUserUnitOfAnAccountTheMachineDoesNotHaveIsRefused)
|
||||
t.Run("AUserUnitIsRefusedWhereTheServiceManagerHasNoAccounts", testAUserUnitIsRefusedWhereTheServiceManagerHasNoAccounts)
|
||||
t.Run("RemovingAUserUnitWithItsManagerAwayWaitsAndIsNeverFatal", testRemovingAUserUnitWithItsManagerAwayWaitsAndIsNeverFatal)
|
||||
t.Run("RemovingAUserUnitWhoseBusDoesNotAnswerIsNotFatal", testRemovingAUserUnitWhoseBusDoesNotAnswerIsNotFatal)
|
||||
t.Run("RemovingAUserUnitOfAnAccountThatIsGoneForgetsIt", testRemovingAUserUnitOfAnAccountThatIsGoneForgetsIt)
|
||||
t.Run("AUserUnitsFileTheMeshWroteMakesThatUnitAndNoOtherTheMeshs", testAUserUnitsFileTheMeshWroteMakesThatUnitAndNoOtherTheMeshs)
|
||||
t.Run("AMeshMadeUserUnitIsStoppedInItsAccountAndTheMachinesNamesakeIsNot", testAMeshMadeUserUnitIsStoppedInItsAccountAndTheMachinesNamesakeIsNot)
|
||||
t.Run("AServiceMovedIntoAnAccountGivesTheMachinesUnitBack", testAServiceMovedIntoAnAccountGivesTheMachinesUnitBack)
|
||||
t.Run("LingeringIsDeclaredOnTheAccountAndGivenBack", testLingeringIsDeclaredOnTheAccountAndGivenBack)
|
||||
t.Run("LingeringTheOperatorChangedSinceIsLeft", testLingeringTheOperatorChangedSinceIsLeft)
|
||||
t.Run("LingeringIsRefusedWhereTheServiceManagerHasNoAccounts", testLingeringIsRefusedWhereTheServiceManagerHasNoAccounts)
|
||||
}
|
||||
|
||||
@@ -50,7 +50,7 @@ func boxOpener(key identity.SealingKey) Unseal {
|
||||
return func(sealed string) ([]byte, error) { return key.Open(sealed) }
|
||||
}
|
||||
|
||||
func TestAFileTheVaultSealedToThisMachineIsOpenedAndWrittenUnreadableToOthers(t *testing.T) {
|
||||
func testAFileTheVaultSealedToThisMachineIsOpenedAndWrittenUnreadableToOthers(t *testing.T) {
|
||||
key, err := identity.GenerateSealingKey()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -78,7 +78,7 @@ func TestAFileTheVaultSealedToThisMachineIsOpenedAndWrittenUnreadableToOthers(t
|
||||
}
|
||||
}
|
||||
|
||||
func TestAVaultBoxSealedToAnotherMachineIsRefusedAndNothingWritten(t *testing.T) {
|
||||
func testAVaultBoxSealedToAnotherMachineIsRefusedAndNothingWritten(t *testing.T) {
|
||||
mine, _ := identity.GenerateSealingKey()
|
||||
theirs, _ := identity.GenerateSealingKey()
|
||||
path := t.TempDir() + "/broker"
|
||||
@@ -92,7 +92,7 @@ func TestAVaultBoxSealedToAnotherMachineIsRefusedAndNothingWritten(t *testing.T)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAVaultSealedFileSaysWhatIsInItOnce(t *testing.T) {
|
||||
func testAVaultSealedFileSaysWhatIsInItOnce(t *testing.T) {
|
||||
key, _ := identity.GenerateSealingKey()
|
||||
box, _ := json.Marshal(vaultSealedTo(t, key, "x"))
|
||||
for what, extra := range map[string]string{
|
||||
@@ -110,3 +110,10 @@ func TestAVaultSealedFileSaysWhatIsInItOnce(t *testing.T) {
|
||||
t.Error("a box of a version the SDK does not open was accepted")
|
||||
}
|
||||
}
|
||||
|
||||
// TestVaultSealed runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestVaultSealed(t *testing.T) {
|
||||
t.Run("AFileTheVaultSealedToThisMachineIsOpenedAndWrittenUnreadableToOthers", testAFileTheVaultSealedToThisMachineIsOpenedAndWrittenUnreadableToOthers)
|
||||
t.Run("AVaultBoxSealedToAnotherMachineIsRefusedAndNothingWritten", testAVaultBoxSealedToAnotherMachineIsRefusedAndNothingWritten)
|
||||
t.Run("AVaultSealedFileSaysWhatIsInItOnce", testAVaultSealedFileSaysWhatIsInItOnce)
|
||||
}
|
||||
|
||||
@@ -35,7 +35,7 @@ func declare(t *testing.T, resources string) *declaration.Declaration {
|
||||
return d
|
||||
}
|
||||
|
||||
func TestAFileMayBeBytesRatherThanText(t *testing.T) {
|
||||
func testAFileMayBeBytesRatherThanText(t *testing.T) {
|
||||
// A wallpaper, a font, an icon. Stored as its own encoding it would be a wallpaper nothing
|
||||
// can open.
|
||||
dir := t.TempDir()
|
||||
@@ -56,7 +56,7 @@ func TestAFileMayBeBytesRatherThanText(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAFileSaysWhatIsInItExactlyOnce(t *testing.T) {
|
||||
func testAFileSaysWhatIsInItExactlyOnce(t *testing.T) {
|
||||
// Three ways of saying it and no precedence between them, so "what is in this file" is
|
||||
// answerable by looking rather than by knowing which field wins.
|
||||
_, err := declaration.Parse([]byte(`{"declaration":1,"resources":[
|
||||
@@ -69,7 +69,7 @@ func TestAFileSaysWhatIsInItExactlyOnce(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestBytesThatAreNotBase64AreRefused(t *testing.T) {
|
||||
func testBytesThatAreNotBase64AreRefused(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
d := declare(t, `{"id":"w","type":"file","path":"`+dir+`/x","bytes":"not base64!!"}`)
|
||||
_, _, err := Apply(context.Background(), archHost(t), d, store.State{},
|
||||
@@ -118,7 +118,7 @@ func serving(t *testing.T, body []byte) string {
|
||||
return server.URL + "/theme.tar.gz"
|
||||
}
|
||||
|
||||
func TestAnArchiveIsUnpacked(t *testing.T) {
|
||||
func testAnArchiveIsUnpacked(t *testing.T) {
|
||||
body, digest := anArchive(t, map[string]string{
|
||||
"config/theme.conf": "dark", "config/icons/one.svg": "<svg/>",
|
||||
})
|
||||
@@ -143,7 +143,7 @@ func TestAnArchiveIsUnpacked(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnArchiveThatIsNotWhatWasDeclaredIsRefusedBeforeAnythingIsWritten(t *testing.T) {
|
||||
func testAnArchiveThatIsNotWhatWasDeclaredIsRefusedBeforeAnythingIsWritten(t *testing.T) {
|
||||
// The only thing making bytes from a network the mesh does not control safe to unpack is
|
||||
// that they hash to what was declared.
|
||||
body, _ := anArchive(t, map[string]string{"a": "b"})
|
||||
@@ -161,7 +161,7 @@ func TestAnArchiveThatIsNotWhatWasDeclaredIsRefusedBeforeAnythingIsWritten(t *te
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnArchiveCannotWriteOutsideWhereItWasUnpacked(t *testing.T) {
|
||||
func testAnArchiveCannotWriteOutsideWhereItWasUnpacked(t *testing.T) {
|
||||
// The oldest bug in unpacking. Checked against the resolved root rather than by looking for
|
||||
// "..", because there is more than one way to name a path that escapes.
|
||||
body, digest := anArchive(t, map[string]string{"../../escaped": "no"})
|
||||
@@ -182,7 +182,7 @@ func TestAnArchiveCannotWriteOutsideWhereItWasUnpacked(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnUnpackedArchiveIsNotFetchedAgainForNothing(t *testing.T) {
|
||||
func testAnUnpackedArchiveIsNotFetchedAgainForNothing(t *testing.T) {
|
||||
// The digest is the whole identity of an archive, so a matching record means the tree came
|
||||
// from these exact bytes. Applying twice must not report work.
|
||||
body, digest := anArchive(t, map[string]string{"a": "b"})
|
||||
@@ -211,7 +211,7 @@ func TestAnUnpackedArchiveIsNotFetchedAgainForNothing(t *testing.T) {
|
||||
// The archive is the one path where a symlink could arrive without anybody declaring it, which is
|
||||
// why the refusal lives here. ADR 0012 was earned by production data loss through a symlink
|
||||
// resolved inside a container volume path.
|
||||
func TestAnArchiveWithSomethingThatIsNotAFileIsRefused(t *testing.T) {
|
||||
func testAnArchiveWithSomethingThatIsNotAFileIsRefused(t *testing.T) {
|
||||
// A theme needing a symlink would otherwise arrive silently incomplete, and a device node in
|
||||
// an archive is not something to unpack quietly onto a machine.
|
||||
var raw bytes.Buffer
|
||||
@@ -240,7 +240,7 @@ func TestAnArchiveWithSomethingThatIsNotAFileIsRefused(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnArchiveMustBePinned(t *testing.T) {
|
||||
func testAnArchiveMustBePinned(t *testing.T) {
|
||||
_, err := declaration.Parse([]byte(`{"declaration":1,"resources":[
|
||||
{"id":"t","type":"archive","source":"https://example.invalid/a.tgz","path":"/opt/t"}]}`))
|
||||
if err == nil {
|
||||
@@ -255,7 +255,7 @@ func TestAnArchiveMustBePinned(t *testing.T) {
|
||||
//
|
||||
// The whole argument for widening the vocabulary is lifecycle — an action could create one and
|
||||
// nothing could ever take it away — so removal is the assertion that matters, not creation.
|
||||
func TestANetworkIsCreatedAndThenRemovedWhenNoLongerDeclared(t *testing.T) {
|
||||
func testANetworkIsCreatedAndThenRemovedWhenNoLongerDeclared(t *testing.T) {
|
||||
var calls []string
|
||||
there := map[string]bool{}
|
||||
run := func(_ context.Context, name string, args ...string) (string, error) {
|
||||
@@ -300,7 +300,7 @@ func TestANetworkIsCreatedAndThenRemovedWhenNoLongerDeclared(t *testing.T) {
|
||||
}
|
||||
|
||||
// A network is created once and left alone when it is already there.
|
||||
func TestANetworkAlreadyThereIsNotRebuilt(t *testing.T) {
|
||||
func testANetworkAlreadyThereIsNotRebuilt(t *testing.T) {
|
||||
var created int
|
||||
run := func(_ context.Context, name string, args ...string) (string, error) {
|
||||
args = oldShape(name, args)
|
||||
@@ -327,7 +327,7 @@ func TestANetworkAlreadyThereIsNotRebuilt(t *testing.T) {
|
||||
// JSON document cannot be handed a file that is entirely a token, and the mesh cannot compose the
|
||||
// document because it discarded the value. So the module supplies the document with a hole, the
|
||||
// mesh delivers the value sealed, and the host is the only thing that ever holds both.
|
||||
func TestASealedValueIsPutIntoTheFileThatNamesIt(t *testing.T) {
|
||||
func testASealedValueIsPutIntoTheFileThatNamesIt(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "settings.json")
|
||||
d := declare(t, `{"id":"settings","type":"file","path":"`+path+`",`+
|
||||
@@ -374,7 +374,7 @@ func TestASealedValueIsPutIntoTheFileThatNamesIt(t *testing.T) {
|
||||
// A declaration reaches a node over the broker and `env` is plain text in it, so a password there
|
||||
// is a password the broker sees. A sealed file arrives unreadable, the host writes it, and the
|
||||
// runtime reads it.
|
||||
func TestAContainerIsGivenItsEnvironmentFiles(t *testing.T) {
|
||||
func testAContainerIsGivenItsEnvironmentFiles(t *testing.T) {
|
||||
var ran []string
|
||||
run := func(_ context.Context, name string, args ...string) (string, error) {
|
||||
args = oldShape(name, args)
|
||||
@@ -410,7 +410,7 @@ func TestAContainerIsGivenItsEnvironmentFiles(t *testing.T) {
|
||||
// A container may name its resolvers and its own address — the shape a module shipping its own
|
||||
// validating DNS needs: the resolver pinned where its siblings can find it, the siblings pointed
|
||||
// at it. Both flags take addresses, so both reach the runtime verbatim.
|
||||
func TestAContainerIsGivenItsResolverAndItsAddress(t *testing.T) {
|
||||
func testAContainerIsGivenItsResolverAndItsAddress(t *testing.T) {
|
||||
var ran []string
|
||||
run := func(_ context.Context, name string, args ...string) (string, error) {
|
||||
args = oldShape(name, args)
|
||||
@@ -443,7 +443,7 @@ func TestAContainerIsGivenItsResolverAndItsAddress(t *testing.T) {
|
||||
// The resolver and address are part of the spec — a container whose dns or ip moved is a
|
||||
// different container, or the fields can never reach one that already runs. That is not
|
||||
// hypothetical: their first deployment compared equal and changed nothing.
|
||||
func TestAChangedResolverOrAddressIsAChangedContainer(t *testing.T) {
|
||||
func testAChangedResolverOrAddressIsAChangedContainer(t *testing.T) {
|
||||
base := &declaration.Container{ID: "c", Name: "x", Image: "a@sha256:00"}
|
||||
withDns := &declaration.Container{ID: "c", Name: "x", Image: "a@sha256:00", Dns: []string{"192.168.203.254"}}
|
||||
withIP := &declaration.Container{ID: "c", Name: "x", Image: "a@sha256:00", IP: "192.168.203.254"}
|
||||
@@ -455,3 +455,22 @@ func TestAChangedResolverOrAddressIsAChangedContainer(t *testing.T) {
|
||||
t.Error("adding an address did not change the spec, so it can never reach a running container")
|
||||
}
|
||||
}
|
||||
|
||||
// TestVocabulary runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestVocabulary(t *testing.T) {
|
||||
t.Run("AFileMayBeBytesRatherThanText", testAFileMayBeBytesRatherThanText)
|
||||
t.Run("AFileSaysWhatIsInItExactlyOnce", testAFileSaysWhatIsInItExactlyOnce)
|
||||
t.Run("BytesThatAreNotBase64AreRefused", testBytesThatAreNotBase64AreRefused)
|
||||
t.Run("AnArchiveIsUnpacked", testAnArchiveIsUnpacked)
|
||||
t.Run("AnArchiveThatIsNotWhatWasDeclaredIsRefusedBeforeAnythingIsWritten", testAnArchiveThatIsNotWhatWasDeclaredIsRefusedBeforeAnythingIsWritten)
|
||||
t.Run("AnArchiveCannotWriteOutsideWhereItWasUnpacked", testAnArchiveCannotWriteOutsideWhereItWasUnpacked)
|
||||
t.Run("AnUnpackedArchiveIsNotFetchedAgainForNothing", testAnUnpackedArchiveIsNotFetchedAgainForNothing)
|
||||
t.Run("AnArchiveWithSomethingThatIsNotAFileIsRefused", testAnArchiveWithSomethingThatIsNotAFileIsRefused)
|
||||
t.Run("AnArchiveMustBePinned", testAnArchiveMustBePinned)
|
||||
t.Run("ANetworkIsCreatedAndThenRemovedWhenNoLongerDeclared", testANetworkIsCreatedAndThenRemovedWhenNoLongerDeclared)
|
||||
t.Run("ANetworkAlreadyThereIsNotRebuilt", testANetworkAlreadyThereIsNotRebuilt)
|
||||
t.Run("ASealedValueIsPutIntoTheFileThatNamesIt", testASealedValueIsPutIntoTheFileThatNamesIt)
|
||||
t.Run("AContainerIsGivenItsEnvironmentFiles", testAContainerIsGivenItsEnvironmentFiles)
|
||||
t.Run("AContainerIsGivenItsResolverAndItsAddress", testAContainerIsGivenItsResolverAndItsAddress)
|
||||
t.Run("AChangedResolverOrAddressIsAChangedContainer", testAChangedResolverOrAddressIsAChangedContainer)
|
||||
}
|
||||
|
||||
@@ -34,7 +34,7 @@ func writtenOver(t *testing.T, content string, mode os.FileMode) (path string, s
|
||||
return path, state
|
||||
}
|
||||
|
||||
func TestAFileWrittenOverGetsItsKeptOriginalBackWhenUndeclared(t *testing.T) {
|
||||
func testAFileWrittenOverGetsItsKeptOriginalBackWhenUndeclared(t *testing.T) {
|
||||
path, state := writtenOver(t, pacmanFound, 0o640)
|
||||
rec, _ := state.Find(namesID)
|
||||
if rec.Kept == "" || rec.KeptMode != "0640" {
|
||||
@@ -63,7 +63,7 @@ func TestAFileWrittenOverGetsItsKeptOriginalBackWhenUndeclared(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAFileTheMeshMadeIsRemovedWhenUndeclared(t *testing.T) {
|
||||
func testAFileTheMeshMadeIsRemovedWhenUndeclared(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "pacman.conf")
|
||||
_, state := applyKeepingIn(t, wholeDecl(path, pacmanMesh), store.State{}, t.TempDir())
|
||||
if rec, _ := state.Find(namesID); rec.Kept != "" {
|
||||
@@ -78,7 +78,7 @@ func TestAFileTheMeshMadeIsRemovedWhenUndeclared(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAFileWrittenOverAndChangedSinceIsLeftAsItStands(t *testing.T) {
|
||||
func testAFileWrittenOverAndChangedSinceIsLeftAsItStands(t *testing.T) {
|
||||
path, state := writtenOver(t, pacmanFound, 0o644)
|
||||
edited := pacmanMesh + "IgnorePkg = linux\n"
|
||||
if err := os.WriteFile(path, []byte(edited), 0o644); err != nil {
|
||||
@@ -95,7 +95,7 @@ func TestAFileWrittenOverAndChangedSinceIsLeftAsItStands(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAFileWhoseKeptOriginalIsMissingIsLeftAndSaysSo(t *testing.T) {
|
||||
func testAFileWhoseKeptOriginalIsMissingIsLeftAndSaysSo(t *testing.T) {
|
||||
path, state := writtenOver(t, pacmanFound, 0o644)
|
||||
rec, _ := state.Find(namesID)
|
||||
if err := os.Remove(rec.Kept); err != nil {
|
||||
@@ -111,7 +111,7 @@ func TestAFileWhoseKeptOriginalIsMissingIsLeftAndSaysSo(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAFileWrittenOverAndDeletedSinceIsNotBroughtBack(t *testing.T) {
|
||||
func testAFileWrittenOverAndDeletedSinceIsNotBroughtBack(t *testing.T) {
|
||||
path, state := writtenOver(t, pacmanFound, 0o644)
|
||||
if err := os.Remove(path); err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -125,7 +125,7 @@ func TestAFileWrittenOverAndDeletedSinceIsNotBroughtBack(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAFileWhosePathMovedIsNeverGivenTheOldPathsOriginal(t *testing.T) {
|
||||
func testAFileWhosePathMovedIsNeverGivenTheOldPathsOriginal(t *testing.T) {
|
||||
// The old path's original stays with the old path's record; the new path keeps its own.
|
||||
oldPath, state := writtenOver(t, pacmanFound, 0o644)
|
||||
newPath := filepath.Join(filepath.Dir(oldPath), "pacman.d.conf")
|
||||
@@ -151,7 +151,7 @@ func TestAFileWhosePathMovedIsNeverGivenTheOldPathsOriginal(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestARecordFromBeforeTheModeWasKeptPutsTheOriginalBackAsTheFileStands(t *testing.T) {
|
||||
func testARecordFromBeforeTheModeWasKeptPutsTheOriginalBackAsTheFileStands(t *testing.T) {
|
||||
path, state := writtenOver(t, pacmanFound, 0o644)
|
||||
for i := range state.Resources {
|
||||
state.Resources[i].KeptMode, state.Resources[i].KeptOwner = "", ""
|
||||
@@ -171,3 +171,14 @@ func TestARecordFromBeforeTheModeWasKeptPutsTheOriginalBackAsTheFileStands(t *te
|
||||
t.Errorf("reported as %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestWhole runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestWhole(t *testing.T) {
|
||||
t.Run("AFileWrittenOverGetsItsKeptOriginalBackWhenUndeclared", testAFileWrittenOverGetsItsKeptOriginalBackWhenUndeclared)
|
||||
t.Run("AFileTheMeshMadeIsRemovedWhenUndeclared", testAFileTheMeshMadeIsRemovedWhenUndeclared)
|
||||
t.Run("AFileWrittenOverAndChangedSinceIsLeftAsItStands", testAFileWrittenOverAndChangedSinceIsLeftAsItStands)
|
||||
t.Run("AFileWhoseKeptOriginalIsMissingIsLeftAndSaysSo", testAFileWhoseKeptOriginalIsMissingIsLeftAndSaysSo)
|
||||
t.Run("AFileWrittenOverAndDeletedSinceIsNotBroughtBack", testAFileWrittenOverAndDeletedSinceIsNotBroughtBack)
|
||||
t.Run("AFileWhosePathMovedIsNeverGivenTheOldPathsOriginal", testAFileWhosePathMovedIsNeverGivenTheOldPathsOriginal)
|
||||
t.Run("ARecordFromBeforeTheModeWasKeptPutsTheOriginalBackAsTheFileStands", testARecordFromBeforeTheModeWasKeptPutsTheOriginalBackAsTheFileStands)
|
||||
}
|
||||
|
||||
@@ -26,7 +26,7 @@ table inet mesh_guard {
|
||||
}
|
||||
`
|
||||
|
||||
func TestTheGuardIsExactlyThisTable(t *testing.T) {
|
||||
func testTheGuardIsExactlyThisTable(t *testing.T) {
|
||||
if got := AsGuard([]int{15672, 5432}); got != goldenGuard {
|
||||
t.Fatalf("the guard changed:\n%s", got)
|
||||
}
|
||||
@@ -52,13 +52,13 @@ ExecStop=nft delete table inet mesh_guard
|
||||
WantedBy=multi-user.target
|
||||
`
|
||||
|
||||
func TestTheGuardUnitIsExactlyThisUnit(t *testing.T) {
|
||||
func testTheGuardUnitIsExactlyThisUnit(t *testing.T) {
|
||||
if got := guardUnitText(); got != goldenGuardUnit {
|
||||
t.Fatalf("the guard's unit changed:\n%s", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTheGuardRefusesOnlyWhatIsAddressedToThisMachine(t *testing.T) {
|
||||
func testTheGuardRefusesOnlyWhatIsAddressedToThisMachine(t *testing.T) {
|
||||
// A machine that routes for others — a predecessor's private-network hub — must not have a
|
||||
// packet for another machine's database port refused (novox/hq ADR 0103).
|
||||
for _, line := range strings.Split(AsGuard([]int{5432}), "\n") {
|
||||
@@ -68,7 +68,7 @@ func TestTheGuardRefusesOnlyWhatIsAddressedToThisMachine(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnAdoptedBundleLoadsNoDroppingTableAndExactlyTheGuard(t *testing.T) {
|
||||
func testAnAdoptedBundleLoadsNoDroppingTableAndExactlyTheGuard(t *testing.T) {
|
||||
r := producedBundle(t)
|
||||
p := FoundationPorts{Store: 5433}
|
||||
if _, err := RewritePorts(&r, p, ""); err != nil {
|
||||
@@ -133,7 +133,7 @@ func TestAnAdoptedBundleLoadsNoDroppingTableAndExactlyTheGuard(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAConvergedBundleIsNotMadeAnAdoptedOne(t *testing.T) {
|
||||
func testAConvergedBundleIsNotMadeAnAdoptedOne(t *testing.T) {
|
||||
// The converged genesis keeps the foundation's filter, byte for byte (novox/hq ADR 0088).
|
||||
r := producedBundle(t)
|
||||
for _, res := range r.Declaration.Resources {
|
||||
@@ -146,7 +146,7 @@ func TestAConvergedBundleIsNotMadeAnAdoptedOne(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnAdoptedGenesisTakesTheMeshsOwnModulesBeforePushingThem(t *testing.T) {
|
||||
func testAnAdoptedGenesisTakesTheMeshsOwnModulesBeforePushingThem(t *testing.T) {
|
||||
t.Setenv("TMPDIR", t.TempDir())
|
||||
for _, c := range []struct {
|
||||
module string
|
||||
@@ -171,7 +171,7 @@ func TestAnAdoptedGenesisTakesTheMeshsOwnModulesBeforePushingThem(t *testing.T)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAConvergedGenesisTakesNothing(t *testing.T) {
|
||||
func testAConvergedGenesisTakesNothing(t *testing.T) {
|
||||
t.Setenv("TMPDIR", t.TempDir())
|
||||
rec := &controlRecorder{settings: map[string]string{}}
|
||||
control := controlPlane{container: "temp-mesh-controller", run: rec.run, timeout: time.Second}
|
||||
@@ -184,7 +184,7 @@ func TestAConvergedGenesisTakesNothing(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnAdoptedGenesisOpensTheRegistryFromAnywhere(t *testing.T) {
|
||||
func testAnAdoptedGenesisOpensTheRegistryFromAnywhere(t *testing.T) {
|
||||
t.Setenv("TMPDIR", t.TempDir())
|
||||
rec := &controlRecorder{settings: map[string]string{}}
|
||||
control := controlPlane{container: "temp-mesh-controller", run: rec.run, timeout: time.Second}
|
||||
@@ -197,7 +197,7 @@ func TestAnAdoptedGenesisOpensTheRegistryFromAnywhere(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnAdoptedGenesisChoosesTheFilterAndLoadsNone(t *testing.T) {
|
||||
func testAnAdoptedGenesisChoosesTheFilterAndLoadsNone(t *testing.T) {
|
||||
rec := &controlRecorder{settings: map[string]string{}}
|
||||
control := controlPlane{container: "mesh-controller", run: rec.run, timeout: time.Second}
|
||||
o := Options{Node: "anchor", Adopted: true, Answers: map[string]string{"packet-filter": "nftables"}}
|
||||
@@ -210,7 +210,7 @@ func TestAnAdoptedGenesisChoosesTheFilterAndLoadsNone(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnAdoptedNodeIsRecordedAdopted(t *testing.T) {
|
||||
func testAnAdoptedNodeIsRecordedAdopted(t *testing.T) {
|
||||
stop := errors.New("stop here")
|
||||
runtime := &asked{answer: func(name string, args []string) (string, error) {
|
||||
joined := strings.Join(args, " ")
|
||||
@@ -231,3 +231,17 @@ func TestAnAdoptedNodeIsRecordedAdopted(t *testing.T) {
|
||||
t.Errorf("the node was not added adopted: %v", runtime.commands)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAdopted runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestAdopted(t *testing.T) {
|
||||
t.Run("TheGuardIsExactlyThisTable", testTheGuardIsExactlyThisTable)
|
||||
t.Run("TheGuardUnitIsExactlyThisUnit", testTheGuardUnitIsExactlyThisUnit)
|
||||
t.Run("TheGuardRefusesOnlyWhatIsAddressedToThisMachine", testTheGuardRefusesOnlyWhatIsAddressedToThisMachine)
|
||||
t.Run("AnAdoptedBundleLoadsNoDroppingTableAndExactlyTheGuard", testAnAdoptedBundleLoadsNoDroppingTableAndExactlyTheGuard)
|
||||
t.Run("AConvergedBundleIsNotMadeAnAdoptedOne", testAConvergedBundleIsNotMadeAnAdoptedOne)
|
||||
t.Run("AnAdoptedGenesisTakesTheMeshsOwnModulesBeforePushingThem", testAnAdoptedGenesisTakesTheMeshsOwnModulesBeforePushingThem)
|
||||
t.Run("AConvergedGenesisTakesNothing", testAConvergedGenesisTakesNothing)
|
||||
t.Run("AnAdoptedGenesisOpensTheRegistryFromAnywhere", testAnAdoptedGenesisOpensTheRegistryFromAnywhere)
|
||||
t.Run("AnAdoptedGenesisChoosesTheFilterAndLoadsNone", testAnAdoptedGenesisChoosesTheFilterAndLoadsNone)
|
||||
t.Run("AnAdoptedNodeIsRecordedAdopted", testAnAdoptedNodeIsRecordedAdopted)
|
||||
}
|
||||
|
||||
@@ -20,7 +20,7 @@ import (
|
||||
// is the one it claims to be, by asking its package database about a package that is certainly
|
||||
// there. Getting this wrong installs with the wrong package manager and the wrong unit names.
|
||||
|
||||
func TestTheMachineIsAskedWhichSystemItIs(t *testing.T) {
|
||||
func testTheMachineIsAskedWhichSystemItIs(t *testing.T) {
|
||||
// Only pacman answers, so this is the arch host and nothing had to be told so.
|
||||
onlyPacman := func(_ context.Context, name string, _ ...string) (string, error) {
|
||||
if name == "pacman" {
|
||||
@@ -40,7 +40,7 @@ func TestTheMachineIsAskedWhichSystemItIs(t *testing.T) {
|
||||
|
||||
// A machine that is none of them is refused with what each of them said. "Unsupported system" is
|
||||
// a sentence nobody can act on; "pacman does not answer here" is.
|
||||
func TestAMachineThatIsNoneOfThemIsRefusedWithWhatEachSaid(t *testing.T) {
|
||||
func testAMachineThatIsNoneOfThemIsRefusedWithWhatEachSaid(t *testing.T) {
|
||||
nothing := func(context.Context, string, ...string) (string, error) {
|
||||
return "", errors.New("command not found")
|
||||
}
|
||||
@@ -58,7 +58,7 @@ func TestAMachineThatIsNoneOfThemIsRefusedWithWhatEachSaid(t *testing.T) {
|
||||
|
||||
// And a machine that was TOLD what it is still has to prove it. Installing the arch half of the
|
||||
// host on Alpine must say so once, at the start, rather than failing later inside pacman.
|
||||
func TestASystemThatWasNamedIsStillProved(t *testing.T) {
|
||||
func testASystemThatWasNamedIsStillProved(t *testing.T) {
|
||||
onlyApk := func(_ context.Context, name string, _ ...string) (string, error) {
|
||||
if name == "apk" {
|
||||
return "apk-tools-2.14.0\n", nil
|
||||
@@ -75,7 +75,7 @@ func TestASystemThatWasNamedIsStillProved(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestASystemNobodyHasBuiltIsRefusedByName(t *testing.T) {
|
||||
func testASystemNobodyHasBuiltIsRefusedByName(t *testing.T) {
|
||||
anything := func(context.Context, string, ...string) (string, error) { return "", nil }
|
||||
_, err := WorkOutSystem(context.Background(), anything, "debian")
|
||||
if err == nil {
|
||||
@@ -88,7 +88,7 @@ func TestASystemNobodyHasBuiltIsRefusedByName(t *testing.T) {
|
||||
|
||||
// A foundation is applied before any mesh exists, so it can carry no secret the mesh sealed — there
|
||||
// is no key to open one with. Refused with a sentence rather than a nil dereference.
|
||||
func TestASealedFileInAFoundationIsRefusedWithAReason(t *testing.T) {
|
||||
func testASealedFileInAFoundationIsRefusedWithAReason(t *testing.T) {
|
||||
_, err := refuseSealed("anything")
|
||||
if err == nil {
|
||||
t.Fatal("a sealed file in a foundation bundle was accepted")
|
||||
@@ -100,7 +100,7 @@ func TestASealedFileInAFoundationIsRefusedWithAReason(t *testing.T) {
|
||||
|
||||
// Defends novox/hq ADR 0100: the carried bundle keeps the original of a file it writes over that
|
||||
// the host has no record of — the distribution's own ruleset, say.
|
||||
func TestTheBundleKeepsTheOriginalOfWhatItWritesOver(t *testing.T) {
|
||||
func testTheBundleKeepsTheOriginalOfWhatItWritesOver(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
conf := filepath.Join(dir, "nftables.conf")
|
||||
if err := os.WriteFile(conf, []byte("# the distribution's own\n"), 0o644); err != nil {
|
||||
@@ -134,7 +134,7 @@ func TestTheBundleKeepsTheOriginalOfWhatItWritesOver(t *testing.T) {
|
||||
// Defends novox/hq issue 104: genesis consumes the bundle, recording the digest of what it applied
|
||||
// and the mode the operator raised the machine in, so the host's own `reconcile` never applies the
|
||||
// carried bytes over it.
|
||||
func TestGenesisConsumesTheBundleAndRecordsTheMode(t *testing.T) {
|
||||
func testGenesisConsumesTheBundleAndRecordsTheMode(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
raw := []byte(`{"declaration":1,"resources":[
|
||||
{"id":"a","type":"file","path":"` + filepath.Join(dir, "a.conf") + `","content":"x\n"}]}`)
|
||||
@@ -180,3 +180,14 @@ func TestGenesisConsumesTheBundleAndRecordsTheMode(t *testing.T) {
|
||||
t.Errorf("a genesis re-run set the mode back to %q over the mesh's converged", known.Mode)
|
||||
}
|
||||
}
|
||||
|
||||
// TestApply runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestApply(t *testing.T) {
|
||||
t.Run("TheMachineIsAskedWhichSystemItIs", testTheMachineIsAskedWhichSystemItIs)
|
||||
t.Run("AMachineThatIsNoneOfThemIsRefusedWithWhatEachSaid", testAMachineThatIsNoneOfThemIsRefusedWithWhatEachSaid)
|
||||
t.Run("ASystemThatWasNamedIsStillProved", testASystemThatWasNamedIsStillProved)
|
||||
t.Run("ASystemNobodyHasBuiltIsRefusedByName", testASystemNobodyHasBuiltIsRefusedByName)
|
||||
t.Run("ASealedFileInAFoundationIsRefusedWithAReason", testASealedFileInAFoundationIsRefusedWithAReason)
|
||||
t.Run("TheBundleKeepsTheOriginalOfWhatItWritesOver", testTheBundleKeepsTheOriginalOfWhatItWritesOver)
|
||||
t.Run("GenesisConsumesTheBundleAndRecordsTheMode", testGenesisConsumesTheBundleAndRecordsTheMode)
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ import (
|
||||
// **Exercised rather than assumed.** This is the refusal that stands between a person and a
|
||||
// machine left holding a store, a broker and no control plane — the failure the whole preflight
|
||||
// exists to prevent — and a refusal nothing tests is a refusal nobody has read.
|
||||
func TestAnInstallerWithNothingToBuildRefuses(t *testing.T) {
|
||||
func testAnInstallerWithNothingToBuildRefuses(t *testing.T) {
|
||||
err := Source{}.Check()
|
||||
if err == nil {
|
||||
t.Fatal("a source naming no repository was accepted; nothing would have been built")
|
||||
@@ -24,7 +24,7 @@ func TestAnInstallerWithNothingToBuildRefuses(t *testing.T) {
|
||||
}
|
||||
|
||||
// A repository without a commit refuses too, because a branch is somebody else's moving target.
|
||||
func TestABranchIsNotACommit(t *testing.T) {
|
||||
func testABranchIsNotACommit(t *testing.T) {
|
||||
err := Source{Repository: "https://example.invalid/mesh-controller.git"}.Check()
|
||||
if err == nil {
|
||||
t.Fatal("a source with no ref was accepted; genesis would have built whatever a branch pointed at")
|
||||
@@ -35,7 +35,7 @@ func TestABranchIsNotACommit(t *testing.T) {
|
||||
}
|
||||
|
||||
// And a repository with a commit is enough.
|
||||
func TestARepositoryAndACommitIsEnough(t *testing.T) {
|
||||
func testARepositoryAndACommitIsEnough(t *testing.T) {
|
||||
if err := (Source{Repository: "https://example.invalid/mesh-controller.git", Ref: "a1b2c3d4"}).Check(); err != nil {
|
||||
t.Fatalf("a repository and a commit were refused: %v", err)
|
||||
}
|
||||
@@ -46,7 +46,7 @@ func TestARepositoryAndACommitIsEnough(t *testing.T) {
|
||||
// it rebuilds the control plane from source, and a copy in the catalogue, which genesis read — and
|
||||
// nothing kept them equal (novox/hq 04-ISSUES/072). The builder already reports the manifest it
|
||||
// built, artifact resolved to the image; genesis takes it from there and reads no second copy.
|
||||
func TestTheBuildHandsOverTheManifestTheMeshWillHold(t *testing.T) {
|
||||
func testTheBuildHandsOverTheManifestTheMeshWillHold(t *testing.T) {
|
||||
manifest := `{"module":"mesh-controller","version":"1","resources":[` +
|
||||
`{"id":"server","type":"container","name":"mesh-controller","image":"` + builtImage + `"}]}`
|
||||
runtime := &asked{answer: aRepository(t, imageFormManifest, func(string, []string) (string, error) {
|
||||
@@ -68,7 +68,7 @@ func TestTheBuildHandsOverTheManifestTheMeshWillHold(t *testing.T) {
|
||||
|
||||
// A result without a manifest is a build the installer cannot finish, and it is refused beside the
|
||||
// builder that said it rather than at step 9 with a message about a missing file.
|
||||
func TestABuildReportingNoManifestIsRefused(t *testing.T) {
|
||||
func testABuildReportingNoManifestIsRefused(t *testing.T) {
|
||||
runtime := &asked{answer: aRepository(t, imageFormManifest, func(string, []string) (string, error) {
|
||||
return `{"module":"mesh-controller","commit":"a1b2c3d4",` +
|
||||
`"made":[{"name":"server","kind":"image","reference":"` + builtImage + `"}]}`, nil
|
||||
@@ -81,7 +81,7 @@ func TestABuildReportingNoManifestIsRefused(t *testing.T) {
|
||||
}
|
||||
|
||||
// And a manifest that does not name the image the build produced describes some other build.
|
||||
func TestABuildWhoseManifestNamesAnotherImageIsRefused(t *testing.T) {
|
||||
func testABuildWhoseManifestNamesAnotherImageIsRefused(t *testing.T) {
|
||||
runtime := &asked{answer: aRepository(t, imageFormManifest, func(string, []string) (string, error) {
|
||||
return `{"module":"mesh-controller","commit":"a1b2c3d4","manifest":{"module":"mesh-controller",` +
|
||||
`"resources":[{"id":"server","type":"container","image":"sha256:` + strings.Repeat("9", 64) + `"}]},` +
|
||||
@@ -93,3 +93,13 @@ func TestABuildWhoseManifestNamesAnotherImageIsRefused(t *testing.T) {
|
||||
t.Fatalf("a manifest naming another image was accepted, or refused for another reason: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestBuild runs this file's tests, each a subtest named as its function was (design 47 H2 §819, the test budget).
|
||||
func TestBuild(t *testing.T) {
|
||||
t.Run("AnInstallerWithNothingToBuildRefuses", testAnInstallerWithNothingToBuildRefuses)
|
||||
t.Run("ABranchIsNotACommit", testABranchIsNotACommit)
|
||||
t.Run("ARepositoryAndACommitIsEnough", testARepositoryAndACommitIsEnough)
|
||||
t.Run("TheBuildHandsOverTheManifestTheMeshWillHold", testTheBuildHandsOverTheManifestTheMeshWillHold)
|
||||
t.Run("ABuildReportingNoManifestIsRefused", testABuildReportingNoManifestIsRefused)
|
||||
t.Run("ABuildWhoseManifestNamesAnotherImageIsRefused", testABuildWhoseManifestNamesAnotherImageIsRefused)
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user