diff --git a/README.md b/README.md index 59ef6bc..803d4e6 100644 --- a/README.md +++ b/README.md @@ -122,14 +122,24 @@ This is early. What is built: its own data archived into `/backups` (`--no-backup` to skip; a store kept elsewhere, PostgreSQL or S3, is backed up where it lives). +- **`uninstall [--purge]`** -- takes away what the installer put on this + machine: containers, units, binaries (and the old ones kept for rollback), + the console's and the webmail's files, the webmail's user, its Node. The + data stays -- the server's volumes or directory, Caddy's certificates, the + credentials and secrets -- with the install record marked removed, so + `install` run again with the same options brings it all back. `--purge` + removes the data too, all but `/backups`, which it names for you to + delete. Docker, and the configuration your own web server loads, are left + alone. To take one component off, run `install` again with it skipped. + - **`status`** -- what is installed, what is running, and where those two disagree: a container stopped by hand, or a deployment nothing recorded installing. It exits non-zero when they disagree, so a machine can be asked in a script whether it still matches itself. Not built yet: `join` in the interface (it is a command for now) and of -front ends on the host, `uninstall`, `certs`, and moving the server between -a container and the host. The design is in the inbuxa specification (§6.1 and +front ends on the host, `certs`, and moving the server between a container +and the host. The design is in the inbuxa specification (§6.1 and the installer draft); the phases are there too. inbuxa install --local --domain example.test --install-deps --yes @@ -180,6 +190,8 @@ is tested on a throwaway virtual machine rather than on anybody's desk: the same on the host, and a bad release put back CONSOLE_TARBALL=… WEBMAIL_TARBALL=… e2e/vm/run.sh e2e/cases/upgrade-frontends-host.sh the console and the webmail on the host, moved on + e2e/vm/run.sh e2e/cases/uninstall-containers.sh uninstalled, installed again on the data, purged + e2e/vm/run.sh e2e/cases/uninstall-host.sh the same with the server and the webmail on the host e2e/vm/run.sh e2e/cases/topology.sh growing and shrinking from a file e2e/vm/run.sh e2e/cases/status-export.sh intent against reality, and the file OLD_REF= e2e/vm/run.sh e2e/cases/upgrade-volumes.sh diff --git a/cmd/inbuxa/main.go b/cmd/inbuxa/main.go index 1cec139..ce1f089 100644 --- a/cmd/inbuxa/main.go +++ b/cmd/inbuxa/main.go @@ -50,6 +50,8 @@ const usage = `inbuxa -- install the inbuxa suite on this machine inbuxa upgrade [component…] move what is here to the releases this installer installs: --dry-run, --yes, --no-backup + inbuxa uninstall take the programs away, keep the data: + --dry-run, --yes, --purge (the data too) inbuxa export [-o FILE] write a topology file from what is here inbuxa version this program's version @@ -130,6 +132,8 @@ func main() { os.Exit(statusCmd()) case "upgrade": os.Exit(upgradeCmd(os.Args[2:])) + case "uninstall": + os.Exit(uninstallCmd(os.Args[2:])) case "version": fmt.Println(version) case "-h", "--help", "help": @@ -692,7 +696,7 @@ func upgradeCmd(args []string) int { fmt.Fprintln(os.Stderr, err.Error()) return 1 } - if !st.Installed() { + if !st.Installed() || st.Removed() { fmt.Fprintln(os.Stderr, "nothing is installed here to upgrade") return 1 } @@ -747,6 +751,74 @@ func upgradeCmd(args []string) int { return 0 } +// uninstallCmd takes away what the installer put here. The data stays +// unless --purge, and with it the install record, marked removed, so +// install run again brings everything back. +func uninstallCmd(args []string) int { + fs := flag.NewFlagSet("uninstall", flag.ContinueOnError) + fs.Usage = func() { fmt.Print(usage) } + dryRun := fs.Bool("dry-run", false, "") + yes := fs.Bool("yes", false, "") + purge := fs.Bool("purge", false, "") + if err := fs.Parse(args); err != nil { + return 2 + } + if fs.NArg() > 0 { + c := fs.Arg(0) + fmt.Fprintf(os.Stderr, "uninstall takes away the whole installation. To take only the %s off this machine,\n"+ + "run install again as before, with --%s skip: it converges, and removes it.\n", c, c) + return 2 + } + st, err := state.Load() + if err != nil { + fmt.Fprintln(os.Stderr, err.Error()) + return 1 + } + if !st.Installed() || (st.Removed() && !*purge) { + fmt.Println("Nothing is installed here to take away.") + if st.Removed() { + fmt.Printf("The data of an earlier install is kept in %s; --purge removes that too.\n", st.Dir) + } + return 0 + } + r := apply.UninstallPlan(st, *purge) + fmt.Println("Taken away:") + for _, x := range r.Remove { + fmt.Println(" - " + x) + } + if len(r.Keep) > 0 { + fmt.Println("\nKept:") + for _, x := range r.Keep { + fmt.Println(" - " + x) + } + } + if len(r.Notes) > 0 { + fmt.Println("\nWorth knowing:") + for _, x := range r.Notes { + fmt.Println(" - " + x) + } + } + if *dryRun { + return 0 + } + if !*yes { + fmt.Fprintln(os.Stderr, "\nNothing has happened yet. Pass --yes to carry this out.") + return 1 + } + f := host.Survey(context.Background()) + if !f.Root { + fmt.Fprintln(os.Stderr, "uninstalling needs root") + return 1 + } + fmt.Println("\nUninstalling:") + if err := apply.Uninstall(context.Background(), st, *purge, f, &printer{}); err != nil { + fmt.Fprintln(os.Stderr, "\nstopped: "+err.Error()) + return 1 + } + fmt.Println("\nDone.") + return 0 +} + func shapeComponent(s string) (string, error) { switch strings.ToLower(s) { case "server", "console", "webmail": @@ -771,6 +843,12 @@ func statusCmd() int { fmt.Println("Nothing is installed on this machine.") return 0 } + if st.Removed() { + fmt.Printf("Nothing is installed on this machine: uninstalled %s, with its data kept in %s.\n", + st.RemovedAt.Format("2006-01-02 15:04 UTC"), st.Dir) + fmt.Println("`inbuxa install` with the same options brings it back; `inbuxa uninstall --purge` removes the data.") + return 0 + } name := st.Machine if name == "" { diff --git a/e2e/cases/all-host.sh b/e2e/cases/all-host.sh index f6c5d6d..45058c3 100644 --- a/e2e/cases/all-host.sh +++ b/e2e/cases/all-host.sh @@ -53,6 +53,13 @@ via admin.$D -D - -o /dev/null "https://admin.$D$ASSET" | grep -qi "cache-contro via webmail.$D https://webmail.$D/api/health | grep -q '"ok":true' && ok "the webmail is healthy through nginx" || bad "the webmail through nginx" CODE=$(via mail.$D -o /dev/null -w '%{http_code}' https://mail.$D/.well-known/jmap) case "$CODE" in 30*|200|401) ok "the mail server through nginx ($CODE)" ;; *) bad "the server through nginx: $CODE" ;; esac +# The server gives a code for the webmail's own address only if it knows the +# webmail's client: registered from the secret in its environment. +USER=$(awk '/^first mailbox/ {print $3}' "$DIR/credentials.txt") +PASS=$(awk '/^first mailbox/{getline; print $2}' "$DIR/credentials.txt") +ANSWER=$(via mail.$D -X POST https://mail.$D/api/auth -H 'Content-Type: application/json' -H 'Accept: application/json' \ + -d "{\"type\":\"authCode\",\"accountName\":\"$USER\",\"accountSecret\":\"$PASS\",\"clientId\":\"ihasmail-inbuxa\",\"redirectUri\":\"https://webmail.$D/api/auth/callback\",\"codeChallenge\":\"E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM\",\"codeChallengeMethod\":\"S256\"}") +grep -q '"client_\{0,1\}[cC]ode"' <<<"$ANSWER" && ok "the server signs people in for the webmail at https://webmail.$D" || { bad "no sign-in for the webmail"; head -c 200 <<<"$ANSWER" | sed 's/^/ /'; } echo echo "==> status" diff --git a/e2e/cases/uninstall-containers.sh b/e2e/cases/uninstall-containers.sh new file mode 100644 index 0000000..ecc38ef --- /dev/null +++ b/e2e/cases/uninstall-containers.sh @@ -0,0 +1,74 @@ +#!/bin/bash +# SPDX-FileCopyrightText: 2026 Coffey Labs LLC +# SPDX-License-Identifier: AGPL-3.0-or-later +# +# inbuxa uninstall, everything in containers: the programs go and the data +# stays; install run again brings it back with the same mailbox; --purge +# then removes the data too, all but the backups. +# +# Run from the host with: e2e/vm/run.sh e2e/cases/uninstall-containers.sh +set -uo pipefail + +pass=0; fail=0 +ok() { echo " ok $*"; pass=$((pass+1)); } +bad() { echo " FAIL $*"; fail=$((fail+1)); } +DIR=/var/lib/inbuxa +rt() { command -v docker >/dev/null 2>&1 && echo docker || echo podman; } +containers() { $(rt) ps -a --filter label=com.docker.compose.project=inbuxa --format '{{.Names}}' | wc -l; } +volumes() { $(rt) volume ls --format '{{.Name}}' | grep -c '^inbuxa_'; } +signs_in() { + local user pass + user=$(awk '/^first mailbox/ {print $3}' "$DIR/credentials.txt") + pass=$(awk '/^first mailbox/{getline; print $2}' "$DIR/credentials.txt") + curl -s -X POST http://127.0.0.1:8081/api/auth -H 'Content-Type: application/json' -H 'Accept: application/json' \ + -d "{\"type\":\"authCode\",\"accountName\":\"$user\",\"accountSecret\":\"$pass\",\"clientId\":\"ihasmail-inbuxa\",\"redirectUri\":\"http://127.0.0.1:8080/api/auth/callback\",\"codeChallenge\":\"E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM\",\"codeChallengeMethod\":\"S256\"}" \ + | grep -q '"client_\{0,1\}[cC]ode"' +} + +echo "==> installed, with an archive from an upgrade" +/tmp/inbuxa install --local --domain example.test --install-deps --yes >/dev/null 2>&1 && ok "installed" || bad "install" +mkdir -p $DIR/backups && echo archive > $DIR/backups/server-test.tar.gz +signs_in && ok "the first mailbox signs in" || bad "no sign-in to start with" + +echo +echo "==> what it would do" +DRY="$(/tmp/inbuxa uninstall --dry-run 2>&1)"; rc=$? +grep -q "inbuxa_inbuxa-data" <<<"$(sed -n '/^Kept:/,$p' <<<"$DRY")" && ok "the server's volumes are kept" || { bad "dry run"; echo "$DRY" | sed 's/^/ /'; } +[ "$(containers)" = 3 ] && ok "a dry run changed nothing" || bad "containers: $(containers)" +OUT="$(/tmp/inbuxa uninstall 2>&1)"; rc=$? +[ $rc -ne 0 ] && [ "$(containers)" = 3 ] && ok "without --yes, nothing happens" || bad "it ran without --yes" +OUT="$(/tmp/inbuxa uninstall console --yes 2>&1)"; rc=$? +[ $rc -eq 2 ] && grep -q -- "--console skip" <<<"$OUT" && ok "one component points to install --console skip" || bad "uninstall console: exit $rc" + +echo +echo "==> uninstalling" +OUT="$(/tmp/inbuxa uninstall --yes 2>&1)"; rc=$? +[ $rc -eq 0 ] && ok "uninstalled (exit 0)" || { bad "exit $rc"; echo "$OUT" | tail -6 | sed 's/^/ /'; } +[ "$(containers)" = 0 ] && ok "no containers left" || bad "$(containers) containers left" +[ "$(volumes)" -ge 2 ] && ok "the volumes are kept ($(volumes))" || bad "the volumes are gone" +[ -f $DIR/credentials.txt ] && [ -f $DIR/.env ] && ok "credentials.txt and .env are kept" || bad "the credentials are gone" +[ ! -f $DIR/compose.yaml ] && ok "the compose file is gone" || bad "compose.yaml is still there" +/tmp/inbuxa status 2>&1 | grep -q "uninstalled" && ok "status says it was uninstalled, data kept" || bad "status: $(/tmp/inbuxa status 2>&1 | head -2)" +/tmp/inbuxa upgrade --yes >/dev/null 2>&1 && bad "upgrade ran on nothing" || ok "upgrade has nothing to do" + +echo +echo "==> installed again, on what was kept" +OUT="$(/tmp/inbuxa install --local --domain example.test --yes 2>&1)"; rc=$? +[ $rc -eq 0 ] && ok "install again (exit 0)" || { bad "reinstall exit $rc"; echo "$OUT" | tail -8 | sed 's/^/ /'; } +[ "$(containers)" = 3 ] && ok "three containers again" || bad "$(containers) containers" +for _ in $(seq 1 30); do signs_in && break; sleep 2; done +signs_in && ok "the same mailbox signs in: the data came back" || bad "the first mailbox no longer signs in" +/tmp/inbuxa status >/dev/null 2>&1 && ok "status: installed and in agreement" || bad "status after reinstall" + +echo +echo "==> purged" +OUT="$(/tmp/inbuxa uninstall --purge --yes 2>&1)"; rc=$? +[ $rc -eq 0 ] && ok "purged (exit 0)" || { bad "purge exit $rc"; echo "$OUT" | tail -6 | sed 's/^/ /'; } +[ "$(containers)" = 0 ] && [ "$(volumes)" = 0 ] && ok "no containers, no volumes" || bad "containers $(containers), volumes $(volumes)" +[ "$(ls -A $DIR)" = backups ] && ok "only $DIR/backups is left" || bad "left in $DIR: $(ls -A $DIR | tr '\n' ' ')" +[ ! -f /etc/inbuxa/install.json ] && ok "the install record is gone" || bad "install.json is still there" +/tmp/inbuxa status 2>&1 | grep -q "Nothing is installed" && ok "status: nothing installed" || bad "status after purge" + +echo +echo "==> $pass passed, $fail failed" +[ "$fail" -eq 0 ] diff --git a/e2e/cases/uninstall-host.sh b/e2e/cases/uninstall-host.sh new file mode 100644 index 0000000..cf447f1 --- /dev/null +++ b/e2e/cases/uninstall-host.sh @@ -0,0 +1,60 @@ +#!/bin/bash +# SPDX-FileCopyrightText: 2026 Coffey Labs LLC +# SPDX-License-Identifier: AGPL-3.0-or-later +# +# inbuxa uninstall, the server and the webmail on the host: units, binaries, +# the webmail's files and user and the installer's Node go; the server's +# directory and user stay, and install run again brings the server back on +# them; --purge takes those too. +# +# Run from the host with: e2e/vm/run.sh e2e/cases/uninstall-host.sh +set -uo pipefail + +pass=0; fail=0 +ok() { echo " ok $*"; pass=$((pass+1)); } +bad() { echo " FAIL $*"; fail=$((fail+1)); } +DIR=/var/lib/inbuxa +signs_in() { + local user pass + user=$(awk '/^first mailbox/ {print $3}' "$DIR/credentials.txt") + pass=$(awk '/^first mailbox/{getline; print $2}' "$DIR/credentials.txt") + curl -s -X POST http://127.0.0.1:8081/api/auth -H 'Content-Type: application/json' -H 'Accept: application/json' \ + -d "{\"type\":\"authCode\",\"accountName\":\"$user\",\"accountSecret\":\"$pass\",\"clientId\":\"ihasmail-inbuxa\",\"redirectUri\":\"http://127.0.0.1:8080/api/auth/callback\",\"codeChallenge\":\"E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM\",\"codeChallengeMethod\":\"S256\"}" \ + | grep -q '"client_\{0,1\}[cC]ode"' +} +user() { getent passwd "$1" >/dev/null; } +INSTALL=(/tmp/inbuxa install --local --domain example.test --server host --webmail host --install-deps --yes) + +echo "==> installed on the host" +"${INSTALL[@]}" >/dev/null 2>&1 && ok "installed" || bad "install" +signs_in && ok "the first mailbox signs in" || bad "no sign-in to start with" + +echo +echo "==> uninstalling" +OUT="$(/tmp/inbuxa uninstall --yes 2>&1)"; rc=$? +[ $rc -eq 0 ] && ok "uninstalled (exit 0)" || { bad "exit $rc"; echo "$OUT" | tail -6 | sed 's/^/ /'; } +for u in inbuxa-server inbuxa-webmail; do + [ ! -f /etc/systemd/system/$u.service ] && ! systemctl is-active --quiet $u && ok "$u is gone" || bad "$u is still there" +done +[ ! -e /usr/local/bin/inbuxa-server ] && ok "the server's binary is gone" || bad "the binary is still there" +[ ! -e $DIR/webmail ] && ! user inbuxa-webmail && ok "the webmail's files and user are gone" || bad "webmail files or user left" +[ ! -e /opt/inbuxa/node ] && ok "the installer's Node is gone" || bad "/opt/inbuxa/node is still there" +[ -f $DIR/server/config.json ] && user inbuxa && ok "the server's directory and user are kept" || bad "the server's data or user went" + +echo +echo "==> installed again, on what was kept" +OUT="$("${INSTALL[@]}" 2>&1)"; rc=$? +[ $rc -eq 0 ] && ok "install again (exit 0)" || { bad "reinstall exit $rc"; echo "$OUT" | tail -8 | sed 's/^/ /'; } +for _ in $(seq 1 30); do signs_in && break; sleep 2; done +signs_in && ok "the same mailbox signs in" || bad "the first mailbox no longer signs in" +curl -fsS http://127.0.0.1:8080/api/health | grep -q '"ok":true' && ok "the webmail is back" || bad "no webmail" + +echo +echo "==> purged" +OUT="$(/tmp/inbuxa uninstall --purge --yes 2>&1)"; rc=$? +[ $rc -eq 0 ] && ok "purged (exit 0)" || bad "purge exit $rc" +[ ! -e $DIR ] && ! user inbuxa && ok "$DIR and the inbuxa user are gone" || bad "left: $(ls -A $DIR 2>/dev/null | tr '\n' ' ') user=$(user inbuxa && echo yes)" + +echo +echo "==> $pass passed, $fail failed" +[ "$fail" -eq 0 ] diff --git a/internal/apply/apply.go b/internal/apply/apply.go index c82cba2..d34d118 100644 --- a/internal/apply/apply.go +++ b/internal/apply/apply.go @@ -228,20 +228,7 @@ func Run(ctx context.Context, p plan.Plan, f host.Facts, log Log) (*Result, erro if err := hs.Install(ctx); err != nil { return nil, err } - env := map[string]string{ - "INBUXA_ADMIN_URL": stack.ConsoleURL, - "INBUXA_WEBMAIL_URL": stack.WebmailURL, - } - if stack.Webmail { - env["INBUXA_WEBMAIL_CLIENT_SECRET"] = sec.WebmailOAuth - } - if o.Local { - env["INBUXA_PUBLIC_URL"] = stack.ServerPublicURL - } - if stack.CABundle { - env["SSL_CERT_FILE"] = filepath.Join(dir, "ca-bundle.crt") - } - if _, err := hs.WriteEnv(env); err != nil { + if _, err := hs.WriteEnv(serverEnv(o, stack, sec)); err != nil { return nil, err } log.Info("%s, %s", hostUnitPath, hs.envPath()) @@ -757,6 +744,7 @@ func saveState(st *state.State, o plan.Options, f host.Facts, log Log) { st.Machine, st.Dir, st.Domain = o.Machine, o.Dir, o.Domain st.Runtime, st.Topology = f.Runtime.Kind, o.TopologyPath st.Installer = "server " + release.ServerVersion + st.RemovedAt = nil // installed again, on what was kept st.Shapes = map[string]string{} for _, c := range []plan.Component{plan.Server, plan.Console, plan.Webmail} { if sh := o.Shape(c); sh != plan.Skip { @@ -768,25 +756,41 @@ func saveState(st *state.State, o plan.Options, f host.Facts, log Log) { } } +// verifyFor is how long Verify gives each check. +var verifyFor = time.Minute + // Verify is the last step: does what was installed actually answer? func Verify(ctx context.Context, res *Result, o plan.Options, server bool, log Log) []string { var problems []string + // Each for up to a minute: a container started a moment ago -- the + // last thing a converge does -- can refuse a connection before it + // answers, and that is not a problem to report. check := func(what, url string, want string) { - ctx, cancel := context.WithTimeout(ctx, 10*time.Second) - defer cancel() - req, _ := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) - resp, err := (&http.Client{}).Do(req) - if err != nil { - problems = append(problems, fmt.Sprintf("%s did not answer at %s: %v", what, url, err)) - return + var last string + deadline := time.Now().Add(verifyFor) + for { + ctx, cancel := context.WithTimeout(ctx, 10*time.Second) + req, _ := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) + resp, err := (&http.Client{}).Do(req) + if err == nil { + body, _ := io.ReadAll(io.LimitReader(resp.Body, 64<<10)) + resp.Body.Close() + if want == "" || strings.Contains(string(body), want) { + cancel() + log.Info("%s answers", what) + return + } + last = fmt.Sprintf("%s answered at %s but did not look like itself", what, url) + } else { + last = fmt.Sprintf("%s did not answer at %s: %v", what, url, err) + } + cancel() + if time.Now().After(deadline) { + problems = append(problems, last) + return + } + time.Sleep(2 * time.Second) } - defer resp.Body.Close() - body, _ := io.ReadAll(io.LimitReader(resp.Body, 64<<10)) - if want != "" && !strings.Contains(string(body), want) { - problems = append(problems, fmt.Sprintf("%s answered at %s but did not look like itself", what, url)) - return - } - log.Info("%s answers", what) } if server { check("the mail server", "http://127.0.0.1:8081/.well-known/jmap", "") @@ -871,6 +875,27 @@ func waitFor(ctx context.Context, log Log, what string, limit time.Duration, pro return fmt.Errorf("waited %s for %s: %w", limit, what, last) } +// serverEnv is what a server on the host reads from its environment: the +// front ends' addresses, and the webmail's client secret whenever there is +// a webmail here in either shape -- without it the server registers no +// client for the webmail, which then answers and signs nobody in. +func serverEnv(o plan.Options, stack compose.Stack, sec compose.Secrets) map[string]string { + env := map[string]string{ + "INBUXA_ADMIN_URL": stack.ConsoleURL, + "INBUXA_WEBMAIL_URL": stack.WebmailURL, + } + if stack.WebmailURL != "" { + env["INBUXA_WEBMAIL_CLIENT_SECRET"] = sec.WebmailOAuth + } + if o.Local { + env["INBUXA_PUBLIC_URL"] = stack.ServerPublicURL + } + if stack.CABundle { + env["SSL_CERT_FILE"] = filepath.Join(o.Dir, "ca-bundle.crt") + } + return env +} + // logSource is wherever a server's last lines come from: its container, or // the journal. type logSource interface { diff --git a/internal/apply/frontends_test.go b/internal/apply/frontends_test.go index b012e1a..454574c 100644 --- a/internal/apply/frontends_test.go +++ b/internal/apply/frontends_test.go @@ -88,3 +88,24 @@ func TestUnpackReplacesOnlyWhenComplete(t *testing.T) { t.Error("a failed unpack disturbed what was there") } } + +// The webmail's client is registered from the server's environment: a +// webmail in either shape needs its secret there, or it answers and signs +// nobody in. (2026.10.12.3 left it out for a webmail on the host beside a +// server on the host.) +func TestAServerOnTheHostIsGivenTheWebmailsSecretInEitherShape(t *testing.T) { + sec := compose.Secrets{WebmailOAuth: "w"} + o := plan.Options{Dir: "/var/lib/inbuxa"} + for _, s := range []compose.Stack{ + {HostServer: true, Webmail: true, WebmailURL: "https://webmail.example.org"}, + {HostServer: true, WebmailUnit: true, WebmailURL: "https://webmail.example.org"}, + } { + env := serverEnv(o, s, sec) + if env["INBUXA_WEBMAIL_CLIENT_SECRET"] != "w" || env["INBUXA_WEBMAIL_URL"] != "https://webmail.example.org" { + t.Errorf("webmail container=%v unit=%v: %v", s.Webmail, s.WebmailUnit, env) + } + } + if env := serverEnv(o, compose.Stack{HostServer: true}, sec); env["INBUXA_WEBMAIL_CLIENT_SECRET"] != "" { + t.Errorf("no webmail, and a secret anyway: %v", env) + } +} diff --git a/internal/apply/uninstall.go b/internal/apply/uninstall.go new file mode 100644 index 0000000..d4a7ac1 --- /dev/null +++ b/internal/apply/uninstall.go @@ -0,0 +1,184 @@ +// SPDX-FileCopyrightText: 2026 Coffey Labs LLC +// SPDX-License-Identifier: AGPL-3.0-or-later + +package apply + +// Uninstall takes away what the installer put on this machine. +// +// The programs go: containers and the compose project, units, binaries and +// the old ones kept for rollback, the console's and the webmail's files, the +// webmail's user, the installer's own Node. The data stays unless --purge: +// the server's volumes or its directory, Caddy's certificates, the +// credentials, the secrets and the zone file -- and the install record, +// marked removed, so `install` run again picks all of it up. +// +// Never touched, purge or not: the backups the installer made (named, for +// the operator to delete once sure), Docker and anything else the +// distribution installed, and the operator's own web server -- if it loads +// the proxy configuration that was written for it, taking that file away +// would break its next reload, so it is said instead. +// +// Taking one component off is `install` with that component skipped, which +// converges; this is the whole machine. + +import ( + "context" + "fmt" + "os" + "path/filepath" + "strings" + "time" + + "git.coffeylabs.org/inbuxa/inbuxa-installer/internal/docker" + "git.coffeylabs.org/inbuxa/inbuxa-installer/internal/host" + "git.coffeylabs.org/inbuxa/inbuxa-installer/internal/plan" + "git.coffeylabs.org/inbuxa/inbuxa-installer/internal/state" +) + +// Removal is what uninstall would do, in the words it is shown in. +type Removal struct { + Remove []string + Keep []string + Notes []string +} + +// UninstallPlan says what goes and what stays, for what is recorded here. +func UninstallPlan(st *state.State, purge bool) Removal { + var r Removal + dir := st.Dir + keepOrRemove := func(what string) { + if purge { + r.Remove = append(r.Remove, what) + } else { + r.Keep = append(r.Keep, what) + } + } + exists := func(p string) bool { _, err := os.Stat(p); return err == nil } + + if exists(filepath.Join(dir, "compose.yaml")) { + r.Remove = append(r.Remove, "the containers of the compose project in "+dir) + if st.Shapes["server"] == string(plan.Container) { + keepOrRemove("the server's volumes, inbuxa_inbuxa-etc and inbuxa_inbuxa-data (its configuration and mail)") + } + if b, _ := os.ReadFile(filepath.Join(dir, "compose.yaml")); strings.Contains(string(b), "\n caddy:\n") { + keepOrRemove("Caddy's volumes (its certificates and ACME account)") + } + } + if st.Shapes["server"] == string(plan.Host) { + r.Remove = append(r.Remove, HostServerUnit+", "+HostServerBinary+" and any older binaries kept beside it") + keepOrRemove(filepath.Join(dir, "server") + " (the server's configuration and mail) and its user, inbuxa") + } + if st.Shapes["console"] == string(plan.Host) { + r.Remove = append(r.Remove, filepath.Join(dir, "console")+" (the console's files)") + } + if st.Shapes["webmail"] == string(plan.Host) { + r.Remove = append(r.Remove, HostWebmailUnit+", "+filepath.Join(dir, "webmail")+" and its user, "+HostWebmailUser) + if exists(filepath.Dir(filepath.Dir(host.OwnPath))) { + r.Remove = append(r.Remove, "the installer's own Node, "+filepath.Dir(filepath.Dir(host.OwnPath))) + } + } + keepOrRemove("credentials.txt, .env, dns.zone and the rest of " + dir) + if exists(filepath.Join(dir, "proxy")) { + keepOrRemove(filepath.Join(dir, "proxy") + " (the configuration written for your web server)") + r.Notes = append(r.Notes, "if your web server loads anything from "+filepath.Join(dir, "proxy")+", take that out of its configuration") + } + if exists(filepath.Join(dir, "backups")) { + r.Keep = append(r.Keep, filepath.Join(dir, "backups")+" (the server's archives: delete it yourself once you are sure)") + } + if purge { + r.Remove = append(r.Remove, "the install record, "+state.Path) + } else { + r.Keep = append(r.Keep, "the install record, "+state.Path+", marked removed: `inbuxa install` with the same options brings it all back") + } + if st.ServerURL != "" { + r.Notes = append(r.Notes, "the server at "+st.ServerURL+" still lists these front ends; clear them in its console") + } + r.Notes = append(r.Notes, "Docker, and anything else the distribution installed, is left as it is") + return r +} + +// Uninstall carries the plan out. +func Uninstall(ctx context.Context, st *state.State, purge bool, f host.Facts, log Log) error { + dir := st.Dir + if _, err := os.Stat(filepath.Join(dir, "compose.yaml")); err == nil { + log.Step("removing the containers") + docker.UseRuntime(f.Runtime) + cmp := docker.Compose{Dir: dir, Runtime: f.Runtime} + args := []string{"down", "--remove-orphans"} + if purge { + args = append(args, "--volumes") + } + if err := cmp.Run(ctx, args...); err != nil { + return err + } + os.Remove(filepath.Join(dir, "compose.yaml")) + os.Remove(filepath.Join(dir, "Caddyfile")) + } + + if st.Shapes["webmail"] == string(plan.Host) { + log.Step("removing the webmail from this machine") + removeUnit(ctx, HostWebmailUnit, webmailUnitPath) + os.RemoveAll(filepath.Join(dir, "webmail")) + os.RemoveAll(filepath.Join(dir, "webmail.prev")) + os.Remove(filepath.Join(dir, "webmail.env")) + runQuiet(ctx, "userdel", HostWebmailUser) + os.RemoveAll(filepath.Dir(filepath.Dir(host.OwnPath))) + os.Remove(filepath.Dir(filepath.Dir(filepath.Dir(host.OwnPath)))) // /opt/inbuxa, if now empty + } + if st.Shapes["console"] == string(plan.Host) { + log.Step("removing the console's files") + os.RemoveAll(filepath.Join(dir, "console")) + os.RemoveAll(filepath.Join(dir, "console.prev")) + } + if st.Shapes["server"] == string(plan.Host) { + log.Step("removing the server from this machine") + removeUnit(ctx, HostServerUnit, hostUnitPath) + old, _ := filepath.Glob(HostServerBinary + ".*") + for _, p := range append(old, HostServerBinary) { + os.Remove(p) + } + os.Remove(filepath.Join(dir, "server.env")) + if purge { + os.RemoveAll(filepath.Join(dir, "server")) + runQuiet(ctx, "userdel", HostServerUser) + } + } + + if purge { + log.Step("removing the data (--purge)") + // By name, as well as by `down --volumes`: after an uninstall that + // kept them there is no compose file left to name them. + if f.Runtime.Usable { + docker.UseRuntime(f.Runtime) + for _, v := range []string{"inbuxa_inbuxa-etc", "inbuxa_inbuxa-data", "inbuxa_caddy-data", "inbuxa_caddy-config"} { + docker.Output(ctx, "volume", "rm", "--force", v) + } + } + entries, _ := os.ReadDir(dir) + for _, e := range entries { + if e.Name() == "backups" { + log.Info("left %s: delete it yourself once you are sure", filepath.Join(dir, "backups")) + continue + } + os.RemoveAll(filepath.Join(dir, e.Name())) + } + os.Remove(dir) // only if nothing is left in it + os.Remove(state.Path) + os.Remove(filepath.Dir(state.Path)) + return nil + } + now := time.Now().UTC().Truncate(time.Second) + st.RemovedAt = &now + if err := st.Save(); err != nil { + return fmt.Errorf("the programs are gone, but the record of what was kept could not be written: %w", err) + } + log.Info("the data is kept; `inbuxa install` with the same options brings it back") + return nil +} + +func removeUnit(ctx context.Context, unit, path string) { + runQuiet(ctx, "systemctl", "disable", "--now", "--quiet", unit) + os.Remove(path) + os.RemoveAll(path + ".d") + runQuiet(ctx, "systemctl", "daemon-reload") +} diff --git a/internal/apply/uninstall_test.go b/internal/apply/uninstall_test.go new file mode 100644 index 0000000..75901e5 --- /dev/null +++ b/internal/apply/uninstall_test.go @@ -0,0 +1,60 @@ +// SPDX-FileCopyrightText: 2026 Coffey Labs LLC +// SPDX-License-Identifier: AGPL-3.0-or-later + +package apply + +import ( + "os" + "path/filepath" + "strings" + "testing" + + "git.coffeylabs.org/inbuxa/inbuxa-installer/internal/state" +) + +func TestUninstallKeepsTheDataUnlessPurged(t *testing.T) { + dir := t.TempDir() + os.WriteFile(filepath.Join(dir, "compose.yaml"), []byte("services:\n server:\n caddy:\n"), 0o640) + os.MkdirAll(filepath.Join(dir, "backups"), 0o700) + st := &state.State{Dir: dir, Shapes: map[string]string{"server": "container", "console": "container", "webmail": "container"}} + + r := UninstallPlan(st, false) + all := func(l []string) string { return strings.Join(l, "\n") } + if !strings.Contains(all(r.Remove), "containers") { + t.Errorf("remove = %v", r.Remove) + } + for _, want := range []string{"inbuxa_inbuxa-data", "Caddy's volumes", "credentials.txt", "backups", "marked removed"} { + if !strings.Contains(all(r.Keep), want) { + t.Errorf("kept lacks %q: %v", want, r.Keep) + } + } + + r = UninstallPlan(st, true) + for _, want := range []string{"inbuxa_inbuxa-data", "Caddy's volumes", "credentials.txt", "the install record"} { + if !strings.Contains(all(r.Remove), want) { + t.Errorf("purge does not remove %q: %v", want, r.Remove) + } + } + if !strings.Contains(all(r.Keep), "backups") { + t.Error("purge would take the backups") + } +} + +func TestUninstallOnTheHost(t *testing.T) { + st := &state.State{Dir: t.TempDir(), Shapes: map[string]string{"server": "host", "console": "host", "webmail": "host"}, + ServerURL: ""} + r := UninstallPlan(st, false) + all := strings.Join(r.Remove, "\n") + for _, want := range []string{HostServerUnit, HostWebmailUnit, "console's files"} { + if !strings.Contains(all, want) { + t.Errorf("remove lacks %q: %v", want, r.Remove) + } + } + if !strings.Contains(strings.Join(r.Keep, "\n"), "/server (the server's configuration and mail)") { + t.Errorf("the host server's data is not kept: %v", r.Keep) + } + st.ServerURL = "https://mail.example.org" + if r := UninstallPlan(st, false); !strings.Contains(strings.Join(r.Notes, "\n"), "still lists these front ends") { + t.Errorf("a joined machine's note is missing: %v", r.Notes) + } +} diff --git a/internal/state/state.go b/internal/state/state.go index 6b3720b..657cf21 100644 --- a/internal/state/state.go +++ b/internal/state/state.go @@ -35,8 +35,16 @@ type State struct { ServerURL string `json:"serverUrl,omitempty"` // the server on another machine these front ends were joined to Updated time.Time `json:"updated"` // Installer string `json:"installer,omitempty"` // the version that wrote this + + // RemovedAt is when `inbuxa uninstall` took the programs away and kept + // the data. The shapes stay, so `install` run again picks the data up + // rather than trying a first boot on a server configured long ago. + RemovedAt *time.Time `json:"removedAt,omitempty"` } +// Removed is whether the programs were uninstalled with the data kept. +func (s *State) Removed() bool { return s.RemovedAt != nil } + const Version = 1 // Load reads the state, returning an empty one when there is none. A machine