feat: podman-compose stack units and root/user execution scopes
- syncup: podman first, docker only as fallback (podman wins on name clash;
existing docker units found in podman switch to podman)
- syncup: group podman-compose containers into one `kind: stack` unit per
project (project, working_dir, compose_files, compose_bin from labels);
disable existing member units ("part of stack <project>")
- generator: compose mode (podman-compose up/stop, WorkingDirectory) with
pod start/stop fallback when compose binary/dir/files are missing
- reconcile: stacks disabled with "stack not found" when neither compose
files nor pod exist
- root: scan root + rootless users listed in `users:` (podman only)
- non-root: config ~/.config/unitdore/units.yaml, own user units only
- sysuser package: runuser with XDG_RUNTIME_DIR/DBUS env, home/linger lookup
- install: warn when linger is not enabled for user units
- testdata/stack: podman-compose test stack and captured podman ps fixture
- docs: README, generated-units, man page, AGENTS, PLAN
This commit is contained in:
+99
-8
@@ -2,6 +2,8 @@ package systemd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"text/template"
|
||||
|
||||
@@ -12,12 +14,18 @@ const systemUnitTemplate = `# /etc/systemd/system/{{.ServiceName}}
|
||||
# Generated by unitdore — do not edit manually
|
||||
|
||||
[Unit]
|
||||
Description=Unitdore: {{.Unit.Name}} ({{.Unit.Runtime}})
|
||||
Description=Unitdore: {{.Unit.Name}} ({{.Label}})
|
||||
After=network.target{{with .RuntimeService}} {{.}}
|
||||
Requires={{.}}{{end}}
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
Type={{.ServiceType}}
|
||||
{{- if eq .ServiceType "oneshot"}}
|
||||
RemainAfterExit=yes
|
||||
{{- end}}
|
||||
{{- with .WorkingDir}}
|
||||
WorkingDirectory={{.}}
|
||||
{{- end}}
|
||||
ExecStart={{.ExecStart}}
|
||||
ExecStop={{if .ExecStop}}-{{.ExecStop}}{{end}}
|
||||
{{- if .Unit.Restart}}
|
||||
@@ -36,11 +44,17 @@ const userUnitTemplate = `# ~/.config/systemd/user/{{.ServiceName}}
|
||||
# Generated by unitdore — do not edit manually
|
||||
|
||||
[Unit]
|
||||
Description=Unitdore: {{.Unit.Name}} ({{.Unit.Runtime}})
|
||||
Description=Unitdore: {{.Unit.Name}} ({{.Label}})
|
||||
After=default.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
Type={{.ServiceType}}
|
||||
{{- if eq .ServiceType "oneshot"}}
|
||||
RemainAfterExit=yes
|
||||
{{- end}}
|
||||
{{- with .WorkingDir}}
|
||||
WorkingDirectory={{.}}
|
||||
{{- end}}
|
||||
ExecStart={{.ExecStart}}
|
||||
ExecStop={{if .ExecStop}}-{{.ExecStop}}{{end}}
|
||||
{{- if .Unit.Restart}}
|
||||
@@ -61,6 +75,9 @@ type templateData struct {
|
||||
ExecStart string
|
||||
ExecStop string
|
||||
RuntimeService string
|
||||
Label string // shown in Description
|
||||
ServiceType string // simple | oneshot
|
||||
WorkingDir string
|
||||
}
|
||||
|
||||
// ServiceName returns the systemd service name for a unit, with optional prefix/suffix.
|
||||
@@ -70,14 +87,25 @@ func ServiceName(u config.Unit, prefix, suffix string) string {
|
||||
|
||||
// Generate produces the .service file content for a unit.
|
||||
func Generate(u config.Unit, prefix, suffix string) (string, error) {
|
||||
execStart, execStop := buildExecCommands(u)
|
||||
|
||||
data := templateData{
|
||||
ServiceName: ServiceName(u, prefix, suffix),
|
||||
Unit: u,
|
||||
ExecStart: execStart,
|
||||
ExecStop: execStop,
|
||||
RuntimeService: runtimeService(u.Runtime),
|
||||
Label: u.Runtime,
|
||||
ServiceType: "simple",
|
||||
}
|
||||
|
||||
switch {
|
||||
case u.IsStack() && u.Command == "" && StackMode(u) == StackModeCompose:
|
||||
data.ExecStart, data.ExecStop = buildComposeCommands(u)
|
||||
data.Label = "podman-compose stack"
|
||||
data.WorkingDir = u.WorkingDir
|
||||
case u.IsStack() && u.Command == "":
|
||||
data.ExecStart, data.ExecStop = buildPodCommands(u)
|
||||
data.Label = "podman pod"
|
||||
data.ServiceType = "oneshot"
|
||||
default:
|
||||
data.ExecStart, data.ExecStop = buildExecCommands(u)
|
||||
}
|
||||
|
||||
tmplStr := systemUnitTemplate
|
||||
@@ -125,3 +153,66 @@ func buildExecCommands(u config.Unit) (start, stop string) {
|
||||
}
|
||||
return start, stop
|
||||
}
|
||||
|
||||
// Stack modes: compose (podman-compose up/stop) with pod start/stop as fallback.
|
||||
const (
|
||||
StackModeCompose = "compose"
|
||||
StackModePod = "pod"
|
||||
)
|
||||
|
||||
// StackMode picks how a stack unit is started: compose when the compose binary,
|
||||
// working dir and compose files all exist; otherwise pod start/stop.
|
||||
func StackMode(u config.Unit) string {
|
||||
if ComposeAvailable(u) {
|
||||
return StackModeCompose
|
||||
}
|
||||
return StackModePod
|
||||
}
|
||||
|
||||
// ComposeAvailable reports whether the stack can be driven by podman-compose.
|
||||
func ComposeAvailable(u config.Unit) bool {
|
||||
if u.ComposeBin == "" || u.WorkingDir == "" {
|
||||
return false
|
||||
}
|
||||
if !exists(u.ComposeBin) || !exists(u.WorkingDir) {
|
||||
return false
|
||||
}
|
||||
for _, f := range u.ComposeFiles {
|
||||
if !filepath.IsAbs(f) {
|
||||
f = filepath.Join(u.WorkingDir, f)
|
||||
}
|
||||
if !exists(f) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func exists(path string) bool {
|
||||
_, err := os.Stat(path)
|
||||
return err == nil
|
||||
}
|
||||
|
||||
func buildComposeCommands(u config.Unit) (start, stop string) {
|
||||
args := []string{quoteArg(u.ComposeBin), "-p", quoteArg(u.Project)}
|
||||
for _, f := range u.ComposeFiles {
|
||||
args = append(args, "-f", quoteArg(f))
|
||||
}
|
||||
base := strings.Join(args, " ")
|
||||
return base + " up", base + " stop"
|
||||
}
|
||||
|
||||
func buildPodCommands(u config.Unit) (start, stop string) {
|
||||
pod := quoteArg("pod_" + u.Project)
|
||||
return "/usr/bin/podman pod start " + pod, "/usr/bin/podman pod stop " + pod
|
||||
}
|
||||
|
||||
// quoteArg double-quotes an argument for systemd command lines if it
|
||||
// contains whitespace or quotes.
|
||||
func quoteArg(s string) string {
|
||||
if !strings.ContainsAny(s, " \t\"'\\") {
|
||||
return s
|
||||
}
|
||||
r := strings.NewReplacer(`\`, `\\`, `"`, `\"`)
|
||||
return `"` + r.Replace(s) + `"`
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package systemd
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
@@ -263,3 +265,129 @@ func TestBuildExecCommands(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// newComposeStack creates a stack unit whose compose binary, working dir and
|
||||
// compose file exist on disk (compose mode).
|
||||
func newComposeStack(t *testing.T) config.Unit {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
bin := filepath.Join(dir, "podman-compose")
|
||||
if err := os.WriteFile(bin, []byte("#!/bin/sh\n"), 0755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(dir, "compose.yaml"), []byte("services: {}\n"), 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return config.Unit{
|
||||
Name: "shop",
|
||||
Runtime: "podman",
|
||||
Kind: config.KindStack,
|
||||
Project: "shop",
|
||||
WorkingDir: dir,
|
||||
ComposeFiles: []string{"compose.yaml"},
|
||||
ComposeBin: bin,
|
||||
Enabled: true,
|
||||
}
|
||||
}
|
||||
|
||||
func TestStackMode(t *testing.T) {
|
||||
u := newComposeStack(t)
|
||||
if StackMode(u) != StackModeCompose {
|
||||
t.Errorf("StackMode() = %q, want compose", StackMode(u))
|
||||
}
|
||||
|
||||
missingFile := u
|
||||
missingFile.ComposeFiles = []string{"gone.yaml"}
|
||||
if StackMode(missingFile) != StackModePod {
|
||||
t.Error("missing compose file should fall back to pod mode")
|
||||
}
|
||||
|
||||
missingBin := u
|
||||
missingBin.ComposeBin = ""
|
||||
if StackMode(missingBin) != StackModePod {
|
||||
t.Error("missing compose binary should fall back to pod mode")
|
||||
}
|
||||
|
||||
missingDir := u
|
||||
missingDir.WorkingDir = "/nonexistent/unitdore-test"
|
||||
if StackMode(missingDir) != StackModePod {
|
||||
t.Error("missing working dir should fall back to pod mode")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenerate_StackCompose(t *testing.T) {
|
||||
u := newComposeStack(t)
|
||||
content, err := Generate(u, "", "")
|
||||
if err != nil {
|
||||
t.Fatalf("Generate() error: %v", err)
|
||||
}
|
||||
base := u.ComposeBin + " -p shop -f compose.yaml"
|
||||
for _, want := range []string{
|
||||
"Description=Unitdore: shop (podman-compose stack)",
|
||||
"Type=simple",
|
||||
"WorkingDirectory=" + u.WorkingDir,
|
||||
"ExecStart=" + base + " up",
|
||||
"ExecStop=-" + base + " stop",
|
||||
"WantedBy=multi-user.target",
|
||||
} {
|
||||
if !strings.Contains(content, want) {
|
||||
t.Errorf("Generate() missing %q in output:\n%s", want, content)
|
||||
}
|
||||
}
|
||||
if strings.Contains(content, "RemainAfterExit") || strings.Contains(content, "Requires=") {
|
||||
t.Errorf("compose stack unit has unexpected directives:\n%s", content)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenerate_StackPodFallback(t *testing.T) {
|
||||
u := newComposeStack(t)
|
||||
u.ComposeBin = ""
|
||||
u.User = "hein"
|
||||
content, err := Generate(u, "", "")
|
||||
if err != nil {
|
||||
t.Fatalf("Generate() error: %v", err)
|
||||
}
|
||||
for _, want := range []string{
|
||||
"Description=Unitdore: shop (podman pod)",
|
||||
"Type=oneshot",
|
||||
"RemainAfterExit=yes",
|
||||
"ExecStart=/usr/bin/podman pod start pod_shop",
|
||||
"ExecStop=-/usr/bin/podman pod stop pod_shop",
|
||||
"WantedBy=default.target",
|
||||
} {
|
||||
if !strings.Contains(content, want) {
|
||||
t.Errorf("Generate() missing %q in output:\n%s", want, content)
|
||||
}
|
||||
}
|
||||
if strings.Contains(content, "WorkingDirectory=") {
|
||||
t.Errorf("pod fallback should not set WorkingDirectory:\n%s", content)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenerate_StackCustomCommand(t *testing.T) {
|
||||
u := newComposeStack(t)
|
||||
u.Command = "/usr/local/bin/stack.sh"
|
||||
content, err := Generate(u, "", "")
|
||||
if err != nil {
|
||||
t.Fatalf("Generate() error: %v", err)
|
||||
}
|
||||
if !strings.Contains(content, "ExecStart=/usr/local/bin/stack.sh") {
|
||||
t.Errorf("custom command should override stack commands:\n%s", content)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildComposeCommands_Quoting(t *testing.T) {
|
||||
u := config.Unit{
|
||||
Project: "shop",
|
||||
ComposeBin: "/usr/bin/podman-compose",
|
||||
ComposeFiles: []string{"compose.yaml", "my override.yaml"},
|
||||
}
|
||||
start, stop := buildComposeCommands(u)
|
||||
wantBase := `/usr/bin/podman-compose -p shop -f compose.yaml -f "my override.yaml"`
|
||||
if start != wantBase+" up" {
|
||||
t.Errorf("start = %q", start)
|
||||
}
|
||||
if stop != wantBase+" stop" {
|
||||
t.Errorf("stop = %q", stop)
|
||||
}
|
||||
}
|
||||
|
||||
+11
-18
@@ -8,6 +8,7 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/warkanum/unitdore/config"
|
||||
"github.com/warkanum/unitdore/sysuser"
|
||||
)
|
||||
|
||||
const systemUnitDir = "/etc/systemd/system"
|
||||
@@ -19,7 +20,7 @@ func UnitPath(u config.Unit, prefix, suffix string) (string, error) {
|
||||
return filepath.Join(systemUnitDir, svcName), nil
|
||||
}
|
||||
// Rootless: write to the user's systemd config dir
|
||||
home, err := userHomeDir(u.User)
|
||||
home, err := sysuser.HomeDir(u.User)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
@@ -130,27 +131,19 @@ func systemctl(user string, args ...string) error {
|
||||
}
|
||||
|
||||
func runAsUser(user string, bin string, args ...string) ([]byte, error) {
|
||||
full := append([]string{"-u", user, "--", bin}, args...)
|
||||
return exec.Command("runuser", full...).Output()
|
||||
cmd, err := sysuser.Command(user, bin, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return cmd.Output()
|
||||
}
|
||||
|
||||
func runAsUserCmd(user string, bin string, args ...string) error {
|
||||
full := append([]string{"-u", user, "--", bin}, args...)
|
||||
cmd := exec.Command("runuser", full...)
|
||||
cmd, err := sysuser.Command(user, bin, args...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cmd.Stdout = os.Stdout
|
||||
cmd.Stderr = os.Stderr
|
||||
return cmd.Run()
|
||||
}
|
||||
|
||||
func userHomeDir(user string) (string, error) {
|
||||
out, err := exec.Command("getent", "passwd", user).Output()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("looking up user %s: %w", user, err)
|
||||
}
|
||||
// passwd format: name:pass:uid:gid:gecos:home:shell
|
||||
parts := strings.Split(strings.TrimSpace(string(out)), ":")
|
||||
if len(parts) < 6 {
|
||||
return "", fmt.Errorf("unexpected passwd entry for %s", user)
|
||||
}
|
||||
return parts[5], nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user