320 lines
11 KiB
Go
320 lines
11 KiB
Go
package installation
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/xml"
|
|
"flag"
|
|
"fmt"
|
|
"io"
|
|
"os"
|
|
"os/exec"
|
|
"path/filepath"
|
|
"runtime"
|
|
"strings"
|
|
|
|
"git.a-wan.net/alan/pipelines/internal/paths"
|
|
)
|
|
|
|
const serviceMarker = "Managed by pipelines service"
|
|
const serviceLabel = "net.a-wan.pipelines"
|
|
|
|
type serviceDefinition struct {
|
|
Binary, Directory string
|
|
Args []string
|
|
Environment map[string]string
|
|
}
|
|
|
|
func xmlText(s string) string {
|
|
var b bytes.Buffer
|
|
_ = xml.EscapeText(&b, []byte(s))
|
|
return b.String()
|
|
}
|
|
|
|
func unitQuote(s string) string {
|
|
return `"` + strings.NewReplacer(`\`, `\\`, `"`, `\"`, "%", "%%").Replace(s) + `"`
|
|
}
|
|
|
|
func (d serviceDefinition) render(platform string) (string, error) {
|
|
for _, value := range append(append([]string{d.Binary, d.Directory}, d.Args...), envValues(d.Environment)...) {
|
|
if strings.ContainsAny(value, "\r\n\x00") {
|
|
return "", fmt.Errorf("service settings cannot contain line breaks or NUL")
|
|
}
|
|
}
|
|
if platform == "linux" {
|
|
var b strings.Builder
|
|
// WorkingDirectory is a path setting, not a shell-style argument list.
|
|
// Quotes become literal path characters and make an absolute path invalid.
|
|
fmt.Fprintf(&b, "# %s\n[Unit]\nDescription=Pipelines server\n\n[Service]\nType=simple\nWorkingDirectory=%s\nExecStart=%s", serviceMarker, strings.ReplaceAll(d.Directory, "%", "%%"), unitQuote(strings.ReplaceAll(d.Binary, "$", "$$")))
|
|
for _, arg := range d.Args {
|
|
fmt.Fprintf(&b, " %s", unitQuote(strings.ReplaceAll(arg, "$", "$$")))
|
|
}
|
|
b.WriteString("\nRestart=on-failure\nRestartSec=5\nUMask=0077\n")
|
|
for _, key := range serviceEnvironmentKeys {
|
|
if value, ok := d.Environment[key]; ok {
|
|
fmt.Fprintf(&b, "Environment=%s\n", unitQuote(key+"="+value))
|
|
}
|
|
}
|
|
b.WriteString("\n[Install]\nWantedBy=default.target\n")
|
|
return b.String(), nil
|
|
}
|
|
if platform == "darwin" {
|
|
var b strings.Builder
|
|
fmt.Fprintf(&b, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!-- %s -->\n<plist version=\"1.0\"><dict>\n<key>Label</key><string>%s</string>\n<key>ProgramArguments</key><array>", serviceMarker, serviceLabel)
|
|
for _, arg := range append([]string{d.Binary}, d.Args...) {
|
|
fmt.Fprintf(&b, "<string>%s</string>", xmlText(arg))
|
|
}
|
|
fmt.Fprintf(&b, "</array>\n<key>WorkingDirectory</key><string>%s</string>\n<key>RunAtLoad</key><true/>\n<key>KeepAlive</key><dict><key>SuccessfulExit</key><false/></dict>\n<key>ThrottleInterval</key><integer>5</integer>\n<key>Umask</key><integer>63</integer>\n<key>EnvironmentVariables</key><dict>", xmlText(d.Directory))
|
|
for _, key := range serviceEnvironmentKeys {
|
|
if value, ok := d.Environment[key]; ok {
|
|
fmt.Fprintf(&b, "<key>%s</key><string>%s</string>", key, xmlText(value))
|
|
}
|
|
}
|
|
b.WriteString("</dict>\n</dict></plist>\n")
|
|
return b.String(), nil
|
|
}
|
|
return "", fmt.Errorf("autostart is supported on Linux (systemd) and macOS (launchd)")
|
|
}
|
|
|
|
// Only explicitly supported settings are captured, never the complete environment
|
|
// or provider credentials. File-based notification credentials remain references.
|
|
var serviceEnvironmentKeys = []string{"PATH", "HOME", "XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_STATE_HOME", "XDG_CACHE_HOME", "PIPELINES_OPENCODE", "PIPELINES_OPENCODE_ENDPOINT", "PIPELINES_OPENCODE_ENDPOINT_PASSWORD_FILE", "PIPELINES_OPENCODE_ENDPOINT_USERNAME", "PIPELINES_NTFY_URL", "PIPELINES_NTFY_PUBLIC_URL", "PIPELINES_NTFY_TOKEN_FILE", "PIPELINES_WEB_PUBLIC_URL", "PIPELINES_CLAUDE"}
|
|
|
|
func envValues(env map[string]string) []string {
|
|
var values []string
|
|
for _, key := range serviceEnvironmentKeys {
|
|
if value, ok := env[key]; ok {
|
|
values = append(values, value)
|
|
}
|
|
}
|
|
return values
|
|
}
|
|
|
|
func serviceFile(platform string) (string, error) {
|
|
if platform == "linux" {
|
|
dir, err := os.UserConfigDir()
|
|
return filepath.Join(dir, "systemd", "user", "pipelines.service"), err
|
|
}
|
|
if platform == "darwin" {
|
|
home, err := os.UserHomeDir()
|
|
return filepath.Join(home, "Library", "LaunchAgents", serviceLabel+".plist"), err
|
|
}
|
|
return "", fmt.Errorf("autostart is supported on Linux (systemd) and macOS (launchd)")
|
|
}
|
|
|
|
func verifyServiceFile(path string) error {
|
|
info, err := os.Lstat(path)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if !info.Mode().IsRegular() {
|
|
return fmt.Errorf("refusing to replace non-regular service file %s", path)
|
|
}
|
|
data, err := os.ReadFile(path)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if !strings.Contains(string(data), serviceMarker) {
|
|
return fmt.Errorf("refusing to change unmanaged service file %s", path)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func writeServiceFile(path, content string) error {
|
|
if err := verifyServiceFile(path); err != nil && !os.IsNotExist(err) {
|
|
return err
|
|
}
|
|
if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil {
|
|
return err
|
|
}
|
|
f, err := os.CreateTemp(filepath.Dir(path), ".pipelines-service-*")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer os.Remove(f.Name())
|
|
_, writeErr := io.WriteString(f, content)
|
|
closeErr := f.Close()
|
|
if writeErr != nil {
|
|
return writeErr
|
|
}
|
|
if closeErr != nil {
|
|
return closeErr
|
|
}
|
|
return os.Rename(f.Name(), path)
|
|
}
|
|
|
|
func ServerExecutable(executable string) (string, error) {
|
|
if server, err := exec.LookPath("pipelines-server"); err == nil {
|
|
return filepath.Abs(server)
|
|
}
|
|
resolved, err := filepath.EvalSymlinks(executable)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
server := filepath.Join(filepath.Dir(resolved), "pipelines-server")
|
|
info, err := os.Stat(server)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if !info.Mode().IsRegular() || info.Mode().Perm()&0111 == 0 {
|
|
return "", fmt.Errorf("%s is not an executable server", server)
|
|
}
|
|
return server, nil
|
|
}
|
|
|
|
// ServiceCommand manages the selected native supervisor, or a standalone
|
|
// developer service when no native installation was selected.
|
|
func ServiceCommand(ctx context.Context, executable string, args []string, out, stderr io.Writer) error {
|
|
config, err := Load(executable)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if config != nil && config.Ntfy.Mode == "native" {
|
|
// Use an internal verb so an older manager fails instead of forwarding
|
|
// "service" back into this CLI recursively. Reinstall refreshes manage.py.
|
|
command := exec.CommandContext(ctx, config.Python, append([]string{filepath.Join(config.Prefix, "lib/manage.py"), "--prefix", config.Prefix, "native-service"}, args...)...)
|
|
command.Stdout, command.Stderr = out, stderr
|
|
if err := command.Run(); err != nil {
|
|
return fmt.Errorf("native service command failed (rerun ./install if the manager is outdated): %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
if config == nil && os.Getenv("PIPELINES_PREFIX") != "" {
|
|
return fmt.Errorf("PIPELINES_PREFIX does not select an existing installation; refusing to configure a standalone service")
|
|
}
|
|
help := "Usage: pipelines service enable [--print]\n pipelines service disable | status\nNative installs manage the existing server/web/ntfy supervisor, selected by PIPELINES_PREFIX or the installed CLI path.\nAutostart is per-user, at login. enable starts now; --print only previews.\nStandalone developer binaries also support enable --db FILE --addr HOST:PORT.\nRuns use the directory you invoke pipelines run from.\n"
|
|
if len(args) == 0 || args[0] == "--help" || args[0] == "help" {
|
|
_, err := io.WriteString(out, help)
|
|
return err
|
|
}
|
|
path, err := serviceFile(runtime.GOOS)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
run := func(name string, args ...string) error {
|
|
cmd := exec.CommandContext(ctx, name, args...)
|
|
cmd.Stdout = out
|
|
cmd.Stderr = stderr
|
|
if err := cmd.Run(); err != nil {
|
|
return fmt.Errorf("%s failed: %w", name, err)
|
|
}
|
|
return nil
|
|
}
|
|
domain := fmt.Sprintf("gui/%d", os.Getuid())
|
|
switch args[0] {
|
|
case "enable":
|
|
f := flag.NewFlagSet("service enable", flag.ContinueOnError)
|
|
f.SetOutput(stderr)
|
|
preview := f.Bool("print", false, "Preview service definition without writing or starting")
|
|
defaultDB, err := paths.Database()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
db := f.String("db", defaultDB, "SQLite database file")
|
|
addr := f.String("addr", "127.0.0.1:8080", "Server listen address")
|
|
if err := f.Parse(args[1:]); err != nil {
|
|
if err == flag.ErrHelp {
|
|
return nil
|
|
}
|
|
return err
|
|
}
|
|
if len(f.Args()) != 0 {
|
|
return fmt.Errorf("service enable takes no positional arguments")
|
|
}
|
|
if os.Getenv("PIPELINES_NTFY_TOKEN") != "" {
|
|
return fmt.Errorf("use PIPELINES_NTFY_TOKEN_FILE for autostart; inline tokens are not saved")
|
|
}
|
|
binary, err := ServerExecutable(executable)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
database, err := filepath.Abs(*db)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
home, err := os.UserHomeDir()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
d := serviceDefinition{Binary: binary, Directory: home, Args: []string{"-db", database, "-addr", *addr}, Environment: map[string]string{}}
|
|
for _, key := range serviceEnvironmentKeys {
|
|
if value, ok := os.LookupEnv(key); ok {
|
|
d.Environment[key] = value
|
|
}
|
|
}
|
|
for _, key := range []string{"PIPELINES_OPENCODE", "PIPELINES_OPENCODE_ENDPOINT_PASSWORD_FILE", "PIPELINES_NTFY_TOKEN_FILE"} {
|
|
if value := d.Environment[key]; value != "" && (key != "PIPELINES_OPENCODE" || strings.ContainsRune(value, filepath.Separator)) {
|
|
absolute, err := filepath.Abs(value)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
d.Environment[key] = absolute
|
|
}
|
|
}
|
|
content, err := d.render(runtime.GOOS)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if *preview {
|
|
_, err = io.WriteString(out, content)
|
|
return err
|
|
}
|
|
if err = writeServiceFile(path, content); err != nil {
|
|
return err
|
|
}
|
|
fmt.Fprintf(out, "Saved %s\n", path)
|
|
if runtime.GOOS == "linux" {
|
|
if err = run("systemctl", "--user", "daemon-reload"); err != nil {
|
|
return err
|
|
}
|
|
if err = run("systemctl", "--user", "enable", "pipelines.service"); err != nil {
|
|
return err
|
|
}
|
|
// Reconfiguration also needs to replace an already-running process.
|
|
return run("systemctl", "--user", "restart", "pipelines.service")
|
|
}
|
|
// bootout may fail when the service has not previously been loaded.
|
|
cmd := exec.CommandContext(ctx, "launchctl", "bootout", domain, path)
|
|
_ = cmd.Run()
|
|
if err = run("launchctl", "enable", domain+"/"+serviceLabel); err != nil {
|
|
return err
|
|
}
|
|
return run("launchctl", "bootstrap", domain, path)
|
|
case "disable":
|
|
if len(args) != 1 {
|
|
return fmt.Errorf("service disable takes no arguments")
|
|
}
|
|
if err = verifyServiceFile(path); err != nil {
|
|
return err
|
|
}
|
|
if runtime.GOOS == "linux" {
|
|
err = run("systemctl", "--user", "disable", "--now", "pipelines.service")
|
|
} else {
|
|
err = run("launchctl", "disable", domain+"/"+serviceLabel)
|
|
if err == nil {
|
|
err = run("launchctl", "bootout", domain, path)
|
|
}
|
|
}
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if err = os.Remove(path); err != nil {
|
|
return err
|
|
}
|
|
if runtime.GOOS == "linux" {
|
|
return run("systemctl", "--user", "daemon-reload")
|
|
}
|
|
return nil
|
|
case "status":
|
|
if len(args) != 1 {
|
|
return fmt.Errorf("service status takes no arguments")
|
|
}
|
|
if runtime.GOOS == "linux" {
|
|
return run("systemctl", "--user", "status", "pipelines.service")
|
|
}
|
|
return run("launchctl", "print", domain+"/"+serviceLabel)
|
|
default:
|
|
return fmt.Errorf("unknown service command %q\n%s", args[0], help)
|
|
}
|
|
}
|