Add explicit user-service autostart configuration
This commit is contained in:
@@ -29,6 +29,18 @@ pipelines serve -workspace-root "$HOME" # foreground server
|
|||||||
pipelines
|
pipelines
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Optional autostart at login (starts the server now):
|
||||||
|
|
||||||
|
```sh
|
||||||
|
pipelines service enable --workspace-root "$HOME"
|
||||||
|
pipelines service status
|
||||||
|
```
|
||||||
|
|
||||||
|
Uses user-level systemd on Linux or launchd on macOS; no sudo. Prefer a narrower
|
||||||
|
trusted repository root where possible. Preview with `--print`. Stop any existing
|
||||||
|
foreground/legacy server first. Disable with `pipelines service disable` before
|
||||||
|
uninstalling. See [installation](docs/install.md) for environment and boot options.
|
||||||
|
|
||||||
## Uninstall
|
## Uninstall
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
|
|||||||
+8
-10
@@ -7,7 +7,6 @@ import (
|
|||||||
"git.a-wan.net/alan/pipelines/internal/cli"
|
"git.a-wan.net/alan/pipelines/internal/cli"
|
||||||
"git.a-wan.net/alan/pipelines/internal/installation"
|
"git.a-wan.net/alan/pipelines/internal/installation"
|
||||||
"os"
|
"os"
|
||||||
"os/exec"
|
|
||||||
"os/signal"
|
"os/signal"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"syscall"
|
"syscall"
|
||||||
@@ -19,6 +18,12 @@ func main() {
|
|||||||
app := cli.App{Out: os.Stdout, Err: os.Stderr, In: os.Stdin}
|
app := cli.App{Out: os.Stdout, Err: os.Stderr, In: os.Stdin}
|
||||||
args := os.Args[1:]
|
args := os.Args[1:]
|
||||||
executable, err := os.Executable()
|
executable, err := os.Executable()
|
||||||
|
if err == nil && len(args) > 0 && args[0] == "service" {
|
||||||
|
err = installation.ServiceCommand(ctx, executable, args[1:], os.Stdout, os.Stderr)
|
||||||
|
if err == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
var config *installation.Config
|
var config *installation.Config
|
||||||
if err == nil {
|
if err == nil {
|
||||||
config, err = installation.Load(executable)
|
config, err = installation.Load(executable)
|
||||||
@@ -39,15 +44,8 @@ func main() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if err == nil && config == nil && len(args) > 0 && args[0] == "serve" {
|
if err == nil && config == nil && len(args) > 0 && args[0] == "serve" {
|
||||||
server, findErr := exec.LookPath("pipelines-server")
|
var server string
|
||||||
if findErr != nil {
|
server, err = installation.ServerExecutable(executable)
|
||||||
resolved, resolveErr := filepath.EvalSymlinks(executable)
|
|
||||||
if resolveErr != nil {
|
|
||||||
err = resolveErr
|
|
||||||
} else {
|
|
||||||
server = filepath.Join(filepath.Dir(resolved), "pipelines-server")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if err == nil {
|
if err == nil {
|
||||||
err = syscall.Exec(server, append([]string{server}, args[1:]...), os.Environ())
|
err = syscall.Exec(server, append([]string{server}, args[1:]...), os.Environ())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -35,6 +35,12 @@ second background supervisor. Configure optional services separately using norma
|
|||||||
OS tools. The old managed installation helper remains only for explicit legacy
|
OS tools. The old managed installation helper remains only for explicit legacy
|
||||||
data/lifecycle access; it is not the standard installer.
|
data/lifecycle access; it is not the standard installer.
|
||||||
|
|
||||||
|
Optional autostart is a separate explicit `pipelines service enable` step. It
|
||||||
|
uses the OS user manager directly, requires trusted workspace roots, supports a
|
||||||
|
side-effect-free preview, and captures only documented environment settings.
|
||||||
|
Uninstallation refuses to remove binaries while its autostart definition remains;
|
||||||
|
disable the service first. Installation itself still registers or starts nothing.
|
||||||
|
|
||||||
## Verification limitations
|
## Verification limitations
|
||||||
|
|
||||||
The reviewer checked official stable OpenCode 1.18.35 in isolation and found V2
|
The reviewer checked official stable OpenCode 1.18.35 in isolation and found V2
|
||||||
|
|||||||
+37
-3
@@ -45,8 +45,41 @@ selects another database, including an existing one; nothing is imported or move
|
|||||||
automatically. `pipelines serve --help` prints the actual defaults on your machine.
|
automatically. `pipelines serve --help` prints the actual defaults on your machine.
|
||||||
Drafts use the OS user cache; `PIPELINES_DRAFT_DIR` overrides that location.
|
Drafts use the OS user cache; `PIPELINES_DRAFT_DIR` overrides that location.
|
||||||
|
|
||||||
Use your OS's normal service manager if you want autostart. Pipelines does not
|
## Optional autostart
|
||||||
install a second supervisor. Native foreground startup is the default.
|
|
||||||
|
Stop any existing foreground or legacy server first, then explicitly configure
|
||||||
|
the OS user service:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
pipelines service enable --workspace-root "$HOME"
|
||||||
|
pipelines service status
|
||||||
|
```
|
||||||
|
|
||||||
|
This starts the server now and at subsequent logins. Linux uses
|
||||||
|
`systemctl --user`; macOS uses a LaunchAgent in your user `Library/LaunchAgents`.
|
||||||
|
There is no sudo, Docker dependency, or second supervisor. Choose a narrower root
|
||||||
|
if possible; repeat `--workspace-root` for multiple trusted directories. `--db`
|
||||||
|
and `--addr` select the database/listen address, just like foreground startup.
|
||||||
|
Re-run enable to update the definition and restart with the new settings.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
pipelines service enable --workspace-root "$HOME/repos" --print # preview only
|
||||||
|
pipelines service disable # stop and remove
|
||||||
|
```
|
||||||
|
|
||||||
|
Setup records the current PATH, HOME, XDG directory overrides, selected OpenCode
|
||||||
|
executable, and supported ntfy URL/token-file settings in a private service file.
|
||||||
|
It does not copy provider credentials or the rest of the shell environment.
|
||||||
|
Use `PIPELINES_NTFY_TOKEN_FILE`, not an inline token. Re-run enable after changing
|
||||||
|
these settings or moving binaries. Relative database/token-file paths are resolved
|
||||||
|
at configuration time. Services do not read your shell startup files.
|
||||||
|
|
||||||
|
On Linux this is **login autostart**, not automatically boot-without-login.
|
||||||
|
If needed, explicitly enable lingering using your system's normal administration
|
||||||
|
policy (`loginctl enable-linger "$USER"`). Pipelines does not change that policy.
|
||||||
|
macOS LaunchAgents likewise require a user login. Windows autostart is unsupported.
|
||||||
|
Use `journalctl --user -u pipelines.service` for Linux logs. On macOS inspect
|
||||||
|
`pipelines service status`; run `pipelines serve` in the foreground for diagnostics.
|
||||||
|
|
||||||
## OpenCode
|
## OpenCode
|
||||||
|
|
||||||
@@ -78,7 +111,8 @@ expose an unauthenticated pipeline server or HTTP credentials to untrusted netwo
|
|||||||
|
|
||||||
## Uninstall
|
## Uninstall
|
||||||
|
|
||||||
Stop the foreground server first, then:
|
Disable autostart with `pipelines service disable` if configured, or stop the
|
||||||
|
foreground server first, then:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
pipelines uninstall
|
pipelines uninstall
|
||||||
|
|||||||
@@ -24,3 +24,10 @@ Native generation/assistant completion parsing is regression-tested against a
|
|||||||
controlled HTTP server. Full live inference, permission enforcement by real model
|
controlled HTTP server. Full live inference, permission enforcement by real model
|
||||||
tool calls, cancellation during inference, optional Docker deployment, privileged
|
tool calls, cancellation during inference, optional Docker deployment, privileged
|
||||||
system-wide copying, and OS service-manager registration are **not tested**.
|
system-wide copying, and OS service-manager registration are **not tested**.
|
||||||
|
|
||||||
|
Autostart regression tests exercise both service-definition formats, scoped
|
||||||
|
environment capture, escaping, private files, refusal to overwrite unmanaged
|
||||||
|
files/symlinks, preview without side effects, and lifecycle calls using a mock OS
|
||||||
|
manager. The installed macOS CLI's preview was validated with `plutil -lint`.
|
||||||
|
`GOOS=linux GOARCH=amd64 go build ./cmd/...` also passed. Actual launchd/systemd
|
||||||
|
registration, logout/login restart, and Linux lingering remain **not tested**.
|
||||||
|
|||||||
@@ -33,6 +33,7 @@ var notes = map[string]string{
|
|||||||
}
|
}
|
||||||
|
|
||||||
var serviceHelp = map[string]string{
|
var serviceHelp = map[string]string{
|
||||||
|
"service": "Configure per-user OS autostart: pipelines service enable --workspace-root DIR. Use --print to preview, service status to inspect, and service disable before uninstalling. Linux uses systemd; macOS uses launchd. No sudo.",
|
||||||
"serve": "Run the native server in the foreground. Its flags are documented by pipelines serve --help. Installation never starts it automatically.",
|
"serve": "Run the native server in the foreground. Its flags are documented by pipelines serve --help. Installation never starts it automatically.",
|
||||||
"start": "Start the per-user native pipeline server and this installation's Docker ntfy together.",
|
"start": "Start the per-user native pipeline server and this installation's Docker ntfy together.",
|
||||||
"stop": "Stop both services. Active execution is interrupted; file changes are not rolled back.",
|
"stop": "Stop both services. Active execution is interrupted; file changes are not rolled back.",
|
||||||
|
|||||||
@@ -29,8 +29,10 @@ EXECUTE
|
|||||||
rpc <request.json|-> Send any protocol command (automation escape hatch)
|
rpc <request.json|-> Send any protocol command (automation escape hatch)
|
||||||
|
|
||||||
SERVER / INTERFACE
|
SERVER / INTERFACE
|
||||||
tui Open the dashboard (default with no command)
|
tui Open the dashboard (default with no command)
|
||||||
serve Start native server in the foreground (Ctrl+C stops it)
|
serve Start native server in the foreground (Ctrl+C stops it)
|
||||||
|
service enable Configure user autostart; requires --workspace-root DIR
|
||||||
|
service disable | status Stop/remove autostart, or inspect OS service status
|
||||||
uninstall [--yes] Remove verified Go binaries; retain data and drafts
|
uninstall [--yes] Remove verified Go binaries; retain data and drafts
|
||||||
|
|
||||||
Legacy managed installs: select PIPELINES_PREFIX explicitly for start/stop,
|
Legacy managed installs: select PIPELINES_PREFIX explicitly for start/stop,
|
||||||
|
|||||||
@@ -0,0 +1,318 @@
|
|||||||
|
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
|
||||||
|
fmt.Fprintf(&b, "# %s\n[Unit]\nDescription=Pipelines server\n\n[Service]\nType=simple\nWorkingDirectory=%s\nExecStart=%s", serviceMarker, unitQuote(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_NTFY_URL", "PIPELINES_NTFY_PUBLIC_URL", "PIPELINES_NTFY_TOKEN_FILE"}
|
||||||
|
|
||||||
|
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 uses the OS service manager directly, without a second supervisor.
|
||||||
|
func ServiceCommand(ctx context.Context, executable string, args []string, out, stderr io.Writer) error {
|
||||||
|
help := "Usage: pipelines service enable --workspace-root DIR [--workspace-root DIR] [--db FILE] [--addr HOST:PORT] [--print]\n pipelines service disable | status\nAutostart is per-user, at login. enable starts the server now; --print only previews.\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")
|
||||||
|
var roots []string
|
||||||
|
f.Func("workspace-root", "Trusted repository root (required; repeatable)", func(value string) error {
|
||||||
|
path, err := filepath.Abs(value)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
path, err = filepath.EvalSymlinks(path)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
info, err := os.Stat(path)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !info.IsDir() {
|
||||||
|
return fmt.Errorf("workspace root must be a directory")
|
||||||
|
}
|
||||||
|
roots = append(roots, path)
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if err := f.Parse(args[1:]); err != nil {
|
||||||
|
if err == flag.ErrHelp {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if len(f.Args()) != 0 || len(roots) == 0 {
|
||||||
|
return fmt.Errorf("service enable requires --workspace-root DIR; 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
|
||||||
|
}
|
||||||
|
d := serviceDefinition{Binary: binary, Directory: roots[0], Args: []string{"-db", database, "-addr", *addr}, Environment: map[string]string{}}
|
||||||
|
for _, root := range roots {
|
||||||
|
d.Args = append(d.Args, "-workspace-root", root)
|
||||||
|
}
|
||||||
|
for _, key := range serviceEnvironmentKeys {
|
||||||
|
if value, ok := os.LookupEnv(key); ok {
|
||||||
|
d.Environment[key] = value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, key := range []string{"PIPELINES_OPENCODE", "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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,160 @@
|
|||||||
|
package installation
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/xml"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"runtime"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestServiceDefinitionsQuotePathsAndKeepEnvironmentLimited(t *testing.T) {
|
||||||
|
d := serviceDefinition{Binary: `/some bin/server`, Directory: `/repo "quoted" 100% $USER`, Args: []string{"-workspace-root", `/repo "quoted" 100% $USER`}, Environment: map[string]string{"PATH": "/usr/bin:/custom bin", "PIPELINES_NTFY_TOKEN_FILE": "/secret & token", "PROVIDER_SECRET": "must-not-export"}}
|
||||||
|
for _, platform := range []string{"linux", "darwin"} {
|
||||||
|
text, err := d.render(platform)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if strings.Contains(text, "must-not-export") || !strings.Contains(text, serviceMarker) {
|
||||||
|
t.Fatal("unexpected credentials or missing marker", text)
|
||||||
|
}
|
||||||
|
if platform == "linux" {
|
||||||
|
if !strings.Contains(text, `"/some bin/server"`) || !strings.Contains(text, `100%% $$USER`) || !strings.Contains(text, `Environment="PATH=/usr/bin:/custom bin"`) {
|
||||||
|
t.Fatal("unsafe systemd escaping", text)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
decoder := xml.NewDecoder(strings.NewReader(text))
|
||||||
|
for {
|
||||||
|
_, err := decoder.Token()
|
||||||
|
if err == io.EOF {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal("invalid launchd XML", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !strings.Contains(text, "/secret & token") {
|
||||||
|
t.Fatal("missing XML escaping", text)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
d.Args = []string{"newline\ninjection"}
|
||||||
|
if _, err := d.render("linux"); err == nil {
|
||||||
|
t.Fatal("accepted newline injection")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestServiceWritesRefuseUnmanagedFilesAndSymlinks(t *testing.T) {
|
||||||
|
dir := t.TempDir()
|
||||||
|
path := filepath.Join(dir, "pipelines.service")
|
||||||
|
if err := os.WriteFile(path, []byte("user service"), 0600); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := writeServiceFile(path, serviceMarker); err == nil {
|
||||||
|
t.Fatal("replaced unmanaged file")
|
||||||
|
}
|
||||||
|
if err := os.Remove(path); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := os.Symlink(filepath.Join(dir, "unrelated"), path); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := writeServiceFile(path, serviceMarker); err == nil {
|
||||||
|
t.Fatal("replaced symlink")
|
||||||
|
}
|
||||||
|
if err := os.Remove(path); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for i := 0; i < 2; i++ {
|
||||||
|
if err := writeServiceFile(path, serviceMarker+"\nupdated"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
info, err := os.Stat(path)
|
||||||
|
if err != nil || info.Mode().Perm() != 0600 {
|
||||||
|
t.Fatal("service file must be private", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestServiceConfigurationPreviewAndLifecycleWithMockOSManager(t *testing.T) {
|
||||||
|
if runtime.GOOS != "darwin" && runtime.GOOS != "linux" {
|
||||||
|
t.Skip("no supported OS manager")
|
||||||
|
}
|
||||||
|
home := t.TempDir()
|
||||||
|
bin := filepath.Join(home, "bin")
|
||||||
|
root := filepath.Join(home, "repo with spaces")
|
||||||
|
for _, dir := range []string{bin, root} {
|
||||||
|
if err := os.MkdirAll(dir, 0700); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
t.Setenv("HOME", home)
|
||||||
|
t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, "config"))
|
||||||
|
t.Setenv("XDG_DATA_HOME", filepath.Join(home, "data"))
|
||||||
|
t.Setenv("PATH", bin)
|
||||||
|
t.Setenv("PIPELINES_NTFY_TOKEN", "")
|
||||||
|
server := filepath.Join(bin, "pipelines-server")
|
||||||
|
if err := os.WriteFile(server, []byte("#!/bin/sh\nexit 0\n"), 0700); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
manager := "systemctl"
|
||||||
|
if runtime.GOOS == "darwin" {
|
||||||
|
manager = "launchctl"
|
||||||
|
}
|
||||||
|
capture := filepath.Join(home, "manager-commands")
|
||||||
|
if err := os.WriteFile(filepath.Join(bin, manager), []byte("#!/bin/sh\nprintf '%s\\n' \"$*\" >> '"+capture+"'\n"), 0700); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var out bytes.Buffer
|
||||||
|
ctx := context.Background()
|
||||||
|
path, err := serviceFile(runtime.GOOS)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := ServiceCommand(ctx, server, []string{"enable"}, &out, &out); err == nil {
|
||||||
|
t.Fatal("workspace scope must be explicit")
|
||||||
|
}
|
||||||
|
args := []string{"enable", "--workspace-root", root}
|
||||||
|
if err := ServiceCommand(ctx, server, append(args, "--print"), &out, &out); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := os.Lstat(path); !os.IsNotExist(err) {
|
||||||
|
t.Fatal("preview wrote service file", err)
|
||||||
|
}
|
||||||
|
if _, err := os.Lstat(capture); !os.IsNotExist(err) {
|
||||||
|
t.Fatal("preview invoked OS manager", err)
|
||||||
|
}
|
||||||
|
for i := 0; i < 2; i++ {
|
||||||
|
if err := ServiceCommand(ctx, server, args, &out, &out); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := verifyServiceFile(path); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := Uninstall(server, []string{"--yes"}, strings.NewReader(""), &out); err == nil || !strings.Contains(err.Error(), "service disable") {
|
||||||
|
t.Fatal("uninstall must refuse registered service", err)
|
||||||
|
}
|
||||||
|
if err := ServiceCommand(ctx, server, []string{"status"}, &out, &out); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := ServiceCommand(ctx, server, []string{"disable"}, &out, &out); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if _, err := os.Lstat(path); !os.IsNotExist(err) {
|
||||||
|
t.Fatal("disable left definition", err)
|
||||||
|
}
|
||||||
|
commands, err := os.ReadFile(capture)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
for _, command := range map[string][]string{"linux": {"daemon-reload", "enable pipelines.service", "restart pipelines.service", "status pipelines.service", "disable --now pipelines.service"}, "darwin": {"enable gui/", "bootstrap gui/", "print gui/", "disable gui/", "bootout gui/"}}[runtime.GOOS] {
|
||||||
|
if !strings.Contains(string(commands), command) {
|
||||||
|
t.Fatal("missing OS manager operation", command, string(commands))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -8,6 +8,7 @@ import (
|
|||||||
"io"
|
"io"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
|
"runtime"
|
||||||
"strings"
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -26,6 +27,13 @@ func Uninstall(executable string, args []string, in io.Reader, out io.Writer) er
|
|||||||
if len(f.Args()) > 0 {
|
if len(f.Args()) > 0 {
|
||||||
return fmt.Errorf("uninstall takes no positional arguments")
|
return fmt.Errorf("uninstall takes no positional arguments")
|
||||||
}
|
}
|
||||||
|
if path, err := serviceFile(runtime.GOOS); err == nil {
|
||||||
|
if _, err = os.Lstat(path); err == nil {
|
||||||
|
return fmt.Errorf("disable autostart with pipelines service disable before uninstalling (%s)", path)
|
||||||
|
} else if !os.IsNotExist(err) {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
resolved, err := filepath.EvalSymlinks(executable)
|
resolved, err := filepath.EvalSymlinks(executable)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
|
|||||||
Reference in New Issue
Block a user