From 052a42fd1cc622f5b3c9a32ade34fa1e777f174c Mon Sep 17 00:00:00 2001 From: Dan Tsekhanskiy Date: Sun, 12 Apr 2026 14:45:38 +0000 Subject: [PATCH] feat: Add shell mode to Exec with output-based guards Add Shell, ShellParams, and OnlyIfMatch fields to ExecOpts. Supports powershell (5.1), pwsh (7+), cmd, bash, sh, auto (platform default), and custom paths. Multi-line scripts via -Command (never -File). PowerShell commands are wrapped with $ErrorActionPreference = 'Stop' and $ProgressPreference = 'SilentlyContinue' to prevent silent cmdlet failures and progress bar stdout corruption. OnlyIfMatch enables output-based state detection: guard compares trimmed stdout against expected string instead of exit code. Closes #21 --- docs/examples.md | 45 ++++++- dsl/dsl.go | 17 +-- dsl/resources.go | 19 +-- extensions/exec/exec.go | 231 ++++++++++++++++++++++++++++------- extensions/exec/exec_test.go | 198 ++++++++++++++++++++++++++++++ 5 files changed, 450 insertions(+), 60 deletions(-) diff --git a/docs/examples.md b/docs/examples.md index c77610f..5810ae8 100644 --- a/docs/examples.md +++ b/docs/examples.md @@ -497,9 +497,12 @@ r.Exec(name string, opts dsl.ExecOpts) | Field | Type | Default | Description | |-------|------|---------|-------------| -| `Command` | `string` | `""` | The command to execute. Required. | -| `Args` | `[]string` | `nil` | Arguments passed to the command. | -| `OnlyIf` | `string` | `""` | Guard command. If exits 0, `Command` is skipped (state already correct). | +| `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`. | | `Retries` | `int` | `0` | Number of retry attempts on failure. | | `RetryDelay` | `time.Duration` | `0` | Delay between retries. | @@ -535,6 +538,42 @@ r.Exec("download-agent", dsl.ExecOpts{ Retries: 3, RetryDelay: 5 * time.Second, }) + +// 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", +}) + +// PowerShell 7+: multi-line script +r.Exec("configure-defender", dsl.ExecOpts{ + Shell: "pwsh", + Command: ` + $prefs = Get-MpPreference + if ($prefs.DisableRealtimeMonitoring) { + Set-MpPreference -DisableRealtimeMonitoring $false + } + `, + OnlyIf: "(Get-MpPreference).DisableRealtimeMonitoring", + OnlyIfMatch: "False", +}) + +// PowerShell with custom parameters +r.Exec("run-with-profile", dsl.ExecOpts{ + Shell: "powershell", + ShellParams: []string{"-ExecutionPolicy", "RemoteSigned"}, + Command: "Import-Module MyModule; Invoke-Setup", +}) + +// 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", +}) ``` ### User diff --git a/dsl/dsl.go b/dsl/dsl.go index 95de29a..766dc12 100644 --- a/dsl/dsl.go +++ b/dsl/dsl.go @@ -64,13 +64,16 @@ type ServiceOpts struct { } type ExecOpts struct { - Command string - Args []string - OnlyIf string - Dir string - Env []string - Retries int - RetryDelay time.Duration + 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) + ShellParams []string // when set, replaces default shell flags + Dir string + Env []string + Retries int + RetryDelay time.Duration Meta } diff --git a/dsl/resources.go b/dsl/resources.go index 48bbd55..38094a9 100644 --- a/dsl/resources.go +++ b/dsl/resources.go @@ -49,14 +49,17 @@ func newServiceExtension(name string, opts ServiceOpts, initSystem string) exten func newExecExtension(name string, opts ExecOpts) extensions.Extension { return extexec.New(name, extexec.Opts{ - Command: opts.Command, - Args: opts.Args, - OnlyIf: opts.OnlyIf, - Dir: opts.Dir, - Env: opts.Env, - Retries: opts.Retries, - RetryDelay: opts.RetryDelay, - Critical: opts.Critical, + Command: opts.Command, + Args: opts.Args, + OnlyIf: opts.OnlyIf, + OnlyIfMatch: opts.OnlyIfMatch, + Shell: opts.Shell, + ShellParams: opts.ShellParams, + Dir: opts.Dir, + Env: opts.Env, + Retries: opts.Retries, + RetryDelay: opts.RetryDelay, + Critical: opts.Critical, }) } diff --git a/extensions/exec/exec.go b/extensions/exec/exec.go index 108e222..a89c0ed 100644 --- a/extensions/exec/exec.go +++ b/extensions/exec/exec.go @@ -5,48 +5,86 @@ import ( "fmt" "os" "os/exec" + "runtime" "strings" "time" "github.com/TsekNet/converge/extensions" ) +// 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'; " + // Opts configures an Exec resource. type Opts struct { - Command string - Args []string - OnlyIf string // if exit 0, skip Apply (guard command) - Dir string - Env []string - Retries int - RetryDelay time.Duration - Critical bool + 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) + Dir string + Env []string + Retries int + RetryDelay time.Duration + Critical bool } -// Exec runs an arbitrary command. Use OnlyIf as a guard: if the guard exits 0, the resource is already in sync. +// 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. +// +// When Shell is set, Command is wrapped: the shell binary is invoked with +// default flags (or ShellParams) followed by the command. Command can be +// multi-line. type Exec struct { - Name string - Command string - Args []string - OnlyIf string // if exit 0, skip Apply (guard command) - Dir string - Env []string - Retries int - RetryDelay time.Duration - Critical bool + Name string + Command string + Args []string + OnlyIf string + OnlyIfMatch string + Shell string + ShellParams []string + Dir string + Env []string + Retries int + RetryDelay time.Duration + Critical bool } func New(name string, opts Opts) *Exec { return &Exec{ - Name: name, - Command: opts.Command, - Args: opts.Args, - OnlyIf: opts.OnlyIf, - Dir: opts.Dir, - Env: opts.Env, - Retries: opts.Retries, - RetryDelay: opts.RetryDelay, - Critical: opts.Critical, + Name: name, + Command: opts.Command, + Args: opts.Args, + OnlyIf: opts.OnlyIf, + OnlyIfMatch: opts.OnlyIfMatch, + Shell: opts.Shell, + ShellParams: opts.ShellParams, + Dir: opts.Dir, + Env: opts.Env, + Retries: opts.Retries, + RetryDelay: opts.RetryDelay, + Critical: opts.Critical, } } @@ -54,24 +92,107 @@ 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 } -// checkGuard runs the OnlyIf command. Exit 0 = in sync (skip Apply), non-zero = needs Apply. -func (e *Exec) checkGuard(ctx context.Context) (*extensions.State, error) { - if e.OnlyIf == "" { - return &extensions.State{InSync: false}, nil +// resolvedShell returns the concrete shell name after resolving "auto". +func (e *Exec) resolvedShell() string { + if e.Shell == ShellAuto { + if runtime.GOOS == "windows" { + return ShellPowerShell + } + return ShellBash } + return e.Shell +} - parts := strings.Fields(e.OnlyIf) - if len(parts) == 0 { - return &extensions.State{InSync: false}, nil +// 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:]...) } - cmd := exec.CommandContext(ctx, parts[0], parts[1:]...) + binary, params := e.resolveShell() + args := make([]string, 0, len(params)+2) + args = append(args, params...) + + shell := e.resolvedShell() + 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) + } + + return exec.CommandContext(ctx, binary, args...) +} + +// resolveShell returns the binary path and parameter flags for the configured shell. +func (e *Exec) resolveShell() (binary string, params []string) { + if e.ShellParams != nil { + params = e.ShellParams + } + + shell := e.resolvedShell() + 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 +} + +// applyCmd builds an exec.Cmd for the Apply command. +func (e *Exec) applyCmd(ctx context.Context) *exec.Cmd { + if e.Shell != "" { + return e.shellCmd(ctx, e.Command) + } + return exec.CommandContext(ctx, e.Command, e.Args...) +} + +func (e *Exec) setEnv(cmd *exec.Cmd) { if e.Dir != "" { cmd.Dir = e.Dir } if len(e.Env) > 0 { cmd.Env = append(os.Environ(), e.Env...) } +} + +// 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 { @@ -86,6 +207,30 @@ 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) } @@ -102,13 +247,8 @@ func (e *Exec) Apply(ctx context.Context) (*extensions.Result, error) { var lastErr error for attempt := range retries { - cmd := exec.CommandContext(ctx, e.Command, e.Args...) - if e.Dir != "" { - cmd.Dir = e.Dir - } - if len(e.Env) > 0 { - cmd.Env = append(os.Environ(), e.Env...) - } + cmd := e.applyCmd(ctx) + e.setEnv(cmd) output, err := cmd.CombinedOutput() if err == nil { @@ -127,3 +267,10 @@ 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 8c1bce0..9400b55 100644 --- a/extensions/exec/exec_test.go +++ b/extensions/exec/exec_test.go @@ -34,6 +34,89 @@ func TestExec_Check(t *testing.T) { } } +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) + } + }) + } +} + +func TestExec_Check_ShellBash_OnlyIfMatch(t *testing.T) { + ctx := context.Background() + + 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") + } +} + func TestExec_Apply(t *testing.T) { ctx := context.Background() @@ -76,6 +159,51 @@ func TestExec_Apply(t *testing.T) { } } +func TestExec_Apply_Shell(t *testing.T) { + ctx := context.Background() + + tests := []struct { + name string + shell string + 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}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + e := New("test", Opts{Command: tt.command, Shell: tt.shell}) + result, err := e.Apply(ctx) + if (err != nil) != tt.wantErr { + t.Errorf("Apply() error = %v, wantErr %v", err, tt.wantErr) + } + if err == nil && !result.Changed { + t.Error("Changed should be true on success") + } + }) + } +} + +func TestExec_Apply_ShellParams(t *testing.T) { + ctx := context.Background() + + e := New("test", Opts{ + Command: "echo custom", + Shell: ShellBash, + ShellParams: []string{"-x"}, // trace mode + }) + result, err := e.Apply(ctx) + if err != nil { + t.Fatalf("Apply() error = %v", err) + } + if !result.Changed { + t.Error("Changed should be true") + } +} + func TestExec_ApplyRetries(t *testing.T) { ctx := context.Background() @@ -130,3 +258,73 @@ 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 + }{ + {ShellPowerShell, defaultPowerShellPath}, + {ShellPwsh, "pwsh"}, + {ShellCmd, `C:\Windows\System32\cmd.exe`}, + {ShellBash, "/bin/bash"}, + {ShellSh, "/bin/sh"}, + {"/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, _ := e.resolveShell() + if binary != tt.wantBinary { + t.Errorf("binary = %q, want %q", binary, tt.wantBinary) + } + }) + } +} + +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 TestResolvedShell_Auto(t *testing.T) { + e := &Exec{Shell: ShellAuto} + got := e.resolvedShell() + // On Linux (CI), auto resolves to bash + if got != ShellBash && got != ShellPowerShell { + t.Errorf("resolvedShell() = %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 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) + } + }) + } +}