Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 42 additions & 3 deletions docs/examples.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. |

Expand Down Expand Up @@ -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
Expand Down
17 changes: 10 additions & 7 deletions dsl/dsl.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

Expand Down
19 changes: 11 additions & 8 deletions dsl/resources.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
})
}

Expand Down
231 changes: 189 additions & 42 deletions extensions/exec/exec.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,73 +5,194 @@ 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,
}
}

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 {
Expand All @@ -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)
}
Expand All @@ -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 {
Expand All @@ -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] + "..."
}
Loading
Loading