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
2 changes: 1 addition & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ Read `docs/design.md` for philosophy and security model, `docs/extensions.md` fo
| --- | --- |
| DSL (blueprint API) | `dsl/` (platform-specific methods in build-tagged files) |
| Extensions | `extensions/` (one subdirectory per resource type, see directory for full list) |
| Conditions | `condition/` (FileExists, MountPoint, NetworkInterface, NetworkReachable, RegistryKeyExists) |
| Conditions | [`condition/`](condition/) (see directory for full list) |
| Blueprints | `blueprints/` (baseline, per-OS, CIS benchmarks) |
| Internals | `internal/` (daemon, engine, exit, graph, logging, output, platform, version, watch, winreg) |
| CLI | `cmd/converge/` |
Expand Down
2 changes: 1 addition & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ Short version: implement the [`Extension` interface](extensions/extension.go), d

- **Go 1.26** -- use `slices`, `maps`, range-over-int
- **Table-driven tests** everywhere
- **Build tags** -- use `_linux`, `_darwin`, `_windows` (not `_unix` or `!windows`)
- **Build tags** -- use `_linux`, `_darwin`, `_windows` (not `_unix` or `!windows`). Go 1.17+ requires the `//go:build` directive for `go vet` and IDE support, even when the `_linux`/`_darwin`/`_windows` suffix also restricts compilation.
- **No stubs** -- platform-specific DSL methods live in build-tagged files; if a platform doesn't need an extension, the DSL doesn't expose it
- **Native APIs** -- prefer `golang.org/x/sys/windows`, `/proc/sys/`, `howett.net/plist` over shelling out
- **Error wrapping** with `fmt.Errorf("...: %w", err)`
Expand Down
20 changes: 14 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,9 @@ Download latest installer for your platform from the [Releases](https://github.c

## Quick start

**1. Edit a blueprint** (`blueprints/baseline.go`):
**1. Edit a blueprint** ([blueprints/baseline.go](blueprints/baseline.go)):

Blueprints are Go code compiled into the `converge` binary. Editing a blueprint requires a rebuild.

```go
package blueprints
Expand All @@ -52,15 +54,21 @@ func Baseline(r *dsl.Run) {
}
```

**2. Plan and serve:**
**2. Rebuild:**

```bash
go build -o bin/converge ./cmd/converge
```

**3. Plan and serve:**

```bash
converge plan baseline # dry-run, no root needed
sudo converge serve baseline # run as persistent daemon, re-converge on drift
sudo converge serve baseline --timeout 1s # converge and exit (CI/Packer)
bin/converge plan baseline # dry-run, no root needed
sudo bin/converge serve baseline # run as persistent daemon, re-converge on drift
sudo bin/converge serve baseline --timeout 1s # converge and exit (CI/Packer)
```

**3. Flags:**
**4. Flags:**

```bash
converge plan baseline --out=json # machine-readable output (also: serial)
Expand Down
11 changes: 3 additions & 8 deletions docs/design.md
Original file line number Diff line number Diff line change
Expand Up @@ -119,14 +119,9 @@ type Extension interface {
}
```

| State | Meaning |
|-------------|----------------------------------------------|
| `OK` | System matches desired state. Nothing to do. |
| `Drifted` | System differs from desired state. |
| `Missing` | Resource doesn't exist yet. |
| `Error` | Can't determine state (permissions, etc.). |
`Check` returns `*State{InSync: true}` when nothing needs to change, or `*State{InSync: false, Changes: [...]}` with specific property changes. See [`extensions/state.go`](../extensions/state.go).

`Check()` is read-only. `Apply()` mutates the system and is only called when `Check()` returns `Drifted` or `Missing`. A follow-up `Check()` must return `OK`, otherwise Converge reports a convergence failure.
`Check()` is read-only. `Apply()` mutates the system and is only called when `Check()` reports `InSync: false`. A follow-up `Check()` must return `InSync: true`, otherwise Converge reports a convergence failure.

**Idempotency by construction:** Run it once, drift is fixed. Run it again, nothing changes. The engine enforces this via the Check/Apply split.

Expand Down Expand Up @@ -309,7 +304,7 @@ Defined in `internal/exit/exit.go`:
- **DAG execution order.** Resources execute in topological layer order. Dependencies complete before dependents.
- **Auto-edges.** Implicit dependencies detected automatically (Service->Package, File->parent Dir).
- **Duplicate detection.** Two extensions with same `ID()` = error before any Check().
- **Critical flag.** If `Critical: true` (default), failure aborts remaining apply.
- **Critical flag.** If `Critical: true` (default: false), failure aborts remaining apply.
- **Parallel execution.** `--parallel N` runs up to N resources concurrently within each layer (default: sequential).
- **Per-resource timeout.** `--timeout` sets the deadline for each resource's Check/Apply cycle.
- **Detailed exit codes.** `--detailed-exit-codes` enables granular exit codes for CI/CD integration.
Expand Down
60 changes: 40 additions & 20 deletions docs/examples.md
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,21 @@ func Blueprint(r *dsl.Run) {

`r.Platform()` returns a `platform.Info` struct with `OS`, `Distro`, `Arch`, `PkgManager`, and `InitSystem`.

Use `p.Distro` for distro-specific logic within the same OS:

```go
func Blueprint(r *dsl.Run) {
p := r.Platform()

switch p.Distro {
case "ubuntu":
r.Package("apt-transport-https", dsl.PackageOpts{State: dsl.Present})
case "fedora":
r.Package("dnf-plugins-core", dsl.PackageOpts{State: dsl.Present})
}
}
```

For platform-specific resources like `r.Registry()` (Windows), `r.Sysctl()` (Linux), or `r.Plist()` (macOS), use Go build tags on the blueprint file itself:

```go
Expand Down Expand Up @@ -281,32 +296,32 @@ func Blueprint(r *dsl.Run) {

## Testing Blueprints

Blueprints are Go functions. Test them with `go test`:
Blueprints are Go functions compiled into the binary. Test them with `go test` by registering the blueprint and building the DAG:

```go
package myblueprint_test
package blueprints

import (
"testing"
"github.com/TsekNet/converge/dsl/testing/mock"
"github.com/myorg/myinfra/blueprints/myblueprint"
)

func TestBlueprint(t *testing.T) {
r := mock.NewRun()
myblueprint.Blueprint(r)

if !r.HasFile("/etc/motd") {
t.Error("expected /etc/motd to be declared")
}
"github.com/TsekNet/converge/dsl"
)

if !r.HasPackage("git") {
t.Error("expected git package to be declared")
func TestBaseline(t *testing.T) {
app := dsl.New()
app.Register("baseline", "test", Baseline)

// BuildGraph calls the blueprint, builds the DAG, and adds auto-edges.
// It returns an error if the blueprint declares duplicate resources,
// references missing dependencies, or fails validation.
_, err := app.BuildGraph("baseline")
if err != nil {
t.Fatalf("BuildGraph failed: %v", err)
}
}
```

No containers, no VMs, no network calls.
`BuildGraph` exercises the full blueprint: resource declaration, duplicate detection, dependency validation, and auto-edge wiring. No containers, no VMs, no network calls, no root required.

---

Expand All @@ -316,17 +331,18 @@ All option structs share these common fields via `dsl.Meta`:

| Field | Type | Default | Description |
|-------|------|---------|-------------|
| `Critical` | `bool` | `true` | If `true`, failure aborts the run. Set `false` for best-effort. |
| `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. |
| `AutoEdge` | `*bool` | `nil` | Set to `ptrFalse` to disable auto-edges for this resource. |
| `AutoGroup` | `*bool` | `nil` | Set to `ptrFalse` to disable auto-grouping for this resource. |
| `AutoEdge` | `*bool` | `nil` | Set to `falseVal := false; &falseVal` to disable auto-edges for this resource. |
| `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-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: ptrFalse` on a package to opt out.
**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:

Expand Down Expand Up @@ -478,6 +494,8 @@ r.Service(name string, opts dsl.ServiceOpts)
| macOS | `launchd` | stub (not yet implemented) |
| Windows | Windows SCM | `golang.org/x/sys/windows/svc/mgr` (native Win32) |

> **macOS note:** launchd is not yet implemented natively. Use `r.Exec()` with `launchctl` as a workaround.

**Idempotency:** Checks current state before acting. Starting a running service is a no-op.

**Examples:**
Expand Down Expand Up @@ -525,6 +543,8 @@ r.Exec(name string, opts dsl.ExecOpts)
| `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. |
| `Env` | `[]string` | `nil` | Additional environment variables (KEY=VALUE format). |
| `Retries` | `int` | `0` | Number of retry attempts on failure. |
| `RetryDelay` | `time.Duration` | `0` | Delay between retries. |

Expand Down Expand Up @@ -818,7 +838,7 @@ The `key` uses dotted notation, e.g., `net.ipv4.ip_forward`.
| Field | Type | Default | Description |
|-------|------|---------|-------------|
| `Value` | `string` | `""` | Desired kernel parameter value. Required. |
| `Persist` | `bool` | `true` | If `true`, writes to `/etc/sysctl.d/99-converge.conf` so the setting survives reboots. |
| `Persist` | `bool` | `false` | If `true`, writes to `/etc/sysctl.d/99-converge.conf` so the setting survives reboots. Set `true` for reboot persistence. |

**API:** Direct file I/O to `/proc/sys/`: no `sysctl` command.

Expand Down
2 changes: 2 additions & 0 deletions docs/extensions.md
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,8 @@ func detectManager(name string) PackageManager {
}
```

**Note:** If the package manager is not already detected by `internal/platform/`, add detection logic to the appropriate platform detector function (e.g., `detectLinuxPkgManager()` in `internal/platform/platform.go`).

### 3. Add tests

Create `extensions/pkg/dnf_test.go` with table-driven tests:
Expand Down
6 changes: 6 additions & 0 deletions dsl/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,12 @@ func (a *App) Extensions() []Item {
{"Exec", "Run commands with guards and retries"},
{"User", "Manage local user accounts"},
{"Firewall", "Manage host firewall rules (nftables, pf, Windows Firewall)"},
{"Template", "Render Go text/template to a file with variable substitution"},
{"Hostname", "Ensure system hostname matches desired value"},
{"Cron", "Manage cron jobs (Linux/macOS) and scheduled tasks (Windows)"},
{"Repository", "Manage package repository sources (APT, DNF/YUM)"},
{"KernelModule", "Load or blacklist kernel modules (Linux only)"},
{"Reboot", "Schedule and track platform-native OS reboots"},
{"Registry", "Manage Windows registry keys (Windows only)"},
{"SecurityPolicy", "Manage Windows password and lockout policies (Windows only)"},
{"AuditPolicy", "Manage Windows advanced audit policy (Windows only)"},
Expand Down
Loading