diff --git a/blueprints/cis/cis_darwin.go b/blueprints/cis/cis_darwin.go index 2ce54cb..beb2315 100644 --- a/blueprints/cis/cis_darwin.go +++ b/blueprints/cis/cis_darwin.go @@ -2,7 +2,10 @@ package cis -import "github.com/TsekNet/converge/dsl" +import ( + "github.com/TsekNet/converge/condition" + "github.com/TsekNet/converge/dsl" +) // DarwinCIS enforces CIS macOS L1 benchmark settings. // Based on CIS Apple macOS 26 Tahoe v1.0.0 L1 (90 items). @@ -40,12 +43,12 @@ func cisFirewall(r *dsl.Run) { r.Exec("enable-firewall", dsl.ExecOpts{ Command: "/usr/libexec/ApplicationFirewall/socketfilterfw", Args: []string{"--setglobalstate", "on"}, - OnlyIf: "/usr/libexec/ApplicationFirewall/socketfilterfw --getglobalstate | grep -q enabled", + Condition: condition.Shell("/usr/libexec/ApplicationFirewall/socketfilterfw --getglobalstate | grep -q enabled"), }) r.Exec("enable-stealth", dsl.ExecOpts{ Command: "/usr/libexec/ApplicationFirewall/socketfilterfw", Args: []string{"--setstealthmode", "on"}, - OnlyIf: "/usr/libexec/ApplicationFirewall/socketfilterfw --getstealthmode | grep -q enabled", + Condition: condition.Shell("/usr/libexec/ApplicationFirewall/socketfilterfw --getstealthmode | grep -q enabled"), }) } @@ -66,12 +69,12 @@ func cisSharing(r *dsl.Run) { r.Exec("disable-remote-login", dsl.ExecOpts{ Command: "launchctl", Args: []string{"disable", "system/com.apple.sshd"}, - OnlyIf: "launchctl print system/com.apple.sshd 2>/dev/null | grep -q 'state = disabled'", + Condition: condition.Shell("launchctl print system/com.apple.sshd 2>/dev/null | grep -q 'state = disabled'"), }) r.Exec("disable-remote-management", dsl.ExecOpts{ Command: "launchctl", Args: []string{"disable", "system/com.apple.remotemanagement"}, - OnlyIf: "launchctl print system/com.apple.remotemanagement 2>/dev/null | grep -q 'state = disabled'", + Condition: condition.Shell("launchctl print system/com.apple.remotemanagement 2>/dev/null | grep -q 'state = disabled'"), }) r.Exec("disable-remote-apple-events", dsl.ExecOpts{ Command: "launchctl", @@ -84,7 +87,7 @@ func cisSharing(r *dsl.Run) { r.Exec("enable-time-service", dsl.ExecOpts{ Command: "systemsetup", Args: []string{"-setusingnetworktime", "on"}, - OnlyIf: "systemsetup -getusingnetworktime | grep -q 'On'", + Condition: condition.Shell("systemsetup -getusingnetworktime | grep -q 'On'"), }) } @@ -126,18 +129,18 @@ func cisSecurity(r *dsl.Run) { r.Exec("enable-gatekeeper", dsl.ExecOpts{ Command: "spctl", Args: []string{"--master-enable"}, - OnlyIf: "spctl --status 2>&1 | grep -q enabled", + Condition: condition.Shell("spctl --status 2>&1 | grep -q enabled"), }) r.Exec("check-filevault", dsl.ExecOpts{ Command: "fdesetup", Args: []string{"status"}, - OnlyIf: "fdesetup status | grep -q 'FileVault is On'", + Condition: condition.Shell("fdesetup status | grep -q 'FileVault is On'"), }) // CIS 2.6.8: require admin password for system-wide preference changes r.Exec("require-admin-for-system-prefs", dsl.ExecOpts{ Command: "security", Args: []string{"authorizationdb", "write", "system.preferences", "authenticate-admin"}, - OnlyIf: "security authorizationdb read system.preferences 2>/dev/null | grep -q authenticate-admin", + Condition: condition.Shell("security authorizationdb read system.preferences 2>/dev/null | grep -q authenticate-admin"), }) // CIS 2.13.x: disable guest account and guest access to shares r.Plist("com.apple.loginwindow", dsl.PlistOpts{Key: "GuestEnabled", Value: false, Type: "bool", Host: true}) @@ -165,12 +168,12 @@ func cisMisc(r *dsl.Run) { r.Exec("disable-powernap", dsl.ExecOpts{ Command: "pmset", Args: []string{"-a", "powernap", "0"}, - OnlyIf: "pmset -g | grep -q 'powernap.*0'", + Condition: condition.Shell("pmset -g | grep -q 'powernap.*0'"), }) r.Exec("disable-wake-network", dsl.ExecOpts{ Command: "pmset", Args: []string{"-a", "womp", "0"}, - OnlyIf: "pmset -g | grep -q 'womp.*0'", + Condition: condition.Shell("pmset -g | grep -q 'womp.*0'"), }) r.Plist("com.apple.NetworkBrowser", dsl.PlistOpts{Key: "DisableAirDrop", Value: true, Type: "bool", Host: true}) r.Plist("com.apple.controlcenter", dsl.PlistOpts{Key: "AirplayRecieverEnabled", Value: false, Type: "bool", Host: true}) diff --git a/blueprints/linux_server.go b/blueprints/linux_server.go index 7f1a19c..76e416d 100644 --- a/blueprints/linux_server.go +++ b/blueprints/linux_server.go @@ -14,13 +14,13 @@ func LinuxServer(r *dsl.Run) { "X11Forwarding no\n" + "MaxAuthTries 3\n", Mode: 0600, - Meta: dsl.Meta{Critical: true}, + Critical: true, }) r.Service("sshd", dsl.ServiceOpts{ State: dsl.Running, Enable: true, - Meta: dsl.Meta{Critical: true}, + Critical: true, }) r.Package("fail2ban", dsl.PackageOpts{State: dsl.Present}) diff --git a/condition/combinators.go b/condition/combinators.go new file mode 100644 index 0000000..bd87108 --- /dev/null +++ b/condition/combinators.go @@ -0,0 +1,216 @@ +package condition + +import ( + "context" + "fmt" + "strings" + "time" + + "github.com/TsekNet/converge/extensions" +) + +// All returns a Condition that is met when every sub-condition is met. +// Wait blocks until all sub-conditions are met (checked sequentially). +func All(conditions ...extensions.Condition) extensions.Condition { + return &allCondition{conditions: conditions} +} + +// Any returns a Condition that is met when at least one sub-condition is met. +func Any(conditions ...extensions.Condition) extensions.Condition { + return &anyCondition{conditions: conditions} +} + +// Not returns a Condition that inverts another: met when inner is not met. +func Not(inner extensions.Condition) extensions.Condition { + return ¬Condition{inner: inner} +} + +// ResourceIDs extracts all resource dependency IDs from a Condition tree. +// Used by the DSL to convert condition.Resource entries into DAG edges. +func ResourceIDs(c extensions.Condition) []string { + var ids []string + collectResourceIDs(c, &ids) + return ids +} + +// StripResources returns a new Condition with all Resource conditions removed. +// If only Resource conditions remain, returns nil (no runtime condition needed). +func StripResources(c extensions.Condition) extensions.Condition { + return stripResources(c) +} + +// --- allCondition --- + +type allCondition struct { + conditions []extensions.Condition +} + +func (c *allCondition) Met(ctx context.Context) (bool, error) { + for _, sub := range c.conditions { + met, err := sub.Met(ctx) + if err != nil { + return false, err + } + if !met { + return false, nil + } + } + return true, nil +} + +func (c *allCondition) Wait(ctx context.Context) error { + for _, sub := range c.conditions { + if err := sub.Wait(ctx); err != nil { + return err + } + } + return nil +} + +func (c *allCondition) String() string { + parts := make([]string, len(c.conditions)) + for i, sub := range c.conditions { + parts[i] = sub.String() + } + return fmt.Sprintf("all(%s)", strings.Join(parts, ", ")) +} + +// --- anyCondition --- + +type anyCondition struct { + conditions []extensions.Condition +} + +func (c *anyCondition) Met(ctx context.Context) (bool, error) { + for _, sub := range c.conditions { + met, err := sub.Met(ctx) + if err != nil { + return false, err + } + if met { + return true, nil + } + } + return false, nil +} + +func (c *anyCondition) Wait(ctx context.Context) error { + // Poll until any sub-condition is met. + ticker := time.NewTicker(2 * time.Second) + defer ticker.Stop() + for { + for _, sub := range c.conditions { + if met, _ := sub.Met(ctx); met { + return nil + } + } + select { + case <-ctx.Done(): + return ctx.Err() + case <-ticker.C: + } + } +} + +func (c *anyCondition) String() string { + parts := make([]string, len(c.conditions)) + for i, sub := range c.conditions { + parts[i] = sub.String() + } + return fmt.Sprintf("any(%s)", strings.Join(parts, ", ")) +} + +// --- notCondition --- + +type notCondition struct { + inner extensions.Condition +} + +func (c *notCondition) Met(ctx context.Context) (bool, error) { + met, err := c.inner.Met(ctx) + if err != nil { + return false, err + } + return !met, nil +} + +func (c *notCondition) Wait(ctx context.Context) error { + // Poll until the inner condition is NOT met. + ticker := time.NewTicker(2 * time.Second) + defer ticker.Stop() + for { + if met, _ := c.inner.Met(ctx); !met { + return nil + } + select { + case <-ctx.Done(): + return ctx.Err() + case <-ticker.C: + } + } +} + +func (c *notCondition) String() string { + return fmt.Sprintf("not(%s)", c.inner.String()) +} + +// --- tree helpers --- + +func collectResourceIDs(c extensions.Condition, ids *[]string) { + switch v := c.(type) { + case *resourceCondition: + *ids = append(*ids, v.id) + case *allCondition: + for _, sub := range v.conditions { + collectResourceIDs(sub, ids) + } + case *anyCondition: + for _, sub := range v.conditions { + collectResourceIDs(sub, ids) + } + case *notCondition: + collectResourceIDs(v.inner, ids) + } +} + +func stripResources(c extensions.Condition) extensions.Condition { + switch v := c.(type) { + case *resourceCondition: + return nil + case *allCondition: + var kept []extensions.Condition + for _, sub := range v.conditions { + if stripped := stripResources(sub); stripped != nil { + kept = append(kept, stripped) + } + } + if len(kept) == 0 { + return nil + } + if len(kept) == 1 { + return kept[0] + } + return &allCondition{conditions: kept} + case *anyCondition: + var kept []extensions.Condition + for _, sub := range v.conditions { + if stripped := stripResources(sub); stripped != nil { + kept = append(kept, stripped) + } + } + if len(kept) == 0 { + return nil + } + if len(kept) == 1 { + return kept[0] + } + return &anyCondition{conditions: kept} + case *notCondition: + if stripped := stripResources(v.inner); stripped != nil { + return ¬Condition{inner: stripped} + } + return nil + default: + return c + } +} diff --git a/condition/combinators_test.go b/condition/combinators_test.go new file mode 100644 index 0000000..564252b --- /dev/null +++ b/condition/combinators_test.go @@ -0,0 +1,214 @@ +package condition + +import ( + "context" + "testing" + + "github.com/TsekNet/converge/extensions" +) + +// staticCondition is a test helper that returns a fixed value. +type staticCondition struct { + met bool + str string +} + +func (s *staticCondition) Met(_ context.Context) (bool, error) { return s.met, nil } +func (s *staticCondition) Wait(_ context.Context) error { return nil } +func (s *staticCondition) String() string { return s.str } + +func met(name string) extensions.Condition { return &staticCondition{met: true, str: name} } +func unmet(name string) extensions.Condition { return &staticCondition{met: false, str: name} } + +func TestAll(t *testing.T) { + ctx := context.Background() + + tests := []struct { + name string + conds []extensions.Condition + wantMet bool + }{ + {"all met", []extensions.Condition{met("a"), met("b")}, true}, + {"one unmet", []extensions.Condition{met("a"), unmet("b")}, false}, + {"all unmet", []extensions.Condition{unmet("a"), unmet("b")}, false}, + {"single met", []extensions.Condition{met("a")}, true}, + {"empty", nil, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + c := All(tt.conds...) + got, err := c.Met(ctx) + if err != nil { + t.Fatalf("Met() error = %v", err) + } + if got != tt.wantMet { + t.Errorf("Met() = %v, want %v", got, tt.wantMet) + } + }) + } +} + +func TestAny(t *testing.T) { + ctx := context.Background() + + tests := []struct { + name string + conds []extensions.Condition + wantMet bool + }{ + {"all met", []extensions.Condition{met("a"), met("b")}, true}, + {"one met", []extensions.Condition{unmet("a"), met("b")}, true}, + {"all unmet", []extensions.Condition{unmet("a"), unmet("b")}, false}, + {"single met", []extensions.Condition{met("a")}, true}, + {"empty", nil, false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + c := Any(tt.conds...) + got, err := c.Met(ctx) + if err != nil { + t.Fatalf("Met() error = %v", err) + } + if got != tt.wantMet { + t.Errorf("Met() = %v, want %v", got, tt.wantMet) + } + }) + } +} + +func TestNot(t *testing.T) { + ctx := context.Background() + + tests := []struct { + name string + inner extensions.Condition + wantMet bool + }{ + {"not met -> true", unmet("a"), true}, + {"not unmet -> false", met("a"), false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + c := Not(tt.inner) + got, err := c.Met(ctx) + if err != nil { + t.Fatalf("Met() error = %v", err) + } + if got != tt.wantMet { + t.Errorf("Met() = %v, want %v", got, tt.wantMet) + } + }) + } +} + +func TestResource_AlwaysMet(t *testing.T) { + ctx := context.Background() + c := Resource("package:nginx") + got, err := c.Met(ctx) + if err != nil { + t.Fatalf("Met() error = %v", err) + } + if !got { + t.Error("Resource condition should always be met at runtime") + } +} + +func TestResource_ID(t *testing.T) { + c := Resource("file:/etc/config") + if c.ID() != "file:/etc/config" { + t.Errorf("ID() = %q", c.ID()) + } +} + +func TestResourceIDs(t *testing.T) { + tests := []struct { + name string + cond extensions.Condition + want []string + }{ + {"single resource", Resource("package:nginx"), []string{"package:nginx"}}, + {"all with resources", All(Resource("a"), met("b"), Resource("c")), []string{"a", "c"}}, + {"nested all", All(Resource("a"), All(Resource("b"), met("c"))), []string{"a", "b"}}, + {"any with resources", Any(Resource("a"), Resource("b")), []string{"a", "b"}}, + {"not with resource", Not(Resource("a")), []string{"a"}}, + {"no resources", All(met("a"), met("b")), nil}, + {"nil", nil, nil}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := ResourceIDs(tt.cond) + if len(got) != len(tt.want) { + t.Fatalf("ResourceIDs() = %v, want %v", got, tt.want) + } + for i := range got { + if got[i] != tt.want[i] { + t.Errorf("ResourceIDs()[%d] = %q, want %q", i, got[i], tt.want[i]) + } + } + }) + } +} + +func TestStripResources(t *testing.T) { + tests := []struct { + name string + cond extensions.Condition + wantNil bool + wantStr string + }{ + {"pure resource -> nil", Resource("a"), true, ""}, + {"all resources -> nil", All(Resource("a"), Resource("b")), true, ""}, + {"mixed -> keeps non-resource", All(Resource("a"), met("b")), false, "b"}, + {"no resources -> unchanged", met("b"), false, "b"}, + {"nil -> nil", nil, true, ""}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := StripResources(tt.cond) + if tt.wantNil { + if got != nil { + t.Errorf("StripResources() = %v, want nil", got) + } + return + } + if got == nil { + t.Fatal("StripResources() = nil, want non-nil") + } + if got.String() != tt.wantStr { + t.Errorf("StripResources().String() = %q, want %q", got.String(), tt.wantStr) + } + }) + } +} + +func TestAll_String(t *testing.T) { + c := All(met("a"), met("b")) + want := "all(a, b)" + if got := c.String(); got != want { + t.Errorf("String() = %q, want %q", got, want) + } +} + +func TestAny_String(t *testing.T) { + c := Any(met("a"), met("b")) + want := "any(a, b)" + if got := c.String(); got != want { + t.Errorf("String() = %q, want %q", got, want) + } +} + +func TestNot_String(t *testing.T) { + c := Not(met("a")) + want := "not(a)" + if got := c.String(); got != want { + t.Errorf("String() = %q, want %q", got, want) + } +} + +func TestResource_String(t *testing.T) { + c := Resource("package:nginx") + want := "resource(package:nginx)" + if got := c.String(); got != want { + t.Errorf("String() = %q, want %q", got, want) + } +} diff --git a/condition/resource.go b/condition/resource.go new file mode 100644 index 0000000..88a9333 --- /dev/null +++ b/condition/resource.go @@ -0,0 +1,43 @@ +package condition + +import ( + "context" + "fmt" +) + +// resourceCondition represents a DAG dependency on another resource. +// The DSL extracts these at graph-build time and converts them to edges. +// At runtime, Met always returns true (the engine enforces ordering). +type resourceCondition struct { + id string +} + +func (c *resourceCondition) ID() string { return c.id } +func (c *resourceCondition) Met(_ context.Context) (bool, error) { return true, nil } +func (c *resourceCondition) Wait(_ context.Context) error { return nil } +func (c *resourceCondition) String() string { return fmt.Sprintf("resource(%s)", c.id) } + +// Resource returns a condition that depends on a resource by its full ID +// (e.g. "file:/etc/config"). Prefer the typed constructors below. +func Resource(id string) *resourceCondition { + return &resourceCondition{id: id} +} + +// Typed resource constructors. Each builds the correct ID prefix so the +// caller passes the same name they used in the DSL method. + +func File(path string) *resourceCondition { return &resourceCondition{id: "file:" + path} } +func Package(name string) *resourceCondition { return &resourceCondition{id: "package:" + name} } +func Service(name string) *resourceCondition { return &resourceCondition{id: "service:" + name} } +func Exec(name string) *resourceCondition { return &resourceCondition{id: "exec:" + name} } +func User(name string) *resourceCondition { return &resourceCondition{id: "user:" + name} } +func Template(path string) *resourceCondition { return &resourceCondition{id: "template:" + path} } +func Hostname(name string) *resourceCondition { return &resourceCondition{id: "hostname:" + name} } +func Cron(name string) *resourceCondition { return &resourceCondition{id: "cron:" + name} } +func Repository(name string) *resourceCondition { return &resourceCondition{id: "repository:" + name} } +func Firewall(name string) *resourceCondition { return &resourceCondition{id: "firewall:" + name} } +func Reboot(name string) *resourceCondition { return &resourceCondition{id: "reboot:" + name} } +func Sysctl(key string) *resourceCondition { return &resourceCondition{id: "sysctl:" + key} } +func KernelModule(name string) *resourceCondition { return &resourceCondition{id: "kernelmodule:" + name} } +func Registry(key string) *resourceCondition { return &resourceCondition{id: "registry:" + key} } +func Plist(domain string) *resourceCondition { return &resourceCondition{id: "plist:" + domain} } diff --git a/condition/resource_test.go b/condition/resource_test.go new file mode 100644 index 0000000..84800ef --- /dev/null +++ b/condition/resource_test.go @@ -0,0 +1,56 @@ +package condition + +import ( + "context" + "testing" +) + +func TestTypedResourceConstructors(t *testing.T) { + tests := []struct { + name string + cond *resourceCondition + wantID string + }{ + {"File", File("/etc/config"), "file:/etc/config"}, + {"Package", Package("nginx"), "package:nginx"}, + {"Service", Service("nginx"), "service:nginx"}, + {"Exec", Exec("install"), "exec:install"}, + {"User", User("deploy"), "user:deploy"}, + {"Template", Template("/etc/nginx.conf"), "template:/etc/nginx.conf"}, + {"Hostname", Hostname("web01"), "hostname:web01"}, + {"Cron", Cron("backup"), "cron:backup"}, + {"Repository", Repository("chrome"), "repository:chrome"}, + {"Firewall", Firewall("Allow SSH"), "firewall:Allow SSH"}, + {"Reboot", Reboot("driver-install"), "reboot:driver-install"}, + {"Sysctl", Sysctl("net.ipv4.ip_forward"), "sysctl:net.ipv4.ip_forward"}, + {"KernelModule", KernelModule("cramfs"), "kernelmodule:cramfs"}, + {"Registry", Registry(`HKLM\SOFTWARE\Test`), `registry:HKLM\SOFTWARE\Test`}, + {"Plist", Plist("com.apple.SoftwareUpdate"), "plist:com.apple.SoftwareUpdate"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if tt.cond.ID() != tt.wantID { + t.Errorf("ID() = %q, want %q", tt.cond.ID(), tt.wantID) + } + }) + } +} + +func TestResourceCondition_AlwaysMet(t *testing.T) { + ctx := context.Background() + c := Package("nginx") + met, err := c.Met(ctx) + if err != nil { + t.Fatalf("Met() error = %v", err) + } + if !met { + t.Error("resource condition should always be met at runtime") + } +} + +func TestResource_EscapeHatch(t *testing.T) { + c := Resource("custom:something") + if c.ID() != "custom:something" { + t.Errorf("ID() = %q, want %q", c.ID(), "custom:something") + } +} diff --git a/condition/shell.go b/condition/shell.go new file mode 100644 index 0000000..545c454 --- /dev/null +++ b/condition/shell.go @@ -0,0 +1,78 @@ +package condition + +import ( + "context" + "fmt" + "time" + + "github.com/TsekNet/converge/internal/shell" +) + +// Shell returns a Condition that runs a command in the platform-default shell +// (bash on Linux/macOS, powershell on Windows). Exit code 0 = met. +// +// Chain .Match(expected) for output-based matching, .In(shell) for an explicit +// shell override. +// +// condition.Shell("pgrep nginx") // exit 0 = met +// condition.Shell("cat /etc/hostname").Match("web01") // output match +// condition.Shell("(Get-WindowsOptionalFeature ...).State").Match("Enabled") +// condition.Shell("Get-Feature ...").In("pwsh").Match("Enabled") // explicit shell +func Shell(command string) *shellCondition { + return &shellCondition{ + shellName: shell.Auto, + command: command, + } +} + +type shellCondition struct { + shellName string + command string + expectedOutput string +} + +// In sets an explicit shell. Accepts "powershell", "pwsh", "cmd", "bash", +// "sh", or a custom binary path. +func (c *shellCondition) In(shellName string) *shellCondition { + c.shellName = shellName + return c +} + +// Match sets the expected trimmed stdout. When set, the condition is met +// when the command's trimmed output equals expected (instead of exit code 0). +func (c *shellCondition) Match(expected string) *shellCondition { + c.expectedOutput = expected + return c +} + +func (c *shellCondition) Met(ctx context.Context) (bool, error) { + stdout, err := shell.Run(ctx, c.shellName, c.command, nil) + + if c.expectedOutput != "" { + return stdout == c.expectedOutput, nil + } + + return err == nil, nil +} + +func (c *shellCondition) Wait(ctx context.Context) error { + ticker := time.NewTicker(5 * time.Second) + defer ticker.Stop() + for { + if met, _ := c.Met(ctx); met { + return nil + } + select { + case <-ctx.Done(): + return ctx.Err() + case <-ticker.C: + } + } +} + +func (c *shellCondition) String() string { + if c.expectedOutput != "" { + return fmt.Sprintf("shell %s: %s == %q", c.shellName, shell.Truncate(c.command, 40), c.expectedOutput) + } + return fmt.Sprintf("shell %s: %s", c.shellName, shell.Truncate(c.command, 40)) +} diff --git a/condition/shell_test.go b/condition/shell_test.go new file mode 100644 index 0000000..ec09ab6 --- /dev/null +++ b/condition/shell_test.go @@ -0,0 +1,115 @@ +package condition + +import ( + "context" + "testing" +) + +func TestShell_Met_ExitCode(t *testing.T) { + ctx := context.Background() + + tests := []struct { + name string + command string + wantMet bool + }{ + {"exit 0 = met", "exit 0", true}, + {"exit 1 = not met", "exit 1", false}, + {"true = met", "true", true}, + {"false = not met", "false", false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + c := Shell(tt.command).In("bash") + met, err := c.Met(ctx) + if err != nil { + t.Fatalf("Met() error = %v", err) + } + if met != tt.wantMet { + t.Errorf("Met() = %v, want %v", met, tt.wantMet) + } + }) + } +} + +func TestShell_Met_OutputMatch(t *testing.T) { + ctx := context.Background() + + tests := []struct { + name string + command string + expect string + wantMet bool + }{ + {"output matches", "echo -n hello", "hello", true}, + {"output differs", "echo -n world", "hello", false}, + {"trailing newline trimmed", "echo hello", "hello", true}, + {"command fails, no match", "false", "hello", false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + c := Shell(tt.command).In("bash").Match(tt.expect) + met, err := c.Met(ctx) + if err != nil { + t.Fatalf("Met() error = %v", err) + } + if met != tt.wantMet { + t.Errorf("Met() = %v, want %v", met, tt.wantMet) + } + }) + } +} + +func TestShell_String(t *testing.T) { + tests := []struct { + name string + cond *shellCondition + want string + }{ + {"with match", Shell("echo hello").In("bash").Match("hello"), `shell bash: echo hello == "hello"`}, + {"no match", Shell("pgrep nginx").In("bash"), "shell bash: pgrep nginx"}, + {"auto shell", Shell("pgrep nginx"), "shell auto: pgrep nginx"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := tt.cond.String(); got != tt.want { + t.Errorf("String() = %q, want %q", got, tt.want) + } + }) + } +} + +func TestShell_ChainOrder(t *testing.T) { + ctx := context.Background() + + // .In().Match() and .Match().In() should produce the same result + a := Shell("echo -n yes").In("bash").Match("yes") + b := Shell("echo -n yes").Match("yes").In("bash") + + metA, _ := a.Met(ctx) + metB, _ := b.Met(ctx) + + if metA != metB { + t.Errorf("chain order matters: .In().Match()=%v, .Match().In()=%v", metA, metB) + } + if !metA { + t.Error("both should be met") + } +} + +func TestShell_MultilineScript(t *testing.T) { + ctx := context.Background() + + c := Shell("x=hello\necho -n $x").In("bash").Match("hello") + met, _ := c.Met(ctx) + if !met { + t.Error("multi-line bash script should match output") + } +} + +func TestShell_DefaultShellIsAuto(t *testing.T) { + c := Shell("echo test") + if c.shellName != "auto" { + t.Errorf("default shell = %q, want %q", c.shellName, "auto") + } +} diff --git a/docs/design.md b/docs/design.md index 0d5118b..f7c3b0f 100644 --- a/docs/design.md +++ b/docs/design.md @@ -193,7 +193,7 @@ This means a Linux blueprint can call `r.Sysctl()` but not `r.Registry()`. The c ### DAG Engine -Resources are organized in a directed acyclic graph (DAG). Dependencies are detected automatically via auto-edges and can be declared explicitly via `DependsOn`. The engine computes topological layers and executes them in order, with resources in the same layer running concurrently. +Resources are organized in a directed acyclic graph (DAG). Dependencies are detected automatically via auto-edges and can be declared explicitly via `condition.Package("name")` on the resource's `Condition` field. The engine computes topological layers and executes them in order, with resources in the same layer running concurrently. ```mermaid graph TD @@ -265,7 +265,7 @@ flowchart TD **Key behaviors:** -- **Condition gates.** Resources with a `Condition` set in `Meta` are skipped until the condition is met. The daemon waits using OS-native events (netlink, inotify, NotifyIpInterfaceChange, RegNotifyChangeKeyValue) and triggers initial convergence the moment the condition becomes true. See the `condition` package. +- **Condition gates.** Resources with a `Condition` set are skipped until the condition is met. The daemon waits using OS-native events (netlink, inotify, NotifyIpInterfaceChange, RegNotifyChangeKeyValue) and triggers initial convergence the moment the condition becomes true. See the `condition` package. - **Event-driven, not polling.** Resources implementing `Watcher` (File via inotify, Service via dbus) block on OS-level events. Near-zero CPU at idle. - **DAG propagation.** When a resource changes, its downstream dependents in the DAG are automatically re-checked. This is what Chef, Puppet, and Ansible lack entirely. - **Polling fallback.** Resources without native OS events (Package, Exec) are polled at configurable intervals. diff --git a/docs/examples.md b/docs/examples.md index 116576a..d14e785 100644 --- a/docs/examples.md +++ b/docs/examples.md @@ -8,7 +8,7 @@ For real-world blueprints, see the [blueprints/](../blueprints/) directory, incl - [Writing a Blueprint](#writing-a-blueprint) - [Registering in main.go](#registering-in-maingo) - [Platform-Conditional Logic](#platform-conditional-logic) -- [Explicit Dependencies with DependsOn](#explicit-dependencies-with-dependson) +- [Dependencies and Conditions](#dependencies-and-conditions) - [Daemon Mode (`converge serve`)](#daemon-mode-converge-serve) - [Blueprint Composition](#blueprint-composition) - [Testing Blueprints](#testing-blueprints) @@ -22,6 +22,7 @@ For real-world blueprints, see the [blueprints/](../blueprints/) directory, incl - [Plist](#plist-macos-only) - [InShard](#inshard), [Secret / Encrypted Config](#secret--encrypted-config) - [Conditions](#conditions) + - [Shell](#shell-arbitrary-command-guards), [Resource](#resource-dag-dependencies), [Combinators (All, Any, Not)](#combinators-all-any-not) - [NetworkInterface](#networkinterface-vpn-gated-firewall-rules), [MountPoint](#mountpoint-nfs-backed-service) - [FileExists](#fileexists-cert-enrollment-after-bootstrap), [NetworkReachable](#networkreachable-proxy-config-before-package-installs) - [RegistryKey / RegistryValue](#registrykeyexists--registryvalueexists--registryvalueequals-windows-only) @@ -214,24 +215,31 @@ The compiler enforces this: you can't call `r.Registry()` from a Linux-tagged fi --- -## Explicit Dependencies with DependsOn +## Dependencies and Conditions -Auto-edges handle most dependency relationships automatically (Service->Package, File->parent Dir). For dependencies that auto-edges cannot detect, use `DependsOn`: +Auto-edges handle most dependency relationships automatically (Service->Package, File->parent Dir). For dependencies that auto-edges cannot detect, use typed resource conditions (e.g. `condition.Package`, `condition.File`) to declare explicit DAG edges. Use `condition.Shell` to gate resources on arbitrary command output. Combine conditions with `condition.All`, `condition.Any`, and `condition.Not`. ```go +import ( + "github.com/TsekNet/converge/condition" + "github.com/TsekNet/converge/dsl" +) + func Blueprint(r *dsl.Run) { r.Package("postgresql", dsl.PackageOpts{State: dsl.Present}) r.Exec("db-migrate", dsl.ExecOpts{ - Command: "/usr/bin/db-migrate", - OnlyIf: "test -f /var/lib/myapp/.migration-done", - Meta: dsl.Meta{DependsOn: []string{"package:postgresql"}}, + Command: "/usr/bin/db-migrate", + Condition: condition.All( + condition.Package("postgresql"), + condition.Shell("test -f /var/lib/myapp/.migration-done"), + ), }) r.Service("myapp", dsl.ServiceOpts{ State: dsl.Running, Enable: true, - Meta: dsl.Meta{DependsOn: []string{"exec:db-migrate"}}, + Condition: condition.Exec("db-migrate"), }) } ``` @@ -257,7 +265,7 @@ converge.exe serve baseline What happens: -1. The DAG is built with auto-edges and explicit `DependsOn` relationships +1. The DAG is built with auto-edges and explicit typed resource conditions (e.g. `condition.Package`, `condition.File`) dependencies 2. Initial convergence runs all resources in topological order 3. Per-resource watchers start (inotify for files, dbus for services, etc.) 4. When drift is detected, the drifted resource is re-checked and its DAG dependents are re-evaluated @@ -327,12 +335,11 @@ func TestBaseline(t *testing.T) { ## Resource Reference -All option structs share these common fields via `dsl.Meta`: +All option structs share these common fields directly on each Opts struct: | Field | Type | Default | Description | |-------|------|---------|-------------| | `Critical` | `bool` | `false` | If `true`, failure aborts the run. Set `true` for resources whose failure should abort the run. | -| `DependsOn` | `[]string` | `nil` | Explicit resource IDs this resource depends on. Complements auto-edges. | | `Noop` | `bool` | `false` | Per-resource dry-run: Check only, skip Apply. | | `Retry` | `int` | `0` | Per-resource max retries. 0 = use daemon default (--max-retries). | | `Limit` | `float64` | `0` | Per-resource rate limit (events/sec). 0 = use daemon default. | @@ -340,16 +347,18 @@ All option structs share these common fields via `dsl.Meta`: | `AutoGroup` | `*bool` | `nil` | Set to `falseVal := false; &falseVal` to disable auto-grouping for this resource. | | `Condition` | `extensions.Condition` | `nil` | Gate on runtime state. See [Conditions](#conditions). | -**Auto-edges:** Dependencies are detected automatically: `service:X` depends on `package:X`, files depend on parent directories, services depend on config files. Use `DependsOn` for dependencies auto-edges cannot detect. +**Auto-edges:** Dependencies are detected automatically: `service:X` depends on `package:X`, files depend on parent directories, services depend on config files. Use typed resource conditions (e.g. `condition.Package`, `condition.File`) for dependencies auto-edges cannot detect. **Auto-grouping:** Package resources with the same manager and state are automatically batched into a single install/remove transaction (e.g., `apt install git curl neovim` instead of three separate calls). Set `AutoGroup` to a `*bool` pointing to `false` to opt out (e.g., `falseVal := false; Meta{AutoGroup: &falseVal}`). -Use `DependsOn` for dependencies auto-edges cannot detect: +Use typed resource conditions (e.g. `condition.Package`, `condition.File`) for dependencies auto-edges cannot detect: ```go +import "github.com/TsekNet/converge/condition" + r.Exec("migrate", dsl.ExecOpts{ - Command: "/usr/bin/db-migrate", - Meta: dsl.Meta{DependsOn: []string{"package:postgresql"}}, + Command: "/usr/bin/db-migrate", + Condition: condition.Package("postgresql"), }) ``` @@ -539,8 +548,6 @@ r.Exec(name string, opts dsl.ExecOpts) |-------|------|---------|-------------| | `Command` | `string` | `""` | The command to execute (or script body when Shell is set). Required. | | `Args` | `[]string` | `nil` | Arguments passed to the command. Ignored when Shell is set. | -| `OnlyIf` | `string` | `""` | Guard command. If exits 0 (or output matches OnlyIfMatch), `Command` is skipped. | -| `OnlyIfMatch` | `string` | `""` | When set, guard compares trimmed stdout against this string instead of exit code. | | `Shell` | `string` | `""` | `"auto"` (bash on Linux/macOS, powershell on Windows), `"powershell"`, `"pwsh"`, `"cmd"`, `"bash"`, `"sh"`, or custom path. | | `ShellParams` | `[]string` | `nil` | When set, replaces the default shell flags. PowerShell default: `-NoProfile -NonInteractive -ExecutionPolicy Bypass`. | | `Dir` | `string` | `""` | Working directory. Empty = inherit. | @@ -548,15 +555,17 @@ r.Exec(name string, opts dsl.ExecOpts) | `Retries` | `int` | `0` | Number of retry attempts on failure. | | `RetryDelay` | `time.Duration` | `0` | Delay between retries. | -**Idempotency:** Not inherently idempotent. Always provide an `OnlyIf` command to make it conditional. +**Idempotency:** Not inherently idempotent. Always use `condition.Shell("...")` on `Meta.Condition` to make it conditional. **Examples:** ```go +import "github.com/TsekNet/converge/condition" + // Linux: run a script only if a marker file is missing r.Exec("bootstrap", dsl.ExecOpts{ Command: "/usr/local/bin/bootstrap.sh", - OnlyIf: "test -f /var/lib/myapp/.bootstrapped", + Condition: condition.Shell("test -f /var/lib/myapp/.bootstrapped"), }) // macOS: flush DNS cache @@ -565,28 +574,27 @@ r.Exec("flush-dns", dsl.ExecOpts{ Args: []string{"-flushcache"}, }) -// Windows: enable TLS 1.2 (OnlyIf checks if already set) +// Windows: enable TLS 1.2 (condition checks if already set) r.Exec("enable-tls12", dsl.ExecOpts{ Command: "powershell.exe", Args: []string{"-NoProfile", "-Command", "New-ItemProperty -Path 'HKLM:\\SYSTEM\\...' -Name Enabled -Value 1"}, - OnlyIf: "powershell.exe -NoProfile -Command \"(Get-ItemProperty 'HKLM:\\SYSTEM\\...').Enabled -eq 1\"", + Condition: condition.Shell(`powershell.exe -NoProfile -Command "(Get-ItemProperty 'HKLM:\SYSTEM\...').Enabled -eq 1"`), }) // Retry on transient failure (all platforms) r.Exec("download-agent", dsl.ExecOpts{ Command: "curl", Args: []string{"-fsSL", "-o", "/tmp/agent.tar.gz", "https://example.com/agent.tar.gz"}, - OnlyIf: "test -f /tmp/agent.tar.gz", Retries: 3, RetryDelay: 5 * time.Second, + Condition: condition.Shell("test -f /tmp/agent.tar.gz"), }) // PowerShell: enable Windows feature (5.1, default path) r.Exec("enable-wsl", dsl.ExecOpts{ - Shell: "powershell", - Command: "Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-Subsystem-Linux -NoRestart", - OnlyIf: "(Get-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-Subsystem-Linux).State", - OnlyIfMatch: "Enabled", + Shell: "powershell", + Command: "Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-Subsystem-Linux -NoRestart", + Condition: condition.Shell("(Get-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-Subsystem-Linux).State").In("powershell").Match("Enabled"), }) // PowerShell 7+: multi-line script @@ -598,8 +606,7 @@ r.Exec("configure-defender", dsl.ExecOpts{ Set-MpPreference -DisableRealtimeMonitoring $false } `, - OnlyIf: "(Get-MpPreference).DisableRealtimeMonitoring", - OnlyIfMatch: "False", + Condition: condition.Shell("(Get-MpPreference).DisableRealtimeMonitoring").In("pwsh").Match("False"), }) // PowerShell with custom parameters @@ -611,10 +618,9 @@ r.Exec("run-with-profile", dsl.ExecOpts{ // Bash: multi-line script with output-based guard r.Exec("set-timezone", dsl.ExecOpts{ - Shell: "bash", - Command: "timedatectl set-timezone America/Los_Angeles", - OnlyIf: "timedatectl show --property=Timezone --value", - OnlyIfMatch: "America/Los_Angeles", + Shell: "bash", + Command: "timedatectl set-timezone America/Los_Angeles", + Condition: condition.Shell("timedatectl show --property=Timezone --value").Match("America/Los_Angeles"), }) ``` @@ -1004,24 +1010,26 @@ r.Reboot(name string, opts dsl.RebootOpts) **Examples:** ```go +import "github.com/TsekNet/converge/condition" + // Reboot after installing a kernel module, then gate post-reboot setup // on a device node that only appears after the driver loads. r.Exec("install-driver", dsl.ExecOpts{ Command: "/usr/bin/dkms install mydriver/1.0", - OnlyIf: "test ! -d /sys/module/mydriver", + Condition: condition.Shell("test ! -d /sys/module/mydriver"), }) r.Reboot("driver-install", dsl.RebootOpts{ Reason: "Kernel module requires reboot to activate", Message: "Rebooting to load newly installed driver.", Delay: 30 * time.Second, - Meta: dsl.Meta{DependsOn: []string{"exec:install-driver"}}, + Condition: condition.Exec("install-driver"), }) r.Exec("configure-driver", dsl.ExecOpts{ Command: "/usr/local/bin/configure-driver", - Meta: dsl.Meta{ - Condition: condition.FileExists("/dev/mydriver0"), - DependsOn: []string{"reboot:driver-install"}, - }, + Condition: condition.All( + condition.Reboot("driver-install"), + condition.FileExists("/dev/mydriver0"), + ), }) ``` @@ -1032,24 +1040,24 @@ r.Exec("configure-driver", dsl.ExecOpts{ r.Exec("install-agent", dsl.ExecOpts{ Command: `C:\installers\agent-setup.exe /quiet`, - OnlyIf: `powershell -NoProfile -Command "!(Test-Path 'C:\Program Files\MyAgent\agent.exe')"`, + Condition: condition.Shell(`powershell -NoProfile -Command "!(Test-Path 'C:\Program Files\MyAgent\agent.exe')"`), }) r.Reboot("agent-install", dsl.RebootOpts{ Reason: "Agent installation requires reboot to complete service registration", Message: "This device will restart in 30 seconds to finish agent setup.", Delay: 30 * time.Second, - Meta: dsl.Meta{DependsOn: []string{"exec:install-agent"}}, + Condition: condition.Exec("install-agent"), }) r.Exec("configure-agent", dsl.ExecOpts{ Command: `C:\Program Files\MyAgent\agent.exe --configure`, - Meta: dsl.Meta{ - // Block until the agent's post-reboot registry key appears. - Condition: condition.RegistryValueExists( - `HKLM\SOFTWARE\MyOrg\Agent`, - "InstallComplete", + // Block until the reboot completes and the agent's registry key appears. + Condition: condition.All( + condition.Reboot("agent-install"), + condition.RegistryValueExists( + `HKLM\SOFTWARE\MyOrg\Agent`, + "InstallComplete", + ), ), - DependsOn: []string{"reboot:agent-install"}, - }, }) ``` @@ -1188,10 +1196,8 @@ import "github.com/TsekNet/converge/condition" ```go r.Firewall("allow-internal", dsl.FirewallOpts{ Port: 8443, Protocol: "tcp", Action: "allow", - Meta: dsl.Meta{ // Only apply when tun0 (VPN) interface is up. Condition: condition.NetworkInterface("tun0"), - }, }) ``` @@ -1201,11 +1207,11 @@ r.Firewall("allow-internal", dsl.FirewallOpts{ r.File("/mnt/nfs/config/app.conf", dsl.FileOpts{Content: appConfig}) r.Service("app", dsl.ServiceOpts{ State: dsl.Running, - Meta: dsl.Meta{ - // Wait for NFS mount before managing the service. - Condition: condition.MountPoint("/mnt/nfs"), - DependsOn: []string{"file:/mnt/nfs/config/app.conf"}, - }, + // Wait for NFS mount and config file before managing the service. + Condition: condition.All( + condition.MountPoint("/mnt/nfs"), + condition.File("/mnt/nfs/config/app.conf"), + ), }) ``` @@ -1214,10 +1220,8 @@ r.Service("app", dsl.ServiceOpts{ ```go r.Exec("enroll-cert", dsl.ExecOpts{ Command: "/usr/local/bin/enroll", - Meta: dsl.Meta{ // Wait for the CA bundle to be placed by provisioning. Condition: condition.FileExists("/etc/ssl/ca-bundle.crt"), - }, }) ``` @@ -1227,11 +1231,11 @@ r.Exec("enroll-cert", dsl.ExecOpts{ r.File("/etc/apt/apt.conf.d/99proxy", dsl.FileOpts{Content: proxyConf}) r.Package("curl", dsl.PackageOpts{ State: dsl.Present, - Meta: dsl.Meta{ - // Only install packages once the proxy is reachable. - Condition: condition.NetworkReachable("proxy.corp.example.com", 3128), - DependsOn: []string{"file:/etc/apt/apt.conf.d/99proxy"}, - }, + // Only install packages once the proxy is reachable and config is in place. + Condition: condition.All( + condition.NetworkReachable("proxy.corp.example.com", 3128), + condition.File("/etc/apt/apt.conf.d/99proxy"), + ), }) ``` @@ -1245,32 +1249,26 @@ Gate convergence on Windows registry state. Uses `RegNotifyChangeKeyValue` so no // Gate on key existence (any subkey or value creation under this path) r.Exec("post-install-step", dsl.ExecOpts{ Command: `C:\Program Files\MyApp\setup.exe --post-install`, - Meta: dsl.Meta{ Condition: condition.RegistryKeyExists(`HKLM\SOFTWARE\MyOrg\MyApp`), - }, }) // Gate on a specific value existing under a key r.File(`C:\ProgramData\MyApp\config.json`, dsl.FileOpts{ Content: `{"mode": "managed"}`, - Meta: dsl.Meta{ Condition: condition.RegistryValueExists( `HKLM\SOFTWARE\MyOrg\MyApp`, "SetupComplete", ), - }, }) // Gate on a value equaling a specific string or integer r.Exec("activate-feature", dsl.ExecOpts{ Command: `C:\Program Files\MyApp\activate.exe`, - Meta: dsl.Meta{ Condition: condition.RegistryValueEquals( `HKLM\SOFTWARE\MyOrg\MyApp`, "LicenseState", "active", ), - }, }) ``` @@ -1284,10 +1282,104 @@ All three constructors return `*registryCondition`, which implements `extensions If the target key does not yet exist, `Wait` walks up the key path to find the nearest existing ancestor and watches the subtree with `bWatchSubtree=true`. +### Shell: arbitrary command guards + +`condition.Shell` runs a command in the platform-default shell (bash on Linux/macOS, powershell on Windows). Exit code 0 means the condition is met. Chain `.Match("expected")` to compare trimmed stdout instead of exit code. Chain `.In("shell")` to override the shell. + +```go +import "github.com/TsekNet/converge/condition" + +// Exit-code guard: met when the command exits 0 +r.Exec("bootstrap", dsl.ExecOpts{ + Command: "/usr/local/bin/bootstrap.sh", + Condition: condition.Shell("test -f /var/lib/myapp/.bootstrapped"), +}) + +// Output-match guard: met when stdout matches "Enabled" +r.Exec("enable-wsl", dsl.ExecOpts{ + Shell: "powershell", + Command: "Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-Subsystem-Linux -NoRestart", + Condition: condition.Shell("(Get-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-Subsystem-Linux).State").In("powershell").Match("Enabled"), +}) + +// Explicit shell override with output match +r.Exec("set-timezone", dsl.ExecOpts{ + Shell: "bash", + Command: "timedatectl set-timezone America/Los_Angeles", + Condition: condition.Shell("timedatectl show --property=Timezone --value").In("bash").Match("America/Los_Angeles"), +}) +``` + +### Resource: DAG dependencies + +typed resource conditions (e.g. `condition.Package`, `condition.File`) declares an explicit DAG dependency on another resource by its ID (e.g., `"package:nginx"`, `"exec:migrate"`). The condition is met when the referenced resource has completed successfully. This replaces the former `DependsOn` field. + +```go +import "github.com/TsekNet/converge/condition" + +r.Package("postgresql", dsl.PackageOpts{State: dsl.Present}) +r.Exec("migrate", dsl.ExecOpts{ + Command: "/usr/bin/db-migrate", + Condition: condition.Package("postgresql"), +}) +``` + +### Combinators: All, Any, Not + +Combine conditions with `condition.All` (AND), `condition.Any` (OR), and `condition.Not` (inversion). + +```go +import "github.com/TsekNet/converge/condition" + +// All: both conditions must be met +r.Service("app", dsl.ServiceOpts{ + State: dsl.Running, + Condition: condition.All( + condition.MountPoint("/mnt/nfs"), + condition.File("/mnt/nfs/config/app.conf"), + ), +}) + +// Any: at least one condition must be met +r.Exec("fetch-config", dsl.ExecOpts{ + Command: "/usr/local/bin/fetch-config", + Condition: condition.Any( + condition.NetworkReachable("primary.example.com", 443), + condition.NetworkReachable("fallback.example.com", 443), + ), +}) + +// Not: invert a condition +r.Exec("setup-vpn", dsl.ExecOpts{ + Command: "/usr/local/bin/setup-vpn", + Condition: condition.Not(condition.NetworkInterface("tun0")), +}) + +// Nested: All with Not and Any +r.Exec("complex-gate", dsl.ExecOpts{ + Command: "/usr/local/bin/deploy", + Condition: condition.All( + condition.Package("myapp"), + condition.Not(condition.Shell("pgrep -x deploy")), + condition.Any( + condition.FileExists("/etc/myapp/config.yaml"), + condition.FileExists("/etc/myapp/config.json"), + ), + ), +}) +``` + ### Available conditions | Constructor | Platform | Satisfied when | Wait mechanism | |---|---|---|---| +| `condition.Shell("cmd")` | All | Command exits 0 (platform-default shell) | 5s poll | +| `condition.Shell("cmd").Match("str")` | All | Command stdout matches `str` | 5s poll | +| `condition.Shell("cmd").In("shell").Match("str")` | All | Command stdout matches `str` (explicit shell) | 5s poll | +| `condition.Package("name")` | All | Referenced resource completed successfully | DAG engine (no poll) | +| `condition.All(a, b, ...)` | All | All sub-conditions are met | Delegates to sub-conditions | +| `condition.Any(a, b, ...)` | All | At least one sub-condition is met | Delegates to sub-conditions | +| `condition.Not(a)` | All | Sub-condition is NOT met | Delegates to sub-condition | | `condition.NetworkInterface(name)` | All | Named interface exists and is up | netlink RTMGRP_LINK (Linux), NotifyIpInterfaceChange (Windows), 2s poll (macOS) | | `condition.NetworkReachable(host, port)` | All | TCP connect to host:port succeeds | 5s poll (no kernel event for TCP reachability) | | `condition.MountPoint(path)` | All | path is on a different device than its parent | inotify on /proc/self/mountinfo (Linux), kqueue on / (macOS), 5s poll (Windows) | diff --git a/dsl/converge_test.go b/dsl/converge_test.go index c9bc5fe..a88af04 100644 --- a/dsl/converge_test.go +++ b/dsl/converge_test.go @@ -5,6 +5,7 @@ import ( "strings" "testing" + "github.com/TsekNet/converge/condition" "github.com/TsekNet/converge/internal/graph" ) @@ -248,13 +249,13 @@ func TestRun_DuplicateResource(t *testing.T) { } } -func TestRun_DependsOn_MissingDep(t *testing.T) { +func TestRun_ConditionResource_MissingDep(t *testing.T) { t.Parallel() run := newRun(New()) run.File("/etc/motd", FileOpts{ - Content: "hello", - Meta: Meta{DependsOn: []string{"package:nonexistent"}}, + Content: "hello", + Condition: condition.Package("nonexistent"), }) if run.Err() == nil { @@ -265,14 +266,14 @@ func TestRun_DependsOn_MissingDep(t *testing.T) { } } -func TestRun_DependsOn_Valid(t *testing.T) { +func TestRun_ConditionResource_Valid(t *testing.T) { t.Parallel() run := newRun(New()) run.Package("nginx", PackageOpts{State: Present}) run.Service("nginx", ServiceOpts{ - State: Running, - Meta: Meta{DependsOn: []string{"package:nginx"}}, + State: Running, + Condition: condition.Package("nginx"), }) if run.Err() != nil { @@ -283,6 +284,24 @@ func TestRun_DependsOn_Valid(t *testing.T) { } } +func TestRun_ConditionResource_StrippedFromRuntime(t *testing.T) { + t.Parallel() + + run := newRun(New()) + run.Package("nginx", PackageOpts{State: Present}) + run.File("/etc/nginx/nginx.conf", FileOpts{ + Content: "server {}", + Condition: condition.All( + condition.Package("nginx"), + condition.FileExists("/etc/nginx"), + ), + }) + + if run.Err() != nil { + t.Fatalf("unexpected error: %v", run.Err()) + } +} + func TestRun_EmptyName(t *testing.T) { t.Parallel() diff --git a/dsl/dsl.go b/dsl/dsl.go index 766dc12..c593071 100644 --- a/dsl/dsl.go +++ b/dsl/dsl.go @@ -26,17 +26,16 @@ const ( Stopped ServiceState = "stopped" ) -// Meta holds common metadata shared by all Opts structs. -type Meta struct { - DependsOn []string - Critical bool - Noop bool // skip Apply, only Check (per-resource dry-run) - Retry int // per-resource max retries (0 = use daemon default) - Limit float64 // per-resource rate limit (0 = use daemon default) - AutoEdge *bool // nil = enabled (default), false = disable auto-edges for this resource - AutoGroup *bool // nil = enabled (default), false = disable auto-grouping for this resource - Condition extensions.Condition // nil = no gate; non-nil = skip until condition is met -} +// Common fields shared by all Opts structs. Each Opts struct includes these +// directly (no embedding) so blueprint authors write flat structs. +// +// Critical bool // false = best-effort, true = failure aborts the run +// Noop bool // skip Apply, only Check (per-resource dry-run) +// Retry int // per-resource max retries (0 = use daemon default) +// Limit float64 // per-resource rate limit (0 = use daemon default) +// AutoEdge *bool // nil = enabled, false = disable auto-edges +// AutoGroup *bool // nil = enabled, false = disable auto-grouping +// Condition extensions.Condition // nil = no gate; non-nil = skip until condition is met type FileOpts struct { Content string @@ -48,77 +47,135 @@ type FileOpts struct { Checksum string // expected SHA-256 hex digest (only with URL) BlockName string // when set, manages a tagged block within the file instead of owning the entire file BlockComment string // comment prefix for block markers (default: "#") - Meta + Critical bool + Noop bool + Retry int + Limit float64 + AutoEdge *bool + AutoGroup *bool + Condition extensions.Condition } type PackageOpts struct { - State ResourceState - Meta + State ResourceState + Critical bool + Noop bool + Retry int + Limit float64 + AutoEdge *bool + AutoGroup *bool + Condition extensions.Condition } type ServiceOpts struct { State ServiceState Enable bool StartupType string // "auto", "delayed-auto", "manual", "disabled" (Windows SCM) - Meta + Critical bool + Noop bool + Retry int + Limit float64 + AutoEdge *bool + AutoGroup *bool + Condition extensions.Condition } type ExecOpts struct { Command string Args []string - OnlyIf string - OnlyIfMatch string // when set, OnlyIf compares trimmed stdout against this string - Shell string // "powershell", "pwsh", "bash", "sh", or "" (direct exec) + Shell string // "powershell", "pwsh", "cmd", "bash", "sh", "auto", or custom path ShellParams []string // when set, replaces default shell flags Dir string Env []string Retries int RetryDelay time.Duration - Meta + Critical bool + Noop bool + Retry int + Limit float64 + AutoEdge *bool + AutoGroup *bool + Condition extensions.Condition } type UserOpts struct { - Groups []string - Shell string - Home string - System bool - Meta + Groups []string + Shell string + Home string + System bool + Critical bool + Noop bool + Retry int + Limit float64 + AutoEdge *bool + AutoGroup *bool + Condition extensions.Condition } type RegistryOpts struct { - Value string - Type string - Data any - State ResourceState // Present (default) or Absent - Meta + Value string + Type string + Data any + State ResourceState // Present (default) or Absent + Critical bool + Noop bool + Retry int + Limit float64 + AutoEdge *bool + AutoGroup *bool + Condition extensions.Condition } type SecurityPolicyOpts struct { - Category string // "password" or "lockout" - Key string - Value string - Meta + Category string // "password" or "lockout" + Key string + Value string + Critical bool + Noop bool + Retry int + Limit float64 + AutoEdge *bool + AutoGroup *bool + Condition extensions.Condition } type AuditPolicyOpts struct { Subcategory string Success bool Failure bool - Meta + Critical bool + Noop bool + Retry int + Limit float64 + AutoEdge *bool + AutoGroup *bool + Condition extensions.Condition } type SysctlOpts struct { - Value string - Persist bool - Meta + Value string + Persist bool + Critical bool + Noop bool + Retry int + Limit float64 + AutoEdge *bool + AutoGroup *bool + Condition extensions.Condition } type PlistOpts struct { - Key string - Value any - Type string // "bool", "int", "float", "string" - Host bool // true = /Library/Preferences (system-wide), false = ~/Library/Preferences - Meta + Key string + Value any + Type string // "bool", "int", "float", "string" + Host bool // true = /Library/Preferences (system-wide), false = ~/Library/Preferences + Critical bool + Noop bool + Retry int + Limit float64 + AutoEdge *bool + AutoGroup *bool + Condition extensions.Condition } type FirewallOpts struct { @@ -129,27 +186,51 @@ type FirewallOpts struct { Source string // Optional source address/CIDR Dest string // Optional destination address/CIDR State ResourceState - Meta + Critical bool + Noop bool + Retry int + Limit float64 + AutoEdge *bool + AutoGroup *bool + Condition extensions.Condition } type RebootOpts struct { - Reason string - Message string // optional user-facing message shown in converge output before the reboot fires - Delay time.Duration - Meta + Reason string + Message string // optional user-facing message shown in converge output before the reboot fires + Delay time.Duration + Critical bool + Noop bool + Retry int + Limit float64 + AutoEdge *bool + AutoGroup *bool + Condition extensions.Condition } type TemplateOpts struct { - Source string // Go text/template source - Vars map[string]string // template variables - Mode os.FileMode - Owner string - Group string - Meta + Source string // Go text/template source + Vars map[string]string // template variables + Mode os.FileMode + Owner string + Group string + Critical bool + Noop bool + Retry int + Limit float64 + AutoEdge *bool + AutoGroup *bool + Condition extensions.Condition } type HostnameOpts struct { - Meta + Critical bool + Noop bool + Retry int + Limit float64 + AutoEdge *bool + AutoGroup *bool + Condition extensions.Condition } type KernelModuleState string @@ -160,16 +241,28 @@ const ( ) type KernelModuleOpts struct { - State KernelModuleState - Meta + State KernelModuleState + Critical bool + Noop bool + Retry int + Limit float64 + AutoEdge *bool + AutoGroup *bool + Condition extensions.Condition } type CronOpts struct { - Schedule string // cron expression (Linux/macOS) or trigger spec (Windows) - Command string - User string // user to run as - State ResourceState - Meta + Schedule string // cron expression (Linux/macOS) or trigger spec (Windows) + Command string + User string // user to run as + State ResourceState + Critical bool + Noop bool + Retry int + Limit float64 + AutoEdge *bool + AutoGroup *bool + Condition extensions.Condition } type RepositoryOpts struct { @@ -179,5 +272,11 @@ type RepositoryOpts struct { GPGKey string // GPG key URL Enabled bool State ResourceState - Meta + Critical bool + Noop bool + Retry int + Limit float64 + AutoEdge *bool + AutoGroup *bool + Condition extensions.Condition } diff --git a/dsl/resources.go b/dsl/resources.go index 38094a9..9c495ea 100644 --- a/dsl/resources.go +++ b/dsl/resources.go @@ -51,8 +51,6 @@ func newExecExtension(name string, opts ExecOpts) extensions.Extension { return extexec.New(name, extexec.Opts{ Command: opts.Command, Args: opts.Args, - OnlyIf: opts.OnlyIf, - OnlyIfMatch: opts.OnlyIfMatch, Shell: opts.Shell, ShellParams: opts.ShellParams, Dir: opts.Dir, diff --git a/dsl/run.go b/dsl/run.go index d6e9eeb..86e59da 100644 --- a/dsl/run.go +++ b/dsl/run.go @@ -4,13 +4,25 @@ import ( "errors" "fmt" + "github.com/TsekNet/converge/condition" "github.com/TsekNet/converge/extensions" extpkg "github.com/TsekNet/converge/extensions/pkg" "github.com/TsekNet/converge/internal/graph" "github.com/TsekNet/converge/internal/platform" ) -func toNodeMeta(m Meta) graph.NodeMeta { +// nodeMeta is the internal representation passed to addResource. +// Each DSL method constructs this from the flat Opts fields. +type nodeMeta struct { + Noop bool + Retry int + Limit float64 + AutoEdge *bool + AutoGroup *bool + Condition extensions.Condition +} + +func (m nodeMeta) toGraph() graph.NodeMeta { return graph.NodeMeta{ Noop: m.Noop, Retry: m.Retry, @@ -38,22 +50,25 @@ func newRun(app *App) *Run { } } -func (r *Run) addResource(ext extensions.Extension, meta Meta) { +func (r *Run) addResource(ext extensions.Extension, m nodeMeta) { if err := r.graph.AddNode(ext); err != nil { r.errs = append(r.errs, fmt.Errorf("%s: %v", ext.ID(), err)) return } - r.graph.SetMeta(ext.ID(), toNodeMeta(meta)) - for _, dep := range meta.DependsOn { - if err := r.graph.AddEdge(ext.ID(), dep); err != nil { - r.errs = append(r.errs, fmt.Errorf("dependency %s -> %s: %v", ext.ID(), dep, err)) - return + + if m.Condition != nil { + for _, depID := range condition.ResourceIDs(m.Condition) { + if err := r.graph.AddEdge(ext.ID(), depID); err != nil { + r.errs = append(r.errs, fmt.Errorf("dependency %s -> %s: %v", ext.ID(), depID, err)) + return + } } + m.Condition = condition.StripResources(m.Condition) } + + r.graph.SetMeta(ext.ID(), m.toGraph()) } -// require validates that a required field is not empty, appends an error -// if it is, and returns false to signal the caller to bail out. func (r *Run) require(resource, field, value string) bool { if value == "" { r.errs = append(r.errs, fmt.Errorf("%s requires %s (got empty string)", resource, field)) @@ -62,27 +77,11 @@ func (r *Run) require(resource, field, value string) bool { return true } -// Err returns all errors encountered during blueprint execution, joined. -func (r *Run) Err() error { - return errors.Join(r.errs...) -} - -// Graph returns the resource dependency graph for engine processing. -func (r *Run) Graph() *graph.Graph { - return r.graph -} +func (r *Run) Err() error { return errors.Join(r.errs...) } +func (r *Run) Graph() *graph.Graph { return r.graph } +func (r *Run) Resources() []extensions.Extension { return r.graph.OrderedExtensions() } +func (r *Run) Platform() platform.Info { return r.platform } -// Resources returns collected extensions in insertion order. -func (r *Run) Resources() []extensions.Extension { - return r.graph.OrderedExtensions() -} - -// Platform returns detected OS, distro, package manager, and init system info. -func (r *Run) Platform() platform.Info { - return r.platform -} - -// Include runs another registered blueprint within this Run context. func (r *Run) Include(name string) { if r.app == nil { r.errs = append(r.errs, fmt.Errorf("Include(%q): no app context", name)) @@ -96,11 +95,17 @@ func (r *Run) Include(name string) { entry.fn(r) } +// nm extracts nodeMeta from flat Opts fields. Every Opts struct has the same +// 7 fields; callers pass them by name. +func nm(noop bool, retry int, limit float64, autoEdge, autoGroup *bool, cond extensions.Condition) nodeMeta { + return nodeMeta{Noop: noop, Retry: retry, Limit: limit, AutoEdge: autoEdge, AutoGroup: autoGroup, Condition: cond} +} + func (r *Run) File(path string, opts FileOpts) { if !r.require("File", "path", path) { return } - r.addResource(newFileExtension(path, opts), opts.Meta) + r.addResource(newFileExtension(path, opts), nm(opts.Noop, opts.Retry, opts.Limit, opts.AutoEdge, opts.AutoGroup, opts.Condition)) } func (r *Run) Package(name string, opts PackageOpts) { @@ -110,7 +115,7 @@ func (r *Run) Package(name string, opts PackageOpts) { if opts.State == "" { opts.State = Present } - r.addResource(newPackageExtension(name, opts, r.platform.PkgManager), opts.Meta) + r.addResource(newPackageExtension(name, opts, r.platform.PkgManager), nm(opts.Noop, opts.Retry, opts.Limit, opts.AutoEdge, opts.AutoGroup, opts.Condition)) } func (r *Run) Service(name string, opts ServiceOpts) { @@ -120,7 +125,7 @@ func (r *Run) Service(name string, opts ServiceOpts) { if opts.State == "" { opts.State = Running } - r.addResource(newServiceExtension(name, opts, r.platform.InitSystem), opts.Meta) + r.addResource(newServiceExtension(name, opts, r.platform.InitSystem), nm(opts.Noop, opts.Retry, opts.Limit, opts.AutoEdge, opts.AutoGroup, opts.Condition)) } func (r *Run) Exec(name string, opts ExecOpts) { @@ -130,21 +135,21 @@ func (r *Run) Exec(name string, opts ExecOpts) { if !r.require("Exec", "command", opts.Command) { return } - r.addResource(newExecExtension(name, opts), opts.Meta) + r.addResource(newExecExtension(name, opts), nm(opts.Noop, opts.Retry, opts.Limit, opts.AutoEdge, opts.AutoGroup, opts.Condition)) } func (r *Run) User(name string, opts UserOpts) { if !r.require("User", "name", name) { return } - r.addResource(newUserExtension(name, opts), opts.Meta) + r.addResource(newUserExtension(name, opts), nm(opts.Noop, opts.Retry, opts.Limit, opts.AutoEdge, opts.AutoGroup, opts.Condition)) } func (r *Run) Reboot(name string, opts RebootOpts) { if !r.require("Reboot", "name", name) { return } - r.addResource(newRebootExtension(name, opts), opts.Meta) + r.addResource(newRebootExtension(name, opts), nm(opts.Noop, opts.Retry, opts.Limit, opts.AutoEdge, opts.AutoGroup, opts.Condition)) } func (r *Run) Firewall(name string, opts FirewallOpts) { @@ -160,7 +165,7 @@ func (r *Run) Firewall(name string, opts FirewallOpts) { if opts.Action == "" { opts.Action = "allow" } - r.addResource(newFirewallExtension(name, opts), opts.Meta) + r.addResource(newFirewallExtension(name, opts), nm(opts.Noop, opts.Retry, opts.Limit, opts.AutoEdge, opts.AutoGroup, opts.Condition)) } func (r *Run) Template(path string, opts TemplateOpts) { @@ -170,14 +175,14 @@ func (r *Run) Template(path string, opts TemplateOpts) { if !r.require("Template", "source", opts.Source) { return } - r.addResource(newTemplateExtension(path, opts), opts.Meta) + r.addResource(newTemplateExtension(path, opts), nm(opts.Noop, opts.Retry, opts.Limit, opts.AutoEdge, opts.AutoGroup, opts.Condition)) } func (r *Run) Hostname(name string, opts HostnameOpts) { if !r.require("Hostname", "name", name) { return } - r.addResource(newHostnameExtension(name, opts), opts.Meta) + r.addResource(newHostnameExtension(name, opts), nm(opts.Noop, opts.Retry, opts.Limit, opts.AutoEdge, opts.AutoGroup, opts.Condition)) } func (r *Run) Cron(name string, opts CronOpts) { @@ -193,7 +198,7 @@ func (r *Run) Cron(name string, opts CronOpts) { if opts.State == "" { opts.State = Present } - r.addResource(newCronExtension(name, opts), opts.Meta) + r.addResource(newCronExtension(name, opts), nm(opts.Noop, opts.Retry, opts.Limit, opts.AutoEdge, opts.AutoGroup, opts.Condition)) } func (r *Run) Repository(name string, opts RepositoryOpts) { @@ -219,5 +224,5 @@ func (r *Run) Repository(name string, opts RepositoryOpts) { State: state, ManagerName: r.platform.PkgManager, Critical: opts.Critical, - }), opts.Meta) + }), nm(opts.Noop, opts.Retry, opts.Limit, opts.AutoEdge, opts.AutoGroup, opts.Condition)) } diff --git a/dsl/run_darwin.go b/dsl/run_darwin.go index a9d5179..4e2ecea 100644 --- a/dsl/run_darwin.go +++ b/dsl/run_darwin.go @@ -9,5 +9,5 @@ func (r *Run) Plist(domain string, opts PlistOpts) { if !r.require("Plist", "key", opts.Key) { return } - r.addResource(newPlistExtension(domain, opts), opts.Meta) + r.addResource(newPlistExtension(domain, opts), nm(opts.Noop, opts.Retry, opts.Limit, opts.AutoEdge, opts.AutoGroup, opts.Condition)) } diff --git a/dsl/run_linux.go b/dsl/run_linux.go index bae54ff..319014e 100644 --- a/dsl/run_linux.go +++ b/dsl/run_linux.go @@ -9,7 +9,7 @@ func (r *Run) Sysctl(key string, opts SysctlOpts) { if !r.require("Sysctl", "value", opts.Value) { return } - r.addResource(newSysctlExtension(key, opts), opts.Meta) + r.addResource(newSysctlExtension(key, opts), nm(opts.Noop, opts.Retry, opts.Limit, opts.AutoEdge, opts.AutoGroup, opts.Condition)) } func (r *Run) KernelModule(module string, opts KernelModuleOpts) { @@ -19,5 +19,5 @@ func (r *Run) KernelModule(module string, opts KernelModuleOpts) { if opts.State == "" { opts.State = ModuleLoaded } - r.addResource(newKernelModuleExtension(module, opts), opts.Meta) + r.addResource(newKernelModuleExtension(module, opts), nm(opts.Noop, opts.Retry, opts.Limit, opts.AutoEdge, opts.AutoGroup, opts.Condition)) } diff --git a/dsl/run_windows.go b/dsl/run_windows.go index 56c6a85..2e25e2d 100644 --- a/dsl/run_windows.go +++ b/dsl/run_windows.go @@ -6,7 +6,7 @@ func (r *Run) Registry(key string, opts RegistryOpts) { if !r.require("Registry", "key", key) { return } - r.addResource(newRegistryExtension(key, opts), opts.Meta) + r.addResource(newRegistryExtension(key, opts), nm(opts.Noop, opts.Retry, opts.Limit, opts.AutoEdge, opts.AutoGroup, opts.Condition)) } func (r *Run) SecurityPolicy(name string, opts SecurityPolicyOpts) { @@ -19,7 +19,7 @@ func (r *Run) SecurityPolicy(name string, opts SecurityPolicyOpts) { if !r.require("SecurityPolicy", "key", opts.Key) { return } - r.addResource(newSecurityPolicyExtension(name, opts), opts.Meta) + r.addResource(newSecurityPolicyExtension(name, opts), nm(opts.Noop, opts.Retry, opts.Limit, opts.AutoEdge, opts.AutoGroup, opts.Condition)) } func (r *Run) AuditPolicy(name string, opts AuditPolicyOpts) { @@ -29,5 +29,5 @@ func (r *Run) AuditPolicy(name string, opts AuditPolicyOpts) { if !r.require("AuditPolicy", "subcategory", opts.Subcategory) { return } - r.addResource(newAuditPolicyExtension(name, opts), opts.Meta) + r.addResource(newAuditPolicyExtension(name, opts), nm(opts.Noop, opts.Retry, opts.Limit, opts.AutoEdge, opts.AutoGroup, opts.Condition)) } diff --git a/extensions/exec/exec.go b/extensions/exec/exec.go index dfb92f8..65a9ed2 100644 --- a/extensions/exec/exec.go +++ b/extensions/exec/exec.go @@ -4,52 +4,20 @@ import ( "context" "fmt" "os" - "os/exec" - "runtime" + osexec "os/exec" "strings" "time" "github.com/TsekNet/converge/extensions" + "github.com/TsekNet/converge/internal/shell" ) -// Shell constants for the Shell field. -const ( - ShellAuto = "auto" // bash on Linux/macOS, powershell on Windows - ShellPowerShell = "powershell" // Windows PowerShell 5.1 (C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe) - ShellPwsh = "pwsh" // PowerShell 7+ (pwsh.exe from PATH) - ShellCmd = "cmd" // cmd.exe /C - ShellBash = "bash" // /bin/bash -c - ShellSh = "sh" // /bin/sh -c -) - -// defaultPowerShellPath is the full path to Windows PowerShell 5.1. -const defaultPowerShellPath = `C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe` - -// defaultPSParams are the default flags for PowerShell invocations. -var defaultPSParams = []string{"-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass"} - -// psPrefix is prepended to every PowerShell -Command invocation. -// $ErrorActionPreference = 'Stop': converts non-terminating errors to terminating, -// preventing silent failures from cmdlets that print an error but exit 0. -// $ProgressPreference = 'SilentlyContinue': suppresses Write-Progress output that -// corrupts stdout parsing for OnlyIfMatch and adds latency. -const psPrefix = "$ErrorActionPreference = 'Stop'; $ProgressPreference = 'SilentlyContinue'; " - -// psSuffix is appended to every PowerShell -Command invocation. -// Propagates $LASTEXITCODE from native executables (msiexec, reg.exe, etc.) -// to the process exit code. Without this, powershell.exe exits 0 even when -// the native exe fails. Only fires when $LASTEXITCODE is non-null (pure -// cmdlet commands never set it). -const psSuffix = "; if ($LASTEXITCODE) { exit $LASTEXITCODE }" - // Opts configures an Exec resource. type Opts struct { Command string Args []string - OnlyIf string // guard: exit 0 = in sync (or output match if OnlyIfMatch set) - OnlyIfMatch string // when set, OnlyIf compares trimmed stdout against this string - Shell string // "powershell", "pwsh", "bash", "sh", or "" (direct exec) - ShellParams []string // when set, replaces default shell flags (not the binary or -Command/-c) + Shell string // "powershell", "pwsh", "cmd", "bash", "sh", "auto", or custom path + ShellParams []string // when set, replaces default shell flags Dir string Env []string Retries int @@ -57,8 +25,8 @@ type Opts struct { Critical bool } -// Exec runs an arbitrary command. Use OnlyIf as a guard: if the guard exits 0 -// (or stdout matches OnlyIfMatch), the resource is already in sync. +// Exec runs an arbitrary command. For state detection, use condition.Shell +// on Meta.Condition instead of guards on the Exec resource itself. // // When Shell is set, Command is wrapped: the shell binary is invoked with // default flags (or ShellParams) followed by the command. Command can be @@ -67,8 +35,6 @@ type Exec struct { Name string Command string Args []string - OnlyIf string - OnlyIfMatch string Shell string ShellParams []string Dir string @@ -83,8 +49,6 @@ func New(name string, opts Opts) *Exec { Name: name, Command: opts.Command, Args: opts.Args, - OnlyIf: opts.OnlyIf, - OnlyIfMatch: opts.OnlyIfMatch, Shell: opts.Shell, ShellParams: opts.ShellParams, Dir: opts.Dir, @@ -99,84 +63,15 @@ func (e *Exec) ID() string { return fmt.Sprintf("exec:%s", e.Name) } func (e *Exec) String() string { return fmt.Sprintf("Exec %s", e.Name) } func (e *Exec) IsCritical() bool { return e.Critical } -// shellCmd builds an exec.Cmd for the given command string, respecting the -// Shell setting. When Shell is empty, the command is split on whitespace -// (for guards) or used directly with Args (for Apply). -func (e *Exec) shellCmd(ctx context.Context, command string) *exec.Cmd { - if e.Shell == "" { - parts := strings.Fields(command) - if len(parts) == 0 { - return exec.CommandContext(ctx, command) - } - return exec.CommandContext(ctx, parts[0], parts[1:]...) - } - - binary, params, shell := e.resolveShell() - args := make([]string, 0, len(params)+2) - args = append(args, params...) - - switch shell { - case ShellBash, ShellSh: - args = append(args, "-c", command) - case ShellCmd: - args = append(args, "/C", command) - default: - // PowerShell variants: wrap with error/progress preferences - args = append(args, "-Command", psPrefix+command+psSuffix) - } - - return exec.CommandContext(ctx, binary, args...) -} - -// resolveShell returns the binary path, parameter flags, and resolved shell -// name for the configured shell. The resolved name accounts for "auto" -// expanding to the platform default. -func (e *Exec) resolveShell() (binary string, params []string, shell string) { - if len(e.ShellParams) > 0 { - params = e.ShellParams - } - - shell = e.Shell - if shell == ShellAuto { - if runtime.GOOS == "windows" { - shell = ShellPowerShell - } else { - shell = ShellBash - } - } - - switch shell { - case ShellPowerShell: - binary = defaultPowerShellPath - if params == nil { - params = defaultPSParams - } - case ShellPwsh: - binary = "pwsh" - if params == nil { - params = defaultPSParams - } - case ShellCmd: - binary = `C:\Windows\System32\cmd.exe` - case ShellBash: - binary = "/bin/bash" - case ShellSh: - binary = "/bin/sh" - default: - binary = shell // allow arbitrary shell path - } - return binary, params, shell -} - // applyCmd builds an exec.Cmd for the Apply command. -func (e *Exec) applyCmd(ctx context.Context) *exec.Cmd { +func (e *Exec) applyCmd(ctx context.Context) *osexec.Cmd { if e.Shell != "" { - return e.shellCmd(ctx, e.Command) + return shell.Command(ctx, e.Shell, e.Command, e.ShellParams) } - return exec.CommandContext(ctx, e.Command, e.Args...) + return osexec.CommandContext(ctx, e.Command, e.Args...) } -func (e *Exec) setEnv(cmd *exec.Cmd) { +func (e *Exec) setEnv(cmd *osexec.Cmd) { if e.Dir != "" { cmd.Dir = e.Dir } @@ -185,25 +80,9 @@ func (e *Exec) setEnv(cmd *exec.Cmd) { } } -// checkGuard runs the OnlyIf command. When OnlyIfMatch is empty, exit 0 = in sync. -// When OnlyIfMatch is set, trimmed stdout must equal OnlyIfMatch for in-sync. -func (e *Exec) checkGuard(ctx context.Context) (*extensions.State, error) { - if e.OnlyIf == "" { - return &extensions.State{InSync: false}, nil - } - - cmd := e.shellCmd(ctx, e.OnlyIf) - e.setEnv(cmd) - - if e.OnlyIfMatch != "" { - return e.checkGuardOutput(cmd) - } - - err := cmd.Run() - if err == nil { - return &extensions.State{InSync: true}, nil - } - +// Check for Exec always returns not-in-sync (the command needs to run). +// Use condition.Shell on Meta.Condition for state detection. +func (e *Exec) Check(_ context.Context) (*extensions.State, error) { return &extensions.State{ InSync: false, Changes: []extensions.Change{ @@ -212,34 +91,6 @@ func (e *Exec) checkGuard(ctx context.Context) (*extensions.State, error) { }, nil } -// checkGuardOutput runs the guard and compares trimmed stdout to OnlyIfMatch. -func (e *Exec) checkGuardOutput(cmd *exec.Cmd) (*extensions.State, error) { - out, err := cmd.Output() - // Even if exit code is non-zero, check output: some PS commands - // return the right value but exit non-zero. - actual := strings.TrimSpace(string(out)) - - if err == nil && actual == e.OnlyIfMatch { - return &extensions.State{InSync: true}, nil - } - - from := actual - if from == "" && err != nil { - from = fmt.Sprintf("(error: %v)", err) - } - - return &extensions.State{ - InSync: false, - Changes: []extensions.Change{ - {Property: "output", From: truncate(from, 60), To: e.OnlyIfMatch, Action: "modify"}, - }, - }, nil -} - -func (e *Exec) Check(ctx context.Context) (*extensions.State, error) { - return e.checkGuard(ctx) -} - func (e *Exec) Apply(ctx context.Context) (*extensions.Result, error) { retries := e.Retries if retries <= 0 { @@ -272,10 +123,3 @@ func (e *Exec) Apply(ctx context.Context) (*extensions.Result, error) { return nil, lastErr } - -func truncate(s string, maxLen int) string { - if len(s) <= maxLen { - return s - } - return s[:maxLen] + "..." -} diff --git a/extensions/exec/exec_test.go b/extensions/exec/exec_test.go index e358204..1cf35e5 100644 --- a/extensions/exec/exec_test.go +++ b/extensions/exec/exec_test.go @@ -4,116 +4,20 @@ import ( "context" "testing" "time" -) - -func TestExec_Check(t *testing.T) { - ctx := context.Background() - - tests := []struct { - name string - onlyIf string - wantSync bool - }{ - {"no guard command", "", false}, - {"guard passes (true)", "true", true}, - {"guard fails (false)", "false", false}, - {"guard with args", "test -f /etc/os-release", true}, - {"guard file missing", "test -f /nonexistent/file", false}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - e := &Exec{Name: "test", Command: "echo", OnlyIf: tt.onlyIf} - state, err := e.Check(ctx) - if err != nil { - t.Fatalf("Check() error = %v", err) - } - if state.InSync != tt.wantSync { - t.Errorf("InSync = %v, want %v", state.InSync, tt.wantSync) - } - }) - } -} - -func TestExec_Check_OnlyIfMatch(t *testing.T) { - ctx := context.Background() - tests := []struct { - name string - onlyIf string - onlyIfMatch string - wantSync bool - }{ - {"output matches", "echo -n hello", "hello", true}, - {"output differs", "echo -n world", "hello", false}, - {"output with trailing newline", "echo hello", "hello", true}, - {"command fails, no match", "false", "hello", false}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - e := &Exec{ - Name: "test", - Command: "echo", - OnlyIf: tt.onlyIf, - OnlyIfMatch: tt.onlyIfMatch, - } - state, err := e.Check(ctx) - if err != nil { - t.Fatalf("Check() error = %v", err) - } - if state.InSync != tt.wantSync { - t.Errorf("InSync = %v, want %v", state.InSync, tt.wantSync) - } - }) - } -} - -func TestExec_Check_ShellBash(t *testing.T) { - ctx := context.Background() - - tests := []struct { - name string - onlyIf string - wantSync bool - }{ - {"bash guard passes", "exit 0", true}, - {"bash guard fails", "exit 1", false}, - {"bash multiline", "x=hello\necho $x\nexit 0", true}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - e := &Exec{ - Name: "test", - Command: "echo done", - OnlyIf: tt.onlyIf, - Shell: ShellBash, - } - state, err := e.Check(ctx) - if err != nil { - t.Fatalf("Check() error = %v", err) - } - if state.InSync != tt.wantSync { - t.Errorf("InSync = %v, want %v", state.InSync, tt.wantSync) - } - }) - } -} + "github.com/TsekNet/converge/internal/shell" +) -func TestExec_Check_ShellBash_OnlyIfMatch(t *testing.T) { +func TestExec_Check_AlwaysNotInSync(t *testing.T) { ctx := context.Background() + e := New("test", Opts{Command: "echo"}) - e := &Exec{ - Name: "test", - Command: "echo done", - OnlyIf: "echo -n myvalue", - OnlyIfMatch: "myvalue", - Shell: ShellBash, - } state, err := e.Check(ctx) if err != nil { t.Fatalf("Check() error = %v", err) } - if !state.InSync { - t.Errorf("should be in sync when bash output matches OnlyIfMatch") + if state.InSync { + t.Error("Exec.Check should always return not-in-sync (use condition.Shell for guards)") } } @@ -168,10 +72,10 @@ func TestExec_Apply_Shell(t *testing.T) { command string wantErr bool }{ - {"bash echo", ShellBash, "echo hello", false}, - {"sh echo", ShellSh, "echo hello", false}, - {"bash multiline", ShellBash, "x=42\necho $x", false}, - {"bash failure", ShellBash, "exit 1", true}, + {"bash echo", shell.Bash, "echo hello", false}, + {"sh echo", shell.Sh, "echo hello", false}, + {"bash multiline", shell.Bash, "x=42\necho $x", false}, + {"bash failure", shell.Bash, "exit 1", true}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { @@ -192,7 +96,7 @@ func TestExec_Apply_ShellParams(t *testing.T) { e := New("test", Opts{ Command: "echo custom", - Shell: ShellBash, + Shell: shell.Bash, ShellParams: []string{"-x"}, // trace mode }) result, err := e.Apply(ctx) @@ -258,85 +162,3 @@ func TestExec_IsCritical(t *testing.T) { t.Error("IsCritical() should be true when set") } } - -func TestResolveShell(t *testing.T) { - tests := []struct { - shell string - wantBinary string - wantShell string - }{ - {ShellPowerShell, defaultPowerShellPath, ShellPowerShell}, - {ShellPwsh, "pwsh", ShellPwsh}, - {ShellCmd, `C:\Windows\System32\cmd.exe`, ShellCmd}, - {ShellBash, "/bin/bash", ShellBash}, - {ShellSh, "/bin/sh", ShellSh}, - {"/usr/local/bin/zsh", "/usr/local/bin/zsh", "/usr/local/bin/zsh"}, - } - for _, tt := range tests { - t.Run(tt.shell, func(t *testing.T) { - e := &Exec{Shell: tt.shell} - binary, _, shell := e.resolveShell() - if binary != tt.wantBinary { - t.Errorf("binary = %q, want %q", binary, tt.wantBinary) - } - if shell != tt.wantShell { - t.Errorf("shell = %q, want %q", shell, tt.wantShell) - } - }) - } -} - -func TestResolveShell_CustomParams(t *testing.T) { - e := &Exec{ - Shell: ShellPowerShell, - ShellParams: []string{"-ExecutionPolicy", "RemoteSigned"}, - } - _, params, _ := e.resolveShell() - if len(params) != 2 || params[0] != "-ExecutionPolicy" { - t.Errorf("params = %v, want custom params", params) - } -} - -func TestResolveShell_Auto(t *testing.T) { - e := &Exec{Shell: ShellAuto} - _, _, got := e.resolveShell() - // On Linux (CI), auto resolves to bash - if got != ShellBash && got != ShellPowerShell { - t.Errorf("resolveShell() shell = %q, want bash or powershell", got) - } -} - -func TestResolveShell_DefaultPSParams(t *testing.T) { - e := &Exec{Shell: ShellPowerShell} - _, params, _ := e.resolveShell() - if len(params) != len(defaultPSParams) { - t.Errorf("params = %v, want default PS params %v", params, defaultPSParams) - } -} - -func TestResolveShell_EmptySliceGetsDefaults(t *testing.T) { - e := &Exec{Shell: ShellPowerShell, ShellParams: []string{}} - _, params, _ := e.resolveShell() - if len(params) != len(defaultPSParams) { - t.Errorf("empty ShellParams should get defaults, got %v", params) - } -} - -func TestTruncate(t *testing.T) { - tests := []struct { - input string - max int - want string - }{ - {"short", 10, "short"}, - {"this is way too long", 10, "this is wa..."}, - {"", 5, ""}, - } - for _, tt := range tests { - t.Run(tt.input, func(t *testing.T) { - if got := truncate(tt.input, tt.max); got != tt.want { - t.Errorf("truncate(%q, %d) = %q, want %q", tt.input, tt.max, got, tt.want) - } - }) - } -} diff --git a/internal/shell/shell.go b/internal/shell/shell.go new file mode 100644 index 0000000..e62bd62 --- /dev/null +++ b/internal/shell/shell.go @@ -0,0 +1,130 @@ +// Package shell provides shared shell resolution logic used by the exec +// extension and condition.Shell. It maps shell names (powershell, pwsh, cmd, +// bash, sh, auto) to binary paths and default parameters. +package shell + +import ( + "context" + "fmt" + "os/exec" + "runtime" + "strings" +) + +// Shell name constants. +const ( + Auto = "auto" // bash on Linux/macOS, powershell on Windows + PowerShell = "powershell" // Windows PowerShell 5.1 + Pwsh = "pwsh" // PowerShell 7+ + Cmd = "cmd" // cmd.exe /C + Bash = "bash" // /bin/bash -c + Sh = "sh" // /bin/sh -c +) + +const defaultPowerShellPath = `C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe` + +var defaultPSParams = []string{"-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass"} + +const psPrefix = "$ErrorActionPreference = 'Stop'; $ProgressPreference = 'SilentlyContinue'; " +const psSuffix = "; if ($LASTEXITCODE) { exit $LASTEXITCODE }" + +// Resolve returns the binary path, parameter flags, and resolved shell name +// for the given shell and optional custom parameters. +func Resolve(shell string, customParams []string) (binary string, params []string, resolved string) { + resolved = shell + if resolved == Auto { + if runtime.GOOS == "windows" { + resolved = PowerShell + } else { + resolved = Bash + } + } + + if len(customParams) > 0 { + params = customParams + } + + switch resolved { + case PowerShell: + binary = defaultPowerShellPath + if params == nil { + params = defaultPSParams + } + case Pwsh: + binary = "pwsh" + if params == nil { + params = defaultPSParams + } + case Cmd: + binary = `C:\Windows\System32\cmd.exe` + case Bash: + binary = "/bin/bash" + case Sh: + binary = "/bin/sh" + default: + binary = resolved // custom path + } + return binary, params, resolved +} + +// Command builds an exec.Cmd for the given shell and command string. +// The command is passed via -Command (PowerShell), /C (cmd), or -c (bash/sh). +func Command(ctx context.Context, shell, command string, customParams []string) *exec.Cmd { + binary, params, resolved := Resolve(shell, customParams) + args := make([]string, 0, len(params)+2) + args = append(args, params...) + + switch resolved { + case Bash, Sh: + args = append(args, "-c", command) + case Cmd: + args = append(args, "/C", command) + default: + args = append(args, "-Command", psPrefix+command+psSuffix) + } + + return exec.CommandContext(ctx, binary, args...) +} + +// Run executes a shell command and returns its trimmed stdout. +func Run(ctx context.Context, shell, command string, customParams []string) (stdout string, err error) { + cmd := Command(ctx, shell, command, customParams) + out, err := cmd.Output() + return strings.TrimSpace(string(out)), err +} + +// Truncate shortens a string for display in change descriptions. +func Truncate(s string, maxLen int) string { + if len(s) <= maxLen { + return s + } + return s[:maxLen] + "..." +} + +// IsPowerShell returns true if the resolved shell is a PowerShell variant. +func IsPowerShell(shell string) bool { + resolved := shell + if resolved == Auto && runtime.GOOS == "windows" { + resolved = PowerShell + } + return resolved == PowerShell || resolved == Pwsh +} + +// DirectCommand builds an exec.Cmd for a direct (no-shell) command string, +// splitting on whitespace. +func DirectCommand(ctx context.Context, command string) *exec.Cmd { + parts := strings.Fields(command) + if len(parts) == 0 { + return exec.CommandContext(ctx, command) + } + return exec.CommandContext(ctx, parts[0], parts[1:]...) +} + +// FormatOutput returns a human-readable description of command output for +// change reporting. +func FormatOutput(actual, expected string, err error) string { + if actual == "" && err != nil { + return fmt.Sprintf("(error: %v)", err) + } + return actual +}