diff --git a/CHANGELOG.md b/CHANGELOG.md index e38a8b6..bb62a59 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,14 @@ or later. On Kubernetes its namespace is created if needed and labelled to admit privileged pods (`pod-security.kubernetes.io/enforce=privileged`), which its rootless BuildKit needs; when the installer may not, it stops and says what a cluster admin runs. +- **A native Builder**: `--mode native --role builder` installs the builder directly on the server, + as root, without Docker or Podman. Its static binary comes from the builder's release at the + controller's version and BuildKit from moby/buildkit's release that the installer pins, each + checked against its SHA-256. BuildKit runs as the root service `ansibleforms-buildkitd`, its + socket open to the builder's group only, and the builder as the service of its own system user. + An upgrade moves the builder to the new version and BuildKit to the installer's, an uninstall + removes both services, and a native Builder is found and taken over. Without root it is refused, + saying to run the installer with sudo or to use Docker, Podman or Kubernetes. - **`AF_CHART` names the chart to install from on Kubernetes**: a chart folder or `.tgz`, such as a test build or a copy for an air-gapped cluster, or a mirror's address, in place of the published chart. Installs and upgrades both use it. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index cd85c44..02ef1b4 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -8,6 +8,7 @@ The application itself lives in [ansibleforms/ansibleforms](https://github.com/a - [What lives where](#what-lives-where) - [Building and testing](#building-and-testing) - [Texts and languages](#texts-and-languages) +- [BuildKit's version](#buildkits-version) - [Pull requests](#pull-requests) - [Releasing](#releasing) - [Following app releases](#following-app-releases) @@ -58,6 +59,21 @@ A new or changed text goes into all eleven catalogs, with the app's own words fo --- +## BuildKit's version + +A native Builder runs the BuildKit release that `BuildkitVersion` in `internal/native/builder.go` pins, and an upgrade moves it there. +Dependabot does not see that constant, so it is bumped by hand, best together with the `moby/buildkit` image of the builder's Dockerfile. + +moby/buildkit publishes no checksum files: the SHA-256 of both archives is pinned next to the version, in `buildkitSums`, and checked on download. +Take them from GitHub's digests of the release's assets, then run the tests: + +```bash +gh api repos/moby/buildkit/releases/tags/v0.35.1 \ + --jq '.assets[] | select(.name | test("linux-(amd|arm)64.tar.gz$")) | "\(.digest) \(.name)"' +``` + +--- + ## Pull requests Open one pull request per change, against `main`, with a title such as `fix: short summary of the change`. diff --git a/README.md b/README.md index 9922ca1..03c6541 100644 --- a/README.md +++ b/README.md @@ -32,7 +32,7 @@ The first question is what to install: the whole application, or a part that joi |---|---|---| | Controller | the web interface, its database and its own Runner | Docker, Podman, Kubernetes or native | | Runner | the component that runs the playbooks of a controller elsewhere, outbound or inbound | Docker, Podman, Kubernetes or native | -| Builder | the component that builds the RTE images a controller defines and pushes them to a registry | Docker, Podman or Kubernetes | +| Builder | the component that builds the RTE images a controller defines and pushes them to a registry | Docker, Podman, Kubernetes or native | A Runner and a Builder ask for the controller's address, then join it with a join token or wait for an admin's approval. On Docker and Podman an upgrade writes their compose file again for the new version; on Kubernetes they are the Helm chart's runner and builder modes, @@ -41,7 +41,7 @@ installed and upgraded through `helm` with the values the installer keeps. A Builder has a few needs of its own: - **Controller:** AnsibleForms 7.9.0 or later; it is approved under Connections > Builders. -- **No native install:** its BuildKit runs in its container, on Docker, Podman or Kubernetes. +- **Native:** as root, the builder runs as a systemd service of its own user, BuildKit as a root service. - **Kubernetes:** the installer labels its namespace privileged. - **Rootless Podman:** it runs as the container's root, privileged in your user namespace only. diff --git a/internal/cli/install.go b/internal/cli/install.go index 49e93a7..57d2549 100644 --- a/internal/cli/install.go +++ b/internal/cli/install.go @@ -232,11 +232,11 @@ func install(ctx context.Context, f Flags) error { return nil } if f.Mode == string(state.Native) { - // a builder runs BuildKit in a container : it needs an engine or a cluster - if builder() { - return errors.New(i18n.T("native.cannot_builder")) - } if why := nativeSupported(); why != "" { + // a builder's BuildKit runs as a root service : root, or containers + if builder() && why == "root" { + why = "builder" + } return errors.New(i18n.T("native.cannot_" + why)) } p.mode = f.Mode @@ -280,9 +280,12 @@ func install(ctx context.Context, f Flags) error { home, _ := os.UserHomeDir() def = filepath.Join(home, filepath.Base(def)) } - if nativeMode() { + switch { + case nativeMode() && builder(): + ui.Explain(i18n.T("install.dirHelpNativeBuilder")) + case nativeMode(): ui.Explain(i18n.T("install.dirHelpNative")) - } else { + default: ui.Explain(i18n.T("install.dirHelp")) } d, err := textAgain(f.Dir, i18n.T("install.dir"), orStr(p.dir, def), notEmpty) @@ -304,7 +307,10 @@ func install(ctx context.Context, f Flags) error { } if nativeMode() { // the system user and the services are named after it - def = map[bool]string{true: "ansibleforms-runner", false: "ansibleforms"}[runner()] + def = map[string]string{compose.RoleRunner: "ansibleforms-runner", compose.RoleBuilder: "ansibleforms-builder"}[p.role] + if def == "" { + def = "ansibleforms" + } help, title = i18n.T("install.nameHelpNative"), i18n.T("install.nameNative") } ui.Explain(help) @@ -855,8 +861,8 @@ func doKubeRunner(ctx context.Context, f Flags, p *plan) error { return nil } -// doBuilder installs an RTE builder on compose : it dials the app, approved at once with a -// join token, else by an admin under Connections > Builders. +// doBuilder installs an RTE builder on compose or directly on this server : it dials the app, +// approved at once with a join token, else by an admin under Connections > Builders. // // Args: // @@ -876,7 +882,11 @@ func doBuilder(ctx context.Context, p *plan) error { r.JoinToken = token } o := compose.Options{Role: compose.RoleBuilder, Runtime: p.runtime, Version: p.version.String(), Dir: p.dir, Name: p.name, Runner: r} - st, res, err := composeInstall(ctx, o) + install := composeInstall + if p.mode == string(state.Native) { + install = nativeInstall + } + st, res, err := install(ctx, o) if err != nil { return err } @@ -944,8 +954,8 @@ func builderDone(name string, r compose.RunnerOptions, token string) []string { // chooseEngine picks Docker or Podman, Kubernetes or this server directly, in one list : the // engines the server has as they are, Docker or Podman to install when missing, Kubernetes -// greyed out when no cluster is reached, and this server greyed out for a builder (its -// BuildKit runs in a container) or where it is not supported. +// greyed out when no cluster is reached, and this server greyed out where it is not supported +// (without root : a builder's BuildKit runs as a root service, as a controller's MariaDB does). // // Args: // @@ -955,7 +965,7 @@ func builderDone(name string, r compose.RunnerOptions, token string) []string { // prev: the answer of before (Esc), the default. // withKube: Kubernetes is listed (no --mode). // role: controller, runner (Kubernetes installs the chart's runner mode, an RTE alone) or -// builder (the chart's builder mode ; never natively). +// builder (the chart's builder mode ; natively with BuildKit as a service). // // Returns: // @@ -987,15 +997,11 @@ func chooseEngine(ctx context.Context, f Flags, tools system.Tools, prev string, } kube := withKube && tools.Kubectl && tools.Helm && tools.Cluster nativeOption := func() ui.Option { - hint := "install.modeNativeHint" - if role == compose.RoleRunner { - hint = "install.modeNativeRunnerHint" - } - why := nativeSupported() - if role == compose.RoleBuilder { - why = "builder" + hint := map[string]string{compose.RoleRunner: "install.modeNativeRunnerHint", compose.RoleBuilder: "install.modeNativeBuilderHint"}[role] + if hint == "" { + hint = "install.modeNativeHint" } - if why != "" { + if why := nativeSupported(); why != "" { return ui.Option{Label: i18n.T("install.modeNative_" + why), Value: string(state.Native), Disabled: true} } return ui.Option{Label: i18n.T("install.modeNative"), Value: string(state.Native), Hint: i18n.T(hint)} diff --git a/internal/cli/install_test.go b/internal/cli/install_test.go index 0943166..f176dc7 100644 --- a/internal/cli/install_test.go +++ b/internal/cli/install_test.go @@ -476,7 +476,8 @@ func TestInstallBuilderWizard(t *testing.T) { } // TestInstallBuilderKubeAndNative checks a builder on Kubernetes (the chart's builder mode) -// with a join token and without, a failed helm, and a builder refused directly on this server. +// with a join token and without, a failed helm, and a builder directly on this server: given +// by its flag or picked, as root, and refused without root or on a Linux it does not support. func TestInstallBuilderKubeAndNative(t *testing.T) { for _, join := range []string{"afj_x", ""} { s := fakeServer(t) @@ -493,9 +494,35 @@ func TestInstallBuilderKubeAndNative(t *testing.T) { if err := install(context.Background(), Flags{InstallerVersion: "7.9.0", Lang: "en", Role: "builder", Mode: "kubernetes", AppURL: "https://app"}); err == nil { t.Error("kube builder failed") } + // directly on this server, as root : its folder and its name under /opt, installed natively s = fakeServer(t) - if err := install(context.Background(), Flags{InstallerVersion: "7.9.0", Lang: "en", Role: "builder", Mode: "native"}); err == nil || !strings.Contains(err.Error(), "BuildKit") { - t.Errorf("native builder: %v", err) + s.app = "7.9.0" + t.Setenv("AS_ROOT", "1") + answering(t, map[string][]tui.Answer{}) + if err := install(context.Background(), Flags{InstallerVersion: "7.9.0", Lang: "en", Role: "builder", Mode: "native", AppURL: "https://app", JoinToken: "afj_x"}); err != nil || !s.called("nativeInstall") { + t.Fatalf("native builder: %v, %v", err, s.calls) + } + if st, _ := state.Load(); st.Mode != state.Native || st.Role != "builder" || st.Name != "ansibleforms-builder" || st.Dir != "/opt/ansibleforms-builder" { + t.Errorf("native builder state %+v", st) + } + // picked from the list, then a failed installation + s = fakeServer(t) + s.app = "7.9.0" + s.fail["nativeInstall"] = errors.New("systemd failed") + answering(t, map[string][]tui.Answer{title("install.runtime"): {pick("native")}}) + if err := install(context.Background(), Flags{InstallerVersion: "7.9.0", Lang: "en", Role: "builder", AppURL: "https://app"}); err == nil || !s.called("nativeInstall") { + t.Errorf("native builder failed: %v", err) + } + // without root : refused, saying to run it as root or to use containers + s = fakeServer(t) + t.Setenv("NATIVE_WHY", "root") + if err := install(context.Background(), Flags{InstallerVersion: "7.9.0", Lang: "en", Role: "builder", Mode: "native"}); err == nil || + !strings.Contains(err.Error(), "needs root") || !strings.Contains(err.Error(), "sudo") || !strings.Contains(err.Error(), "Docker, Podman or Kubernetes") { + t.Errorf("native builder without root: %v", err) + } + t.Setenv("NATIVE_WHY", "unsupported") + if err := install(context.Background(), Flags{InstallerVersion: "7.9.0", Lang: "en", Role: "builder", Mode: "native"}); err == nil || !strings.Contains(err.Error(), "not supported") { + t.Errorf("native builder unsupported: %v", err) } if s.called("nativeInstall") { t.Error("installed natively") @@ -503,8 +530,8 @@ func TestInstallBuilderKubeAndNative(t *testing.T) { } // TestBuilderChecks checks the builder's own texts and checks : a controller older than -// 7.9.0 refused, no address unattended, a join token that is none, the native choice greyed -// out and the Kubernetes one with the builder mode's hint, the review, and the role names. +// 7.9.0 refused, no address unattended, a join token that is none, the Kubernetes choice +// with the builder mode's hint, the review, and the role names. func TestBuilderChecks(t *testing.T) { ctx := context.Background() s := fakeServer(t) diff --git a/internal/detect/native.go b/internal/detect/native.go index 1660fe9..c789d26 100644 --- a/internal/detect/native.go +++ b/internal/detect/native.go @@ -20,8 +20,8 @@ type unit struct { const unitProperties = "Id,Description,User,WorkingDirectory,EnvironmentFiles,ExecStart,ActiveState" // services finds AnsibleForms run as systemd services: the units whose description, folder, -// settings or command name AnsibleForms and that run Node.js themselves (a unit that brings a -// compose project up is the containers', found with them). +// settings or command name AnsibleForms and that run Node.js or the RTE builder themselves (a +// unit that brings a compose project up is the containers', found with them). // // Args: // @@ -129,7 +129,7 @@ func parseShow(out string) []unit { // // Returns: // -// True when it names AnsibleForms and runs Node.js, not a container engine. +// True when it names AnsibleForms and runs Node.js or the RTE builder, not a container engine. func isAnsibleForms(u unit) bool { all := strings.ToLower(u.ID + " " + u.Description + " " + u.WorkingDirectory + " " + u.EnvironmentFiles + " " + u.ExecStart) if !strings.Contains(all, "ansibleforms") && !strings.Contains(all, "ansible forms") { @@ -139,7 +139,13 @@ func isAnsibleForms(u unit) bool { if strings.Contains(cmd, "docker") || strings.Contains(cmd, "podman") || strings.Contains(cmd, " compose ") { return false } - return strings.Contains(cmd, "node") || strings.Contains(cmd, "npm") + return strings.Contains(cmd, "node") || strings.Contains(cmd, "npm") || isBuilder(u) +} + +// isBuilder tells whether a unit runs the RTE builder's binary (a native Builder: its +// BuildKit's unit runs buildkitd, and is not one of AnsibleForms' own). +func isBuilder(u unit) bool { + return strings.Contains(strings.ToLower(u.ExecStart), "ansibleforms-rte-builder") } // envFile is the first EnvironmentFile of a unit (systemctl shows "path (ignore_errors=no)"). @@ -211,7 +217,11 @@ func nativeInstall(ctx context.Context, env Env, dir string, units []unit) Insta } sort.Strings(i.Units) main := rte - if app != nil { + if app != nil && isBuilder(*app) { + // a native Builder : the builder alone, named as its instance + i.Role, main = RoleBuilder, app + i.Name = strings.TrimSuffix(app.ID, ".service") + } else if app != nil { i.Role, main = RoleController, app i.Name = strings.TrimSuffix(app.ID, ".service") } else { @@ -252,12 +262,13 @@ func nativeInstall(ctx context.Context, env Env, dir string, units []unit) Insta // nativeProblem tells why native services cannot be taken over, if they cannot: the upgrade // puts a release in releases/, moves the current link and restarts and -rte, -// run by the system user with app.env and rte.env, as the installer writes them. +// run by the system user with app.env and rte.env, as the installer writes them (a +// Builder: alone, with builder.env, in its folder). // // Args: // // i: the installation found. -// app: the app's unit (nil for a Runner). +// app: the app's unit (nil for a Runner ; a Builder's builder). // rte: the RTE's unit (nil when there is none). // // Returns: @@ -265,16 +276,27 @@ func nativeInstall(ctx context.Context, env Env, dir string, units []unit) Insta // The problem's code, "" when there is none. func nativeProblem(i Install, app, rte *unit) string { layout := func(u *unit, service string) bool { - want := i.Name - if service == "rte" { + want, wd := i.Name, filepath.Join(i.Dir, "current", "server") + switch service { + case "rte": want += "-rte" + case "builder": + // the builder runs in its folder, its binary in the current release + wd = i.Dir } return u != nil && u.ID == want+".service" && u.User == i.Name && - filepath.Clean(u.WorkingDirectory) == filepath.Join(i.Dir, "current", "server") && + filepath.Clean(u.WorkingDirectory) == wd && envFile(*u) == filepath.Join(i.Dir, service+".env") } - if !layout(rte, "rte") || (i.Role == RoleController && !layout(app, "app")) { - return NativeLayout + switch i.Role { + case RoleBuilder: + if !layout(app, "builder") { + return NativeLayout + } + default: + if !layout(rte, "rte") || (i.Role == RoleController && !layout(app, "app")) { + return NativeLayout + } } target, err := os.Readlink(filepath.Join(i.Dir, "current")) if err != nil || filepath.Dir(filepath.Clean(target)) != "releases" { diff --git a/internal/detect/native_test.go b/internal/detect/native_test.go index 7883fd1..ec59c35 100644 --- a/internal/detect/native_test.go +++ b/internal/detect/native_test.go @@ -170,3 +170,45 @@ func TestNativeInstallRunnerAndProbe(t *testing.T) { t.Errorf("controller %+v", c) } } + +// TestNativeBuilder checks a native Builder's unit found as a Builder named after it, with +// its port and the version of its current release, taken over in the installer's layout ; +// and each way its layout is not the installer's. BuildKit's own unit is not AnsibleForms'. +func TestNativeBuilder(t *testing.T) { + dir := t.TempDir() + if err := os.MkdirAll(filepath.Join(dir, "releases", "7.9.0"), 0o755); err != nil { + t.Fatal(err) + } + if err := os.Symlink(filepath.Join("releases", "7.9.0"), filepath.Join(dir, "current")); err != nil { + t.Fatal(err) + } + write(t, dir, map[string]string{"builder.env": "PORT=8011\n"}) + u := unit{ID: "bx.service", User: "bx", WorkingDirectory: dir, EnvironmentFiles: filepath.Join(dir, "builder.env") + " (ignore_errors=no)", + ExecStart: "{ path=" + dir + "/current/ansibleforms-rte-builder ; argv[]=" + dir + "/current/ansibleforms-rte-builder }", ActiveState: "active"} + if !isAnsibleForms(u) || !isBuilder(u) || baseDir(u) != dir { + t.Fatalf("the builder's unit %+v", u) + } + bk := unit{ID: "ansibleforms-buildkitd.service", Description: "BuildKit of the AnsibleForms RTE builder (bx)", ExecStart: dir + "/current/buildkit/buildkitd --addr unix:///run/buildkit/buildkitd.sock"} + if isAnsibleForms(bk) { + t.Error("BuildKit's unit taken for AnsibleForms") + } + f := &fake{t: t, has: map[string]bool{}, out: map[string]string{}} + b := nativeInstall(context.Background(), f.env(), dir, []unit{u}) + if b.Role != RoleBuilder || b.Name != "bx" || b.Port != 8011 || b.Version != "7.9.0" || !b.Running || !b.Adoptable() { + t.Fatalf("builder %+v", b) + } + if st := b.State(); st.Mode != state.Native || st.Role != RoleBuilder || st.Dir != dir || st.Name != "bx" { + t.Errorf("state %+v", st) + } + for name, change := range map[string]func(u *unit){ + "another user": func(u *unit) { u.User = "root" }, + "another folder": func(u *unit) { u.WorkingDirectory = "/srv" }, + "another file": func(u *unit) { u.EnvironmentFiles = "/etc/builder.env" }, + } { + other := u + change(&other) + if p := nativeProblem(b, &other, nil); p != NativeLayout { + t.Errorf("%s: %q", name, p) + } + } +} diff --git a/internal/i18n/locales/ca.json b/internal/i18n/locales/ca.json index 8842bbc..a8e3651 100644 --- a/internal/i18n/locales/ca.json +++ b/internal/i18n/locales/ca.json @@ -412,8 +412,12 @@ "install.roleBuilderHint": "Construeix les imatges RTE definides en un AnsibleForms remot.\nLes puja al seu registre, amb BuildKit a dins.\nParla amb AnsibleForms per un únic WebSocket.", "install.roleBuilderShort": "Builder", "install.modeKubernetesBuilderHint": "El mode builder del chart de Helm, al clúster de kubectl.\nEs connecta a l'aplicació: res no hi arriba des de fora.", - "install.modeNative_builder": "Directament en aquest servidor (un Builder necessita contenidors)", - "native.cannot_builder": "Un Builder no s'instal·la directament en aquest servidor.\nEl seu BuildKit corre en un contenidor.\nUseu Docker, Podman o Kubernetes.", + "native.cannot_builder": "Un Builder directament en aquest servidor necessita root.\nEl seu BuildKit funciona com a servei de root.\nExecuta l'instal·lador amb sudo.\nSi no, fes servir Docker, Podman o Kubernetes.", + "install.modeNativeBuilderHint": "El Builder i BuildKit s'instal·len en aquest servidor.\nTots dos funcionen com a serveis systemd, BuildKit com a root.\nPer a servidors on no es permeten contenidors.", + "install.dirHelpNativeBuilder": "Aquí van el Builder, BuildKit i la seva configuració.\nTambé els fitxers dels seus builds i la memòria cau de BuildKit.", + "native.builder": "Baixant el Builder {version}", + "native.buildkit": "Instal·lant BuildKit {version}", + "native.noBuilder": "El Builder {version} no té binari per a aquest servidor.\nInstal·lar-lo directament necessita una versió amb binaris.", "builder.nameHelp": "El seu contenidor i el seu projecte compose porten aquest nom.\nTambé és el seu nom a Connexions > Builders.", "builder.needApp": "Un Builder necessita un AnsibleForms on connectar-se.\nUseu --app-url, i --join per quedar aprovat de seguida.", "builder.appUrlHelp": "L'adreça de l'AnsibleForms per al qual construeix aquest Builder.\nLa mateixa adreça que s'obre en un navegador.", diff --git a/internal/i18n/locales/de.json b/internal/i18n/locales/de.json index ac5f2cc..341621b 100644 --- a/internal/i18n/locales/de.json +++ b/internal/i18n/locales/de.json @@ -412,8 +412,12 @@ "install.roleBuilderHint": "Er baut die RTE-Images, die ein AnsibleForms anderswo definiert.\nEr schiebt sie in ihre Registry, mit BuildKit in ihm.\nEr spricht mit AnsibleForms über einen einzigen WebSocket.", "install.roleBuilderShort": "Builder", "install.modeKubernetesBuilderHint": "Der Builder-Modus des Helm-Charts, im Cluster von kubectl.\nEr verbindet sich zur App: von außen erreicht ihn nichts.", - "install.modeNative_builder": "Direkt auf diesem Server (ein Builder braucht Container)", - "native.cannot_builder": "Ein Builder kann nicht direkt auf diesem Server laufen.\nSein BuildKit läuft in einem Container.\nNutzen Sie Docker, Podman oder Kubernetes.", + "native.cannot_builder": "Ein Builder direkt auf diesem Server braucht root.\nSein BuildKit läuft als root-Dienst.\nStarten Sie den Installer mit sudo.\nSonst nutzen Sie Docker, Podman oder Kubernetes.", + "install.modeNativeBuilderHint": "Der Builder und BuildKit werden auf diesem Server installiert.\nBeide laufen als systemd-Dienste, BuildKit als root.\nFür Server, auf denen keine Container erlaubt sind.", + "install.dirHelpNativeBuilder": "Hier liegen der Builder, BuildKit und ihre Einstellungen.\nEbenso die Dateien seiner Builds und der Cache von BuildKit.", + "native.builder": "Builder {version} wird heruntergeladen", + "native.buildkit": "BuildKit {version} wird installiert", + "native.noBuilder": "Für den Builder {version} gibt es kein Programm für diesen Server.\nDirekt installiert braucht er ein Release mit Programmen.", "builder.nameHelp": "Sein Container und sein Compose-Projekt heißen so.\nEs ist auch sein Name unter Verbindungen > Builder.", "builder.needApp": "Ein Builder braucht ein AnsibleForms, mit dem er sich verbindet.\nNutzen Sie --app-url, und --join für die sofortige Freigabe.", "builder.appUrlHelp": "Die Adresse des AnsibleForms, für das dieser Builder baut.\nDieselbe Adresse, die man im Browser öffnet.", diff --git a/internal/i18n/locales/en.json b/internal/i18n/locales/en.json index 02b32c4..7cc648c 100644 --- a/internal/i18n/locales/en.json +++ b/internal/i18n/locales/en.json @@ -412,8 +412,12 @@ "install.roleBuilderHint": "It builds the RTE images designed in an AnsibleForms elsewhere.\nIt pushes them to their registry, with BuildKit inside it.\nIt talks to AnsibleForms over a single WebSocket.", "install.roleBuilderShort": "Builder", "install.modeKubernetesBuilderHint": "The Helm chart's builder mode, on the cluster kubectl reaches.\nIt dials the app: nothing reaches it from outside.", - "install.modeNative_builder": "Directly on this server (a Builder needs containers)", - "native.cannot_builder": "A Builder cannot be installed directly on this server.\nIts BuildKit runs in a container.\nUse Docker, Podman or Kubernetes.", + "native.cannot_builder": "A Builder installed directly on this server needs root.\nIts BuildKit runs as a root service.\nRun the installer with sudo, or use Docker, Podman or Kubernetes.", + "install.modeNativeBuilderHint": "The Builder and BuildKit are installed on this server.\nBoth run as systemd services, BuildKit as root.\nFor servers where containers are not allowed.", + "install.dirHelpNativeBuilder": "The Builder, BuildKit and their settings go here.\nSo do its builds' files and BuildKit's cache.", + "native.builder": "Downloading the Builder {version}", + "native.buildkit": "Installing BuildKit {version}", + "native.noBuilder": "The Builder {version} has no binary for this server.\nInstalling it directly needs a Builder release with binaries.", "builder.nameHelp": "Its container and its compose project are named after it.\nIt is also its name under Connections > Builders.", "builder.needApp": "A Builder needs an AnsibleForms to connect to.\nUse --app-url, and --join to be approved at once.", "builder.appUrlHelp": "The address of the AnsibleForms this Builder builds for.\nThe same address people open in a browser.", diff --git a/internal/i18n/locales/es.json b/internal/i18n/locales/es.json index e8369e5..ee6e080 100644 --- a/internal/i18n/locales/es.json +++ b/internal/i18n/locales/es.json @@ -412,8 +412,12 @@ "install.roleBuilderHint": "Construye las imágenes RTE definidas en un AnsibleForms remoto.\nLas sube a su registro, con BuildKit dentro de él.\nHabla con AnsibleForms por un único WebSocket.", "install.roleBuilderShort": "Builder", "install.modeKubernetesBuilderHint": "El modo builder del chart de Helm, en el clúster de kubectl.\nSe conecta a la aplicación: nada le llega desde fuera.", - "install.modeNative_builder": "Directamente en este servidor (un Builder necesita contenedores)", - "native.cannot_builder": "Un Builder no se instala directamente en este servidor.\nSu BuildKit corre en un contenedor.\nUsa Docker, Podman o Kubernetes.", + "native.cannot_builder": "Un Builder instalado directamente en este servidor necesita root.\nSu BuildKit corre como servicio de root.\nEjecuta el instalador con sudo, o usa Docker, Podman o Kubernetes.", + "install.modeNativeBuilderHint": "El Builder y BuildKit se instalan en este servidor.\nAmbos corren como servicios systemd, BuildKit como root.\nPara servidores donde no se permiten contenedores.", + "install.dirHelpNativeBuilder": "Aquí van el Builder, BuildKit y sus ajustes.\nTambién los archivos de sus builds y la caché de BuildKit.", + "native.builder": "Descargando el Builder {version}", + "native.buildkit": "Instalando BuildKit {version}", + "native.noBuilder": "El Builder {version} no tiene binario para este servidor.\nInstalarlo directamente necesita una versión con binarios.", "builder.nameHelp": "Su contenedor y su proyecto compose llevan este nombre.\nTambién es su nombre en Conexiones > Builders.", "builder.needApp": "Un Builder necesita un AnsibleForms al que conectarse.\nUsa --app-url, y --join para quedar aprobado al momento.", "builder.appUrlHelp": "La dirección del AnsibleForms para el que construye este Builder.\nLa misma dirección que se abre en un navegador.", diff --git a/internal/i18n/locales/fr.json b/internal/i18n/locales/fr.json index d5babc7..870cd87 100644 --- a/internal/i18n/locales/fr.json +++ b/internal/i18n/locales/fr.json @@ -412,8 +412,12 @@ "install.roleBuilderHint": "Il construit les images RTE d'un AnsibleForms situé ailleurs.\nIl les pousse vers leur registre, avec BuildKit en lui.\nIl parle à AnsibleForms par un seul WebSocket.", "install.roleBuilderShort": "Builder", "install.modeKubernetesBuilderHint": "Le mode builder du chart Helm, sur le cluster de kubectl.\nIl se connecte à l'application : rien ne l'atteint de l'extérieur.", - "install.modeNative_builder": "Directement sur ce serveur (un Builder a besoin de conteneurs)", - "native.cannot_builder": "Un Builder ne s'installe pas directement sur ce serveur.\nSon BuildKit tourne en conteneur.\nUtilisez Docker, Podman ou Kubernetes.", + "native.cannot_builder": "Un Builder installé directement sur ce serveur demande root.\nSon BuildKit tourne comme service root.\nLancez l'installeur avec sudo.\nSinon, utilisez Docker, Podman ou Kubernetes.", + "install.modeNativeBuilderHint": "Le Builder et BuildKit sont installés sur ce serveur.\nTous deux tournent comme services systemd, BuildKit en root.\nPour les serveurs où les conteneurs ne sont pas permis.", + "install.dirHelpNativeBuilder": "Le Builder, BuildKit et leurs réglages vont ici.\nDe même que les fichiers de ses builds et le cache de BuildKit.", + "native.builder": "Téléchargement du Builder {version}", + "native.buildkit": "Installation de BuildKit {version}", + "native.noBuilder": "Le Builder {version} n'a pas de binaire pour ce serveur.\nL'installer directement demande une version avec binaires.", "builder.nameHelp": "Son conteneur et son projet compose portent ce nom.\nC'est aussi son nom dans Connexions > Builders.", "builder.needApp": "Un Builder a besoin d'un AnsibleForms auquel se connecter.\nUtilisez --app-url, et --join pour être approuvé tout de suite.", "builder.appUrlHelp": "L'adresse de l'AnsibleForms pour lequel ce Builder construit.\nLa même adresse que celle ouverte dans un navigateur.", diff --git a/internal/i18n/locales/it.json b/internal/i18n/locales/it.json index dece3e0..e9b219f 100644 --- a/internal/i18n/locales/it.json +++ b/internal/i18n/locales/it.json @@ -412,8 +412,12 @@ "install.roleBuilderHint": "Costruisce le immagini RTE definite in un AnsibleForms altrove.\nLe invia al loro registry, con BuildKit al suo interno.\nParla con AnsibleForms su un unico WebSocket.", "install.roleBuilderShort": "Builder", "install.modeKubernetesBuilderHint": "La modalità builder del chart Helm, sul cluster di kubectl.\nSi connette all'app: nulla lo raggiunge dall'esterno.", - "install.modeNative_builder": "Direttamente su questo server (un Builder richiede container)", - "native.cannot_builder": "Un Builder non si installa direttamente su questo server.\nIl suo BuildKit gira in un container.\nUsa Docker, Podman o Kubernetes.", + "native.cannot_builder": "Un Builder installato direttamente su questo server richiede root.\nIl suo BuildKit gira come servizio root.\nAvvia l'installer con sudo, o usa Docker, Podman o Kubernetes.", + "install.modeNativeBuilderHint": "Il Builder e BuildKit vengono installati su questo server.\nEntrambi girano come servizi systemd, BuildKit come root.\nPer i server in cui i container non sono ammessi.", + "install.dirHelpNativeBuilder": "Qui vanno il Builder, BuildKit e le loro impostazioni.\nCosì come i file delle sue build e la cache di BuildKit.", + "native.builder": "Download del Builder {version}", + "native.buildkit": "Installazione di BuildKit {version}", + "native.noBuilder": "Il Builder {version} non ha un binario per questo server.\nInstallarlo direttamente richiede una release con binari.", "builder.nameHelp": "Il suo container e il suo progetto compose hanno questo nome.\nÈ anche il suo nome in Connessioni > Builder.", "builder.needApp": "Un Builder ha bisogno di un AnsibleForms a cui connettersi.\nUsa --app-url, e --join per essere approvato subito.", "builder.appUrlHelp": "L'indirizzo dell'AnsibleForms per cui costruisce questo Builder.\nLo stesso indirizzo che si apre in un browser.", diff --git a/internal/i18n/locales/ja.json b/internal/i18n/locales/ja.json index 5424c3c..c537238 100644 --- a/internal/i18n/locales/ja.json +++ b/internal/i18n/locales/ja.json @@ -412,8 +412,12 @@ "install.roleBuilderHint": "別の場所の AnsibleForms で定義された RTE イメージをビルドします。\n内部の BuildKit でビルドし、レジストリにプッシュします。\nAnsibleForms とは 1 本の WebSocket で通信します。", "install.roleBuilderShort": "ビルダー", "install.modeKubernetesBuilderHint": "Helm チャートのビルダーモード。kubectl の接続先クラスターに。\nアプリへ接続します: 外部からは何も届きません。", - "install.modeNative_builder": "このサーバーに直接 (ビルダーにはコンテナーが必要)", - "native.cannot_builder": "ビルダーはこのサーバーに直接インストールできません。\nBuildKit はコンテナーで動きます。\nDocker、Podman、Kubernetes を使ってください。", + "native.cannot_builder": "このサーバーに直接入れるビルダーには root が必要です。\nその BuildKit は root のサービスとして動きます。\nsudo でインストーラーを実行してください。\nまたは Docker、Podman、Kubernetes を使ってください。", + "install.modeNativeBuilderHint": "ビルダーと BuildKit をこのサーバーに導入します。\nどちらも systemd サービスとして動き、BuildKit は root です。\nコンテナーが許可されないサーバー向けです。", + "install.dirHelpNativeBuilder": "ビルダー、BuildKit、その設定を保存します。\nビルドのファイルと BuildKit のキャッシュもここです。", + "native.builder": "ビルダー {version} をダウンロードしています", + "native.buildkit": "BuildKit {version} をインストールしています", + "native.noBuilder": "ビルダー {version} にはこのサーバー用のバイナリーがありません。\n直接のインストールには、バイナリーを公開するビルダーのリリースが必要です。", "builder.nameHelp": "コンテナーと compose プロジェクトにこの名前が付きます。\n接続 > ビルダー での名前でもあります。", "builder.needApp": "ビルダーには接続先の AnsibleForms が必要です。\n--app-url を指定し、すぐ承認するには --join も指定します。", "builder.appUrlHelp": "このビルダーがビルドする AnsibleForms のアドレス。\nブラウザーで開くのと同じアドレスです。", diff --git a/internal/i18n/locales/nl.json b/internal/i18n/locales/nl.json index 1b02131..5a8187b 100644 --- a/internal/i18n/locales/nl.json +++ b/internal/i18n/locales/nl.json @@ -412,8 +412,12 @@ "install.roleBuilderHint": "Hij bouwt de RTE-images die een AnsibleForms elders definieert.\nHij pusht ze naar hun registry, met BuildKit erin.\nHij praat met AnsibleForms over één WebSocket.", "install.roleBuilderShort": "Builder", "install.modeKubernetesBuilderHint": "De builder-modus van de Helm-chart, op het cluster van kubectl.\nHij verbindt met de app: niets bereikt hem van buiten.", - "install.modeNative_builder": "Direct op deze server (een Builder heeft containers nodig)", - "native.cannot_builder": "Een Builder kan niet direct op deze server worden geïnstalleerd.\nZijn BuildKit draait in een container.\nGebruik Docker, Podman of Kubernetes.", + "native.cannot_builder": "Een Builder direct op deze server heeft root nodig.\nZijn BuildKit draait als root-dienst.\nStart de installer met sudo.\nGebruik anders Docker, Podman of Kubernetes.", + "install.modeNativeBuilderHint": "De Builder en BuildKit worden op deze server geïnstalleerd.\nBeide draaien als systemd-diensten, BuildKit als root.\nVoor servers waar containers niet zijn toegestaan.", + "install.dirHelpNativeBuilder": "De Builder, BuildKit en hun instellingen komen hier.\nNet als de bestanden van zijn builds en de cache van BuildKit.", + "native.builder": "De Builder {version} downloaden", + "native.buildkit": "BuildKit {version} installeren", + "native.noBuilder": "De Builder {version} heeft geen programma voor deze server.\nDirect installeren vraagt een Builder-release die ze publiceert.", "builder.nameHelp": "Zijn container en zijn compose-project heten zo.\nHet is ook zijn naam onder Verbindingen > Builders.", "builder.needApp": "Een Builder heeft een AnsibleForms nodig om mee te verbinden.\nGebruik --app-url, en --join om meteen goedgekeurd te zijn.", "builder.appUrlHelp": "Het adres van de AnsibleForms waarvoor deze Builder bouwt.\nHetzelfde adres dat men in een browser opent.", diff --git a/internal/i18n/locales/pl.json b/internal/i18n/locales/pl.json index b194258..1bd87d0 100644 --- a/internal/i18n/locales/pl.json +++ b/internal/i18n/locales/pl.json @@ -412,8 +412,12 @@ "install.roleBuilderHint": "Buduje obrazy RTE zdefiniowane w AnsibleForms gdzie indziej.\nWypycha je do ich rejestru, z BuildKit w środku.\nŁączy się z AnsibleForms przez jeden WebSocket.", "install.roleBuilderShort": "Builder", "install.modeKubernetesBuilderHint": "Tryb buildera chartu Helm, w klastrze, do którego sięga kubectl.\nŁączy się z aplikacją: nic nie dociera do niego z zewnątrz.", - "install.modeNative_builder": "Bezpośrednio na tym serwerze (Builder wymaga kontenerów)", - "native.cannot_builder": "Buildera nie można zainstalować bezpośrednio na tym serwerze.\nJego BuildKit działa w kontenerze.\nUżyj Docker, Podman lub Kubernetes.", + "native.cannot_builder": "Builder zainstalowany bezpośrednio na tym serwerze wymaga roota.\nJego BuildKit działa jako usługa roota.\nUruchom instalator przez sudo.\nAlbo użyj Dockera, Podmana lub Kubernetesa.", + "install.modeNativeBuilderHint": "Builder i BuildKit są instalowane na tym serwerze.\nOba działają jako usługi systemd, BuildKit jako root.\nDla serwerów, na których kontenery są niedozwolone.", + "install.dirHelpNativeBuilder": "Tu trafiają Builder, BuildKit i ich ustawienia.\nA także pliki jego buildów i pamięć podręczna BuildKit.", + "native.builder": "Pobieranie Buildera {version}", + "native.buildkit": "Instalowanie BuildKit {version}", + "native.noBuilder": "Builder {version} nie ma programu dla tego serwera.\nInstalacja bezpośrednia wymaga wydania z programami.", "builder.nameHelp": "Jego kontener i projekt compose mają tę nazwę.\nTo także jego nazwa w Połączenia > Buildery.", "builder.needApp": "Builder potrzebuje AnsibleForms, z którym się połączy.\nUżyj --app-url, oraz --join, by od razu był zatwierdzony.", "builder.appUrlHelp": "Adres AnsibleForms, dla którego buduje ten Builder.\nTen sam adres, który otwiera się w przeglądarce.", diff --git a/internal/i18n/locales/pt.json b/internal/i18n/locales/pt.json index 2b845af..6996ad4 100644 --- a/internal/i18n/locales/pt.json +++ b/internal/i18n/locales/pt.json @@ -412,8 +412,12 @@ "install.roleBuilderHint": "Constrói as imagens RTE definidas num AnsibleForms noutro local.\nEnvia-as para o seu registo, com BuildKit dentro dele.\nComunica com o AnsibleForms por um único WebSocket.", "install.roleBuilderShort": "Builder", "install.modeKubernetesBuilderHint": "O modo builder do chart Helm, no cluster do kubectl.\nLiga-se à aplicação: nada o alcança de fora.", - "install.modeNative_builder": "Diretamente neste servidor (um Builder precisa de contentores)", - "native.cannot_builder": "Um Builder não se instala diretamente neste servidor.\nO seu BuildKit corre num contentor.\nUse Docker, Podman ou Kubernetes.", + "native.cannot_builder": "Um Builder instalado diretamente neste servidor precisa de root.\nO seu BuildKit corre como serviço root.\nExecute o instalador com sudo.\nSenão, use Docker, Podman ou Kubernetes.", + "install.modeNativeBuilderHint": "O Builder e o BuildKit são instalados neste servidor.\nAmbos correm como serviços systemd, o BuildKit como root.\nPara servidores onde os contentores não são permitidos.", + "install.dirHelpNativeBuilder": "Aqui ficam o Builder, o BuildKit e as suas definições.\nTambém os ficheiros das suas builds e a cache do BuildKit.", + "native.builder": "A transferir o Builder {version}", + "native.buildkit": "A instalar o BuildKit {version}", + "native.noBuilder": "O Builder {version} não tem binário para este servidor.\nInstalá-lo diretamente precisa de uma versão com binários.", "builder.nameHelp": "O seu contentor e o seu projeto compose têm este nome.\nÉ também o seu nome em Ligações > Builders.", "builder.needApp": "Um Builder precisa de um AnsibleForms a que se ligar.\nUse --app-url, e --join para ser aprovado de imediato.", "builder.appUrlHelp": "O endereço do AnsibleForms para o qual este Builder constrói.\nO mesmo endereço que se abre num navegador.", diff --git a/internal/i18n/locales/zh.json b/internal/i18n/locales/zh.json index 61673f9..28ace47 100644 --- a/internal/i18n/locales/zh.json +++ b/internal/i18n/locales/zh.json @@ -412,8 +412,12 @@ "install.roleBuilderHint": "它构建其他位置的 AnsibleForms 中定义的 RTE 镜像。\n它用内部的 BuildKit 构建,并推送到镜像仓库。\n它通过单个 WebSocket 与 AnsibleForms 通信。", "install.roleBuilderShort": "构建器", "install.modeKubernetesBuilderHint": "Helm chart 的构建器模式,部署到 kubectl 连接的集群。\n它连接应用:外部无法访问它。", - "install.modeNative_builder": "直接安装在此服务器上(构建器需要容器)", - "native.cannot_builder": "构建器不能直接安装在此服务器上。\n它的 BuildKit 在容器中运行。\n请使用 Docker、Podman 或 Kubernetes。", + "native.cannot_builder": "直接安装在此服务器上的构建器需要 root。\n它的 BuildKit 作为 root 服务运行。\n请用 sudo 运行安装程序。\n或者使用 Docker、Podman 或 Kubernetes。", + "install.modeNativeBuilderHint": "构建器和 BuildKit 安装在此服务器上。\n两者都作为 systemd 服务运行,BuildKit 以 root 运行。\n适用于不允许容器的服务器。", + "install.dirHelpNativeBuilder": "构建器、BuildKit 及其设置放在这里。\n它的构建文件和 BuildKit 的缓存也在这里。", + "native.builder": "正在下载构建器 {version}", + "native.buildkit": "正在安装 BuildKit {version}", + "native.noBuilder": "构建器 {version} 没有适用于此服务器的二进制文件。\n直接安装需要发布这些文件的构建器版本。", "builder.nameHelp": "它的容器和 compose 项目以此命名。\n这也是它在 连接 > 构建器 中的名称。", "builder.needApp": "构建器需要一个要连接的 AnsibleForms。\n请使用 --app-url,并用 --join 立即获得批准。", "builder.appUrlHelp": "此构建器为其构建的 AnsibleForms 的地址。\n与在浏览器中打开的地址相同。", diff --git a/internal/native/builder.go b/internal/native/builder.go new file mode 100644 index 0000000..8e02585 --- /dev/null +++ b/internal/native/builder.go @@ -0,0 +1,523 @@ +package native + +// ─── the RTE builder ────────────────────────────────────────────────────────── +// +// A Builder installed directly on the server: the builder's static binary from its GitHub +// release, BuildKit from moby/buildkit's, and two systemd services. BuildKit runs as root (a +// rootful buildkitd, its OCI worker), and serves its socket to the builder's group only ; the +// builder runs as its system user and builds through that socket (BUILDKIT_HOST), starting no +// buildkitd of its own. +// +// The layout of its installation folder (/opt/ansibleforms-builder): +// +// releases// the builder's binary, and a link to the BuildKit it runs with +// current the link to the release that runs (an upgrade moves it, a rollback too) +// runtime/buildkit-/ BuildKit's binaries: buildkitd, buildkit-runc, its QEMU emulators +// data/ the builder's work (BUILDER_WORK_PATH): its spool, its builds' files +// buildkit/ buildkitd's state and cache, root's +// home/ the system user's home +// builder.env the builder's settings and its token + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "io" + "os" + "path/filepath" + "strings" + "time" + + "github.com/ansibleforms/installer/internal/compose" + "github.com/ansibleforms/installer/internal/i18n" + "github.com/ansibleforms/installer/internal/state" + "github.com/ansibleforms/installer/internal/system" + "github.com/ansibleforms/installer/internal/ui" +) + +// BuilderRepo is the builder's GitHub repository, whose releases carry its static binaries +// (ansibleforms-rte-builder_linux_) and their SHA256SUMS. +const BuilderRepo = "ansibleforms/builder" + +// BuildkitVersion is the BuildKit release a native Builder runs, from moby/buildkit's GitHub +// releases. Dependabot does not see a version in Go code: it is bumped by hand, with the +// SHA-256 of both archives in buildkitSums, and best together with the moby/buildkit image the +// builder's own Dockerfile pins. The sums are GitHub's digests of the release's assets: +// +// gh api repos/moby/buildkit/releases/tags/ \ +// --jq '.assets[] | select(.name | test("linux-(amd|arm)64.tar.gz$")) | "\(.digest) \(.name)"' +// +// An upgrade moves an installation's BuildKit to the one this installer pins. +const BuildkitVersion = "v0.35.1" + +// buildkitSums are the SHA-256 of BuildKit's archive for each architecture, at BuildkitVersion +// (moby/buildkit publishes no checksum files: these are pinned here, the archive checked +// against them) ; the tests pin their own. +var buildkitSums = map[string]string{ + "amd64": "b248c2b91698aafef11818fe8b681dc5e341581f7d5676709ff45ca1f29b0408", + "arm64": "46c7d1799250bd8b31266ed718715ab9d3464bad0455d5bfbe48e2eeb92ca965", +} + +// buildkitUnit is the systemd service of BuildKit: one per server, as its socket is. +const buildkitUnit = "ansibleforms-buildkitd" + +// buildkitSocket is where BuildKit listens, for the builder's group only. +const buildkitSocket = "/run/buildkit/buildkitd.sock" + +// builderBinary is the builder's program in a release's folder. +const builderBinary = "ansibleforms-rte-builder" + +// builderPackages are what a Builder needs of the distribution: the certificates it checks +// the controller's and the registries' with. +var builderPackages = system.Packages{ + Apt: []string{"ca-certificates"}, + Dnf: []string{"ca-certificates"}, + Zypper: []string{"ca-certificates"}, +} + +// buildkitState is buildkitd's own folder: its state and its cache, root's. +func (l layout) buildkitState() string { return filepath.Join(l.dir, "buildkit") } + +// ─── install ────────────────────────────────────────────────────────────────── + +// installBuilder installs a Builder: the packages, the system user, the release (the +// builder's binary and BuildKit), its settings and both services, then waits for its probes. +// +// Args: +// +// ctx: the context, to cancel. +// l: the installation. +// o: the answers (o.Runner holds the controller, the join token and the token ; o.Port the +// port of its probes, a free one when 0). +// +// Returns: +// +// The installation's state (saved) and its token, whose fingerprint the end shows. +// +// Errors: +// +// When a step fails; what was made is left for a look. +func installBuilder(ctx context.Context, l layout, o compose.Options) (*state.State, *compose.Result, error) { + // step 1 : the packages and the system user, whose group reaches BuildKit's socket + ui.Step(i18n.T("native.prereqs")) + if err := system.InstallPackages(ctx, builderPackages); err != nil { + return nil, nil, err + } + ui.Step(i18n.T("native.user", "user", o.Name)) + if err := os.MkdirAll(o.Dir, 0o755); err != nil { + return nil, nil, err + } + if err := ensureUser(ctx, l); err != nil { + return nil, nil, err + } + + // step 2 : the release, then its settings + if err := prepareBuilder(ctx, l, o.Version); err != nil { + return nil, nil, err + } + if err := switchTo(l, o.Version); err != nil { + return nil, nil, err + } + port := o.Port + if port == 0 { + port = compose.FreePort("127.0.0.1", 8000) + } + res, err := writeBuilderEnv(l, o, port) + if err != nil { + return nil, nil, err + } + if err := own(ctx, l); err != nil { + return nil, nil, err + } + + // step 3 : BuildKit's service and the builder's, BuildKit started first + ui.Step(i18n.T("native.services")) + if err := writeBuilderUnits(l); err != nil { + return nil, nil, err + } + if err := system.Run(ctx, "", "systemctl", "daemon-reload"); err != nil { + return nil, nil, err + } + for _, s := range services(compose.RoleBuilder) { + if err := system.Run(ctx, "", "systemctl", "enable", "--now", l.unit(s)); err != nil { + return nil, nil, err + } + } + st := &state.State{ + Mode: state.Native, Role: compose.RoleBuilder, Version: o.Version, Dir: o.Dir, Name: o.Name, Port: port, + InstalledAt: time.Now().UTC(), UpdatedAt: time.Now().UTC(), + } + if err := st.Save(); err != nil { + return nil, nil, err + } + ui.Step(i18n.T("compose.waitingBuilder")) + if err := waitPort(ctx, l.unit("builder"), port, 3*time.Minute); err != nil { + return st, res, err + } + return st, res, nil +} + +// writeBuilderEnv writes a Builder's settings: the controller's address, its name and a token +// of its own (the join token too, when one was given), its work folder and this server's +// BuildKit ; and makes its work folder and BuildKit's. +// +// Args: +// +// l: the installation. +// o: the answers. +// port: the port of its probes, on this machine only. +// +// Returns: +// +// Its token. +// +// Errors: +// +// When a folder or the file cannot be made. +func writeBuilderEnv(l layout, o compose.Options, port int) (*compose.Result, error) { + r := o.Runner + token := r.Token + if token == "" { + token = compose.Secret(32) + } + name := r.RteName + if name == "" { + name = o.Name + } + lines := []string{ + "# the controller it dials : its address as people open it", + "CONTROLLER_URL=" + r.AppURL, + "# its name under Connections > Builders", + "RTE_NAME=" + name, + "# its own token : the controller keeps it for it once it joins", + "RTE_TOKEN=" + token, + } + if r.JoinToken != "" { + lines = append(lines, "# the join token that approves it at once, presented once", "RTE_JOIN_TOKEN="+r.JoinToken) + } + if r.TrustAppCert { + lines = append(lines, "# the controller's certificate is self-signed : accepted as it is", "CONTROLLER_TLS_VERIFY=0") + } + lines = append(lines, + "# its spool and its builds' files", + "BUILDER_WORK_PATH="+l.data(), + "# the BuildKit of this server (the "+buildkitUnit+" service) : it starts none of its own", + "BUILDKIT_HOST=unix://"+buildkitSocket, + "# its probes answer on this machine only", + fmt.Sprintf("PORT=%d", port), + "LISTEN_HOST=127.0.0.1", + "HOME="+l.home(), + ) + if err := os.MkdirAll(l.data(), 0o750); err != nil { + return nil, err + } + if err := os.MkdirAll(l.buildkitState(), 0o700); err != nil { + return nil, err + } + if err := writeEnv(l, "builder", "AnsibleForms RTE builder, written by the AnsibleForms installer", lines); err != nil { + return nil, err + } + return &compose.Result{Token: token}, nil +} + +// ─── the release ────────────────────────────────────────────────────────────── + +// builderAsset is the name of the builder's binary for this server's architecture. +func builderAsset() string { + return "ansibleforms-rte-builder_linux_" + system.Arch() +} + +// builderBase is where a builder release's files are published. +func builderBase(version string) string { + return fmt.Sprintf("%s/%s/releases/download/%s", githubBase, BuilderRepo, version) +} + +// buildkitURL is BuildKit's archive for this server's architecture, at BuildkitVersion. +func buildkitURL() string { + return fmt.Sprintf("%s/moby/buildkit/releases/download/%s/buildkit-%s.linux-%s.tar.gz", githubBase, BuildkitVersion, BuildkitVersion, system.Arch()) +} + +// prepareBuilder puts a Builder's release in place, next to the one that runs: the builder's +// binary, its checksum checked against the release's SHA256SUMS, and a link to the BuildKit +// this installer pins. A release that is already there (a retried upgrade) is used as it is. +// +// Args: +// +// ctx: the context, to cancel. +// l: the installation. +// version: the builder's version (AnsibleForms'). +// +// Errors: +// +// When a download, a checksum or a file fails ; a release without binaries is said so. +func prepareBuilder(ctx context.Context, l layout, version string) error { + dir := l.release(version) + if _, err := os.Stat(filepath.Join(dir, ".complete")); err == nil { + return nil + } + _ = os.RemoveAll(dir) + if err := os.MkdirAll(dir, 0o755); err != nil { + return err + } + ui.Step(i18n.T("native.builder", "version", version)) + if err := fetchBinary(ctx, builderBase(version), builderAsset(), filepath.Join(dir, builderBinary)); err != nil { + if errors.Is(err, errNotFound) { + return errors.New(i18n.T("native.noBuilder", "version", version)) + } + return err + } + bk, err := installBuildkit(ctx, l) + if err != nil { + return err + } + if err := os.Symlink(bk, filepath.Join(dir, "buildkit")); err != nil { + return err + } + return os.WriteFile(filepath.Join(dir, ".complete"), []byte(version+"\n"), 0o644) +} + +// installBuildkit installs BuildKit at BuildkitVersion into the runtimes, its archive checked +// against the SHA-256 pinned for this architecture ; one already there is used as it is. +// +// Args: +// +// ctx: the context, to cancel. +// l: the installation. +// +// Returns: +// +// Its folder (buildkitd, buildkit-runc and the rest of the archive's bin/). +// +// Errors: +// +// When no sum is pinned for the architecture, or the download or the checksum fails. +func installBuildkit(ctx context.Context, l layout) (string, error) { + dir := filepath.Join(l.runtime(), "buildkit-"+BuildkitVersion) + if _, err := os.Stat(filepath.Join(dir, "buildkitd")); err == nil { + return dir, nil + } + sum := buildkitSums[system.Arch()] + if sum == "" { + return "", fmt.Errorf("no BuildKit checksum for %s", system.Arch()) + } + ui.Step(i18n.T("native.buildkit", "version", strings.TrimPrefix(BuildkitVersion, "v"))) + tmp := dir + ".tmp" + _ = os.RemoveAll(tmp) + if err := os.MkdirAll(tmp, 0o755); err != nil { + return "", err + } + // the archive holds bin/ alone : its programs go straight into the folder + if err := fetchSum(ctx, buildkitURL(), sum, tmp, 1); err != nil { + return "", err + } + return dir, os.Rename(tmp, dir) +} + +// fetchBinary downloads a program whose SHA-256 a SHA256SUMS file next to it lists, checks it +// and puts it in place, executable. +// +// Args: +// +// ctx: the context, to cancel. +// base: the folder both are published in. +// name: the program's name there. +// dest: where it goes. +// +// Errors: +// +// errNotFound when the release has no SHA256SUMS ; else when it lists no such program, the +// download fails, the checksum differs or the file cannot be written. +func fetchBinary(ctx context.Context, base, name, dest string) error { + sums, err := getText(ctx, base+"/SHA256SUMS") + if err != nil { + return err + } + sum := "" + for _, line := range strings.Split(sums, "\n") { + // " ", or " *" from a binary-mode sha256sum + if f := strings.Fields(line); len(f) == 2 && strings.TrimPrefix(f[1], "*") == name { + sum = f[0] + } + } + if sum == "" { + return fmt.Errorf("%s/SHA256SUMS lists no %s", base, name) + } + body, err := get(ctx, base+"/"+name) + if err != nil { + return err + } + defer body.Close() + tmp := dest + ".tmp" + f, err := os.OpenFile(tmp, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o755) + if err != nil { + return err + } + defer os.Remove(tmp) + h := sha256.New() + _, err = io.Copy(io.MultiWriter(f, h), body) + // the copy's error first, else the close's (a write the disk refused late) + if cerr := f.Close(); err == nil { + err = cerr + } + if err != nil { + return fmt.Errorf("downloading %s/%s: %w", base, name, err) + } + if got := hex.EncodeToString(h.Sum(nil)); !strings.EqualFold(got, sum) { + return fmt.Errorf("the checksum of %s/%s is %s, not %s", base, name, got, sum) + } + return os.Rename(tmp, dest) +} + +// pruneBuildkit deletes the BuildKits no release left links to (after prune). +// +// Args: +// +// l: the installation. +func pruneBuildkit(l layout) { + used := map[string]bool{} + releases, _ := os.ReadDir(l.releases()) + for _, r := range releases { + if target, err := os.Readlink(filepath.Join(l.releases(), r.Name(), "buildkit")); err == nil { + used[filepath.Base(target)] = true + } + } + runtimes, _ := os.ReadDir(l.runtime()) + for _, e := range runtimes { + if strings.HasPrefix(e.Name(), "buildkit-") && !used[e.Name()] { + _ = os.RemoveAll(filepath.Join(l.runtime(), e.Name())) + } + } +} + +// ─── the services ───────────────────────────────────────────────────────────── + +// builderUnitTemplate is the builder's systemd unit: its system user, its settings, its +// binary of the current release ; BuildKit's service is required and started before it. +const builderUnitTemplate = `# AnsibleForms RTE builder ({{NAME}}), written by the AnsibleForms installer +[Unit] +Description=AnsibleForms RTE builder ({{NAME}}) +After=network-online.target {{BUILDKIT}}.service +Wants=network-online.target +Requires={{BUILDKIT}}.service + +[Service] +Type=simple +User={{NAME}} +Group={{NAME}} +WorkingDirectory={{DIR}} +EnvironmentFile={{DIR}}/builder.env +ExecStart={{DIR}}/current/` + builderBinary + ` +Restart=on-failure +RestartSec=5 +PrivateTmp=true +ProtectSystem=full +NoNewPrivileges=true + +[Install] +WantedBy=multi-user.target +` + +// buildkitUnitTemplate is BuildKit's systemd unit: buildkitd of the current release, as root, +// its OCI worker running the builds with the archive's runc (buildkit-runc, found on its PATH +// with the QEMU emulators that build for the other architecture), its socket owned by the +// builder's group, its state in the installation's folder. It tells systemd once it listens +// (Type=notify), so the builder starts on a socket that answers ; Delegate lets it make the +// builds' cgroups. +const buildkitUnitTemplate = `# BuildKit of the AnsibleForms RTE builder ({{NAME}}), written by the AnsibleForms installer. +# It runs as root ; its socket is for the group {{NAME}} only, the builder's system user. +[Unit] +Description=BuildKit of the AnsibleForms RTE builder ({{NAME}}) +After=network-online.target +Wants=network-online.target + +[Service] +Type=notify +Environment=PATH={{DIR}}/current/buildkit:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin +ExecStart={{DIR}}/current/buildkit/buildkitd --addr unix://{{SOCKET}} --group {{NAME}} --root {{DIR}}/buildkit --oci-worker=true --containerd-worker=false +Restart=on-failure +RestartSec=5 +Delegate=yes +KillMode=mixed +LimitNOFILE=1048576 +TasksMax=infinity + +[Install] +WantedBy=multi-user.target +` + +// writeBuilderUnits writes BuildKit's unit and the builder's. +// +// Args: +// +// l: the installation. +// +// Errors: +// +// When a file cannot be written. +func writeBuilderUnits(l layout) error { + r := strings.NewReplacer("{{NAME}}", l.name, "{{DIR}}", l.dir, "{{BUILDKIT}}", buildkitUnit, "{{SOCKET}}", buildkitSocket) + for service, template := range map[string]string{"buildkitd": buildkitUnitTemplate, "builder": builderUnitTemplate} { + if err := os.WriteFile(l.unitPath(service), []byte(r.Replace(template)), 0o644); err != nil { + return err + } + } + return nil +} + +// ─── upgrade ────────────────────────────────────────────────────────────────── + +// upgradeBuilder moves a Builder to another version: its release put in place while the old +// one runs (the builder's binary of that version, BuildKit at this installer's version), its +// units written again, both services stopped, the current link moved, both started, and the +// builder's probes waited for. +// +// Args: +// +// ctx: the context, to cancel. +// st: the installation (saved with the new version once it answers). +// to: the version to upgrade to. +// +// Returns: +// +// What Rollback needs: the version before (a Builder has no database). +// +// Errors: +// +// When a step fails. +func upgradeBuilder(ctx context.Context, st *state.State, to string) (*Undo, error) { + l := layout{dir: st.Dir, name: st.Name} + undo := &Undo{Version: st.Version} + if err := prepareBuilder(ctx, l, to); err != nil { + return nil, err + } + if err := own(ctx, l); err != nil { + return nil, err + } + ui.Step(i18n.T("native.services")) + if err := writeBuilderUnits(l); err != nil { + return nil, err + } + if err := system.Run(ctx, "", "systemctl", "daemon-reload"); err != nil { + return nil, err + } + if err := systemctl(ctx, l, st.Role, "stop"); err != nil { + return undo, err + } + if err := switchTo(l, to); err != nil { + return undo, err + } + if err := systemctl(ctx, l, st.Role, "start"); err != nil { + return undo, err + } + ui.Step(i18n.T("compose.waitingBuilder")) + if err := waitPort(ctx, l.unit("builder"), envPort(l, "builder", st.Port), 3*time.Minute); err != nil { + return undo, err + } + prune(l, to, undo.Version) + pruneBuildkit(l) + st.Version = to + st.UpdatedAt = time.Now().UTC() + return undo, st.Save() +} diff --git a/internal/native/builder_test.go b/internal/native/builder_test.go new file mode 100644 index 0000000..fb35236 --- /dev/null +++ b/internal/native/builder_test.go @@ -0,0 +1,533 @@ +package native + +import ( + "archive/tar" + "context" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/ansibleforms/installer/internal/compose" + "github.com/ansibleforms/installer/internal/state" + "github.com/ansibleforms/installer/internal/system" +) + +// ─── a Builder's server, faked ──────────────────────────────────────────────── + +// builderServer is a fake server (newServer) whose GitHub serves the builder's releases 7.9.0 +// and 7.10.0 with their SHA256SUMS, and BuildKit's archive at BuildkitVersion with its sum +// pinned for the test ; files is what it serves, for a test to change. +type builderServer struct { + *fakeServer + files map[string][]byte +} + +// newBuilderServer sets a Builder's fake server up. +// +// Args: +// +// t: the test. +// +// Returns: +// +// The server ; its dir is where the Builder goes (not made yet). +func newBuilderServer(t *testing.T) *builderServer { + t.Helper() + s := &builderServer{fakeServer: newServer(t)} + binary := []byte("#!/bin/sh\necho builder\n") + bk := archive(t, + entry{name: "bin/", kind: tar.TypeDir, mode: 0o755}, + entry{name: "bin/buildkitd", kind: tar.TypeReg, body: "#!/bin/sh\n", mode: 0o755}, + entry{name: "bin/buildkit-runc", kind: tar.TypeReg, body: "#!/bin/sh\n", mode: 0o755}, + ) + s.files = map[string][]byte{ + "/moby/buildkit/releases/download/" + BuildkitVersion + "/buildkit-" + BuildkitVersion + ".linux-amd64.tar.gz": bk, + } + for _, v := range []string{"7.9.0", "7.10.0"} { + base := "/" + BuilderRepo + "/releases/download/" + v + "/" + s.files[base+"ansibleforms-rte-builder_linux_amd64"] = binary + // a binary-mode line for the other architecture, as sha256sum -b writes it + s.files[base+"SHA256SUMS"] = []byte(sum(binary) + " ansibleforms-rte-builder_linux_amd64\n" + sum(binary) + " *ansibleforms-rte-builder_linux_arm64\n") + } + githubBase = files(t, s.files) + was := buildkitSums + buildkitSums = map[string]string{"amd64": sum(bk)} + t.Cleanup(func() { buildkitSums = was }) + return s +} + +// options are a Builder's answers, its probes on a port that takes connections. +func (s *builderServer) options(t *testing.T) compose.Options { + return compose.Options{Role: compose.RoleBuilder, Dir: s.dir, Name: "bx", Version: "7.9.0", Port: listen(t), + Runner: compose.RunnerOptions{AppURL: "https://app"}} +} + +// installedBuilder installs a Builder on a fake server. +// +// Args: +// +// t: the test. +// +// Returns: +// +// The server and the installation's state. +func installedBuilder(t *testing.T) (*builderServer, *state.State) { + t.Helper() + s := newBuilderServer(t) + st, _, err := Install(context.Background(), s.options(t)) + if err != nil { + t.Fatal(err) + } + return s, st +} + +// ─── install ────────────────────────────────────────────────────────────────── + +// TestInstallBuilder checks a Builder installed: its packages, its user, its release with the +// builder's binary and BuildKit, its settings, BuildKit's unit and the builder's, both +// enabled, BuildKit first, and its state. +func TestInstallBuilder(t *testing.T) { + s := newBuilderServer(t) + o := s.options(t) + o.Runner.JoinToken, o.Runner.TrustAppCert, o.Runner.Token, o.Runner.RteName = "afj_x", true, "given-token-0123456789", "builder-7" + st, res, err := Install(context.Background(), o) + if err != nil { + t.Fatal(err) + } + if st.Mode != state.Native || st.Role != compose.RoleBuilder || st.Port != o.Port || res.Token != "given-token-0123456789" { + t.Errorf("state %+v, result %+v", st, res) + } + l := layout{dir: s.dir, name: "bx"} + for _, p := range []string{ + filepath.Join(l.release("7.9.0"), builderBinary), + filepath.Join(l.release("7.9.0"), "buildkit", "buildkitd"), + filepath.Join(l.release("7.9.0"), "buildkit", "buildkit-runc"), + filepath.Join(l.current(), builderBinary), + l.data(), l.buildkitState(), l.unitPath("builder"), l.unitPath("buildkitd"), + } { + if _, err := os.Stat(p); err != nil { + t.Errorf("%s: %v", p, err) + } + } + if info, _ := os.Stat(filepath.Join(l.release("7.9.0"), builderBinary)); info == nil || info.Mode().Perm()&0o111 == 0 { + t.Error("the builder is not executable") + } + env, _ := os.ReadFile(l.env("builder")) + for _, want := range []string{"CONTROLLER_URL=https://app", "RTE_NAME=builder-7", "RTE_TOKEN=given-token-0123456789", "RTE_JOIN_TOKEN=afj_x", + "CONTROLLER_TLS_VERIFY=0", "BUILDER_WORK_PATH=" + l.data(), "BUILDKIT_HOST=unix:///run/buildkit/buildkitd.sock", "LISTEN_HOST=127.0.0.1"} { + if !strings.Contains(string(env), want+"\n") { + t.Errorf("builder.env lacks %s:\n%s", want, env) + } + } + unit, _ := os.ReadFile(l.unitPath("builder")) + for _, want := range []string{"User=bx", "Requires=ansibleforms-buildkitd.service", "ExecStart=" + s.dir + "/current/ansibleforms-rte-builder", "EnvironmentFile=" + s.dir + "/builder.env"} { + if !strings.Contains(string(unit), want+"\n") { + t.Errorf("the builder's unit lacks %s", want) + } + } + bk, _ := os.ReadFile(l.unitPath("buildkitd")) + if !strings.Contains(string(bk), "buildkitd --addr unix:///run/buildkit/buildkitd.sock --group bx --root "+s.dir+"/buildkit") || + strings.Contains(string(bk), "User=") || filepath.Base(l.unitPath("buildkitd")) != "ansibleforms-buildkitd.service" { + t.Errorf("BuildKit's unit:\n%s", bk) + } + calls := strings.Join(s.bin.Calls(), "\n") + first, then := strings.Index(calls, "enable --now ansibleforms-buildkitd"), strings.Index(calls, "enable --now bx") + if first < 0 || then < first || !s.bin.Called("useradd --system") || !s.bin.Called("chown root:bx "+l.env("builder")) { + t.Errorf("calls %q", s.bin.Calls()) + } + if s.bin.Called("mariadb") { + t.Error("a Builder has no database") + } + if _, err := state.Load(); err != nil { + t.Errorf("state %v", err) + } +} + +// TestInstallBuilderDefaults checks a Builder without a token, a name or a port of its own: +// all three made for it, and a builder that never listens on its port. +func TestInstallBuilderDefaults(t *testing.T) { + s := newBuilderServer(t) + o := s.options(t) + o.Port = 0 + ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) + defer cancel() + st, res, err := Install(ctx, o) + if err == nil || st == nil || st.Port == 0 || len(res.Token) < 16 { + t.Fatalf("state %+v, result %+v, %v", st, res, err) + } + env, _ := os.ReadFile(layout{dir: s.dir}.env("builder")) + if !strings.Contains(string(env), "RTE_NAME=bx\n") || strings.Contains(string(env), "RTE_JOIN_TOKEN") || strings.Contains(string(env), "TLS_VERIFY") { + t.Errorf("builder.env %s", env) + } +} + +// TestInstallBuilderFails checks that each step of a Builder that fails stops the +// installation with its error. +func TestInstallBuilderFails(t *testing.T) { + cases := map[string]func(t *testing.T, s *builderServer, o *compose.Options){ + "unit exists": func(t *testing.T, s *builderServer, o *compose.Options) { + _ = os.WriteFile(layout{name: "bx"}.unitPath("buildkitd"), nil, 0o644) + }, + "packages": func(t *testing.T, s *builderServer, o *compose.Options) { t.Setenv("FAIL", "apt-get update") }, + "folder": func(t *testing.T, s *builderServer, o *compose.Options) { + parent := filepath.Dir(s.dir) + _ = os.Chmod(parent, 0o500) + t.Cleanup(func() { _ = os.Chmod(parent, 0o755) }) + }, + "user": func(t *testing.T, s *builderServer, o *compose.Options) { t.Setenv("FAIL", "useradd") }, + "no release": func(t *testing.T, s *builderServer, o *compose.Options) { o.Version = "9.9.9" }, + "switch": func(t *testing.T, s *builderServer, o *compose.Options) { + hook(t, "useradd", `/bin/mkdir -p "$DIR/current.new/full"`) + }, + "data": func(t *testing.T, s *builderServer, o *compose.Options) { + hook(t, "useradd", `/bin/touch "$DIR/data"`) + }, + "buildkit state": func(t *testing.T, s *builderServer, o *compose.Options) { + hook(t, "useradd", `/bin/touch "$DIR/buildkit"`) + }, + "settings": func(t *testing.T, s *builderServer, o *compose.Options) { + hook(t, "useradd", `/bin/mkdir -p "$DIR/builder.env/x"`) + }, + "own": func(t *testing.T, s *builderServer, o *compose.Options) { t.Setenv("FAIL", "chown -R") }, + "units": func(t *testing.T, s *builderServer, o *compose.Options) { + hook(t, "chown root:bx", `/bin/chmod 0500 "`+unitDir+`"`) + t.Cleanup(func() { _ = os.Chmod(unitDir, 0o755) }) + }, + "daemon-reload": func(t *testing.T, s *builderServer, o *compose.Options) { t.Setenv("FAIL", "systemctl daemon-reload") }, + "enable": func(t *testing.T, s *builderServer, o *compose.Options) { + t.Setenv("FAIL", "enable --now ansibleforms-buildkitd") + }, + "state": func(t *testing.T, s *builderServer, o *compose.Options) { + file := filepath.Join(t.TempDir(), "file") + _ = os.WriteFile(file, nil, 0o600) + t.Setenv("XDG_CONFIG_HOME", file) + }, + } + for name, setup := range cases { + t.Run(name, func(t *testing.T) { + s := newBuilderServer(t) + o := s.options(t) + setup(t, s, &o) + if _, _, err := Install(context.Background(), o); err == nil { + t.Errorf("%s: installed", name) + } + }) + } +} + +// ─── the release ────────────────────────────────────────────────────────────── + +// TestPrepareBuilder checks a release already there used as it is, and each step of one that +// fails: its folder, a release without binaries, one whose sums lack this architecture, and +// BuildKit. +func TestPrepareBuilder(t *testing.T) { + ctx := context.Background() + s := newBuilderServer(t) + l := layout{dir: s.dir, name: "bx"} + _ = os.MkdirAll(l.release("7.9.0"), 0o755) + _ = os.WriteFile(filepath.Join(l.release("7.9.0"), ".complete"), nil, 0o644) + if err := prepareBuilder(ctx, l, "7.9.0"); err != nil { + t.Errorf("complete release: %v", err) + } + if _, err := os.Stat(filepath.Join(l.release("7.9.0"), builderBinary)); err == nil { + t.Error("a complete release downloaded again") + } + + cases := map[string]func(t *testing.T, s *builderServer, l layout) string{ + "folder": func(t *testing.T, s *builderServer, l layout) string { + _ = os.MkdirAll(s.dir, 0o755) + _ = os.WriteFile(l.releases(), nil, 0o644) + return "7.9.0" + }, + "no binaries": func(t *testing.T, s *builderServer, l layout) string { return "7.8.0" }, + "another architecture": func(t *testing.T, s *builderServer, l layout) string { + s.files["/"+BuilderRepo+"/releases/download/7.9.0/SHA256SUMS"] = []byte("ffff ansibleforms-rte-builder_linux_s390x\n") + return "7.9.0" + }, + "buildkit": func(t *testing.T, s *builderServer, l layout) string { + buildkitSums["amd64"] = "0000" + return "7.9.0" + }, + } + for name, setup := range cases { + t.Run(name, func(t *testing.T) { + s := newBuilderServer(t) + l := layout{dir: s.dir, name: "bx"} + v := setup(t, s, l) + err := prepareBuilder(ctx, l, v) + if err == nil { + t.Fatalf("%s: prepared", name) + } + if name == "no binaries" && !strings.Contains(err.Error(), "7.8.0") { + t.Errorf("no binaries: %v", err) + } + }) + } +} + +// hooked serves a Builder's files as files does, running a hook before it serves the path +// named. +// +// Args: +// +// t: the test. +// s: the server whose files it serves. +// path: the path that runs the hook. +// hook: what it does. +func hooked(t *testing.T, s *builderServer, path string, hook func()) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == path { + hook() + } + b, ok := s.files[r.URL.Path] + if !ok { + http.NotFound(w, r) + return + } + _, _ = w.Write(b) + })) + t.Cleanup(srv.Close) + githubBase = srv.URL +} + +// TestPrepareBuilderLinks checks a release whose link to BuildKit, or whose mark of a +// complete release, cannot be written. +func TestPrepareBuilderLinks(t *testing.T) { + ctx := context.Background() + for name, path := range map[string]string{ + "buildkit link": "/" + BuilderRepo + "/releases/download/7.9.0/ansibleforms-rte-builder_linux_amd64", + "complete": "/moby/buildkit/releases/download/" + BuildkitVersion + "/buildkit-" + BuildkitVersion + ".linux-amd64.tar.gz", + } { + t.Run(name, func(t *testing.T) { + s := newBuilderServer(t) + l := layout{dir: s.dir, name: "bx"} + block := map[string]string{"buildkit link": "buildkit", "complete": ".complete"}[name] + hooked(t, s, path, func() { _ = os.MkdirAll(filepath.Join(l.release("7.9.0"), block, "x"), 0o755) }) + if err := prepareBuilder(ctx, l, "7.9.0"); err == nil { + t.Errorf("%s: prepared", name) + } + }) + } +} + +// TestInstallBuildkit checks BuildKit already there, an architecture without a pinned sum, a +// runtimes folder that cannot be made, and a folder in the way of the new one. +func TestInstallBuildkit(t *testing.T) { + ctx := context.Background() + s := newBuilderServer(t) + l := layout{dir: s.dir, name: "bx"} + dir, err := installBuildkit(ctx, l) + if err != nil { + t.Fatal(err) + } + if again, err := installBuildkit(ctx, l); err != nil || again != dir { + t.Errorf("again: %s, %v", again, err) + } + if _, err := installBuildkit(ctx, layout{dir: system.OSReleasePath}); err == nil { + t.Error("runtimes under a file") + } + in := layout{dir: filepath.Join(t.TempDir(), "in"), name: "bx"} + _ = os.MkdirAll(filepath.Join(in.runtime(), "buildkit-"+BuildkitVersion, "other"), 0o755) + if _, err := installBuildkit(ctx, in); err == nil { + t.Error("a folder in the way") + } + system.GOARCH = "arm64" + if _, err := installBuildkit(ctx, layout{dir: t.TempDir()}); err == nil || !strings.Contains(err.Error(), "arm64") { + t.Errorf("no sum for arm64: %v", err) + } +} + +// TestFetchBinary checks each way a binary's download fails: its sums missing or down, the +// program not listed or missing, a body cut short, a file that cannot be made, a checksum +// that differs and a folder in the way. +func TestFetchBinary(t *testing.T) { + ctx := context.Background() + body := []byte("program") + web := files(t, map[string][]byte{ + "/ok/SHA256SUMS": []byte(sum(body) + " prog\n"), + "/ok/prog": body, + "/gone/SHA256SUMS": []byte(sum(body) + " prog\n"), + "/bad/SHA256SUMS": []byte("0000 prog\n"), + "/bad/prog": body, + "/missing/SHA256SUMS": []byte("bad line\n"), + // /short answers 1000 bytes and sends 5 + "/SHA256SUMS": []byte(sum(body) + " short\n"), + }) + dir := t.TempDir() + if err := fetchBinary(ctx, web+"/ok", "prog", filepath.Join(dir, "prog")); err != nil { + t.Fatal(err) + } + for name, c := range map[string]struct{ base, name, dest string }{ + "no sums": {web + "/none", "prog", filepath.Join(dir, "a")}, + "server down": {web + "/broken", "prog", filepath.Join(dir, "a")}, + "not listed": {web + "/missing", "prog", filepath.Join(dir, "a")}, + "no program": {web + "/gone", "prog", filepath.Join(dir, "a")}, + "no folder": {web + "/ok", "prog", filepath.Join(dir, "none", "a")}, + "checksum": {web + "/bad", "prog", filepath.Join(dir, "a")}, + "cut short": {web, "short", filepath.Join(dir, "a")}, + "in the way": {web + "/ok", "prog", dir}, + } { + if err := fetchBinary(ctx, c.base, c.name, c.dest); err == nil { + t.Errorf("%s: fetched", name) + } + } +} + +// TestPruneBuildkit checks the BuildKits no release links to deleted, the one in use and the +// other runtimes kept. +func TestPruneBuildkit(t *testing.T) { + l := layout{dir: t.TempDir(), name: "bx"} + for _, d := range []string{"buildkit-v1", "buildkit-v2", "node-v26"} { + _ = os.MkdirAll(filepath.Join(l.runtime(), d), 0o755) + } + _ = os.MkdirAll(l.release("7.9.0"), 0o755) + _ = os.Symlink(filepath.Join(l.runtime(), "buildkit-v2"), filepath.Join(l.release("7.9.0"), "buildkit")) + _ = os.MkdirAll(l.release("7.8.0"), 0o755) + pruneBuildkit(l) + for d, kept := range map[string]bool{"buildkit-v1": false, "buildkit-v2": true, "node-v26": true} { + if _, err := os.Stat(filepath.Join(l.runtime(), d)); (err == nil) != kept { + t.Errorf("%s kept: %v", d, err == nil) + } + } + pruneBuildkit(layout{dir: filepath.Join(l.dir, "none")}) +} + +// ─── upgrade and the rest ───────────────────────────────────────────────────── + +// TestUpgradeBuilder checks an upgrade: the new release next to the old one, the units +// written again, both services moved to it, the old releases and BuildKits pruned, the state +// saved ; then a rollback to the version before, without a database. +func TestUpgradeBuilder(t *testing.T) { + s, st := installedBuilder(t) + l := layout{dir: s.dir, name: "bx"} + _ = os.MkdirAll(l.release("7.1.0"), 0o755) + _ = os.MkdirAll(filepath.Join(l.runtime(), "buildkit-v0.1.0"), 0o755) + undo, err := Upgrade(context.Background(), st, "7.10.0") + if err != nil { + t.Fatal(err) + } + if st.Version != "7.10.0" || currentVersion(l) != "7.10.0" || undo.Version != "7.9.0" || undo.Dump != "" { + t.Errorf("state %+v, undo %+v", st, undo) + } + for p, kept := range map[string]bool{ + l.release("7.1.0"): false, l.release("7.9.0"): true, filepath.Join(l.runtime(), "buildkit-v0.1.0"): false, + filepath.Join(l.runtime(), "buildkit-"+BuildkitVersion): true, + } { + if _, err := os.Stat(p); (err == nil) != kept { + t.Errorf("%s kept: %v", p, err == nil) + } + } + if !s.bin.Called("systemctl stop ansibleforms-buildkitd bx") || !s.bin.Called("systemctl start ansibleforms-buildkitd bx") { + t.Errorf("calls %q", s.bin.Calls()) + } + if err := Rollback(context.Background(), st, undo); err != nil || st.Version != "7.9.0" || currentVersion(l) != "7.9.0" { + t.Errorf("rollback %v, %+v", err, st) + } + if s.bin.Called("mariadb") { + t.Error("a Builder has no database") + } +} + +// TestUpgradeBuilderFails checks that each step that fails stops a Builder's upgrade, with +// what a rollback needs once the services were touched. +func TestUpgradeBuilderFails(t *testing.T) { + cases := map[string]func(t *testing.T, s *builderServer, st *state.State) string{ + "release": func(t *testing.T, s *builderServer, st *state.State) string { return "9.9.9" }, + "own": func(t *testing.T, s *builderServer, st *state.State) string { + t.Setenv("FAIL", "chown -R") + return "7.10.0" + }, + "units": func(t *testing.T, s *builderServer, st *state.State) string { + p := layout{name: "bx"}.unitPath("builder") + _ = os.Remove(p) + _ = os.MkdirAll(filepath.Join(p, "x"), 0o755) + return "7.10.0" + }, + "daemon-reload": func(t *testing.T, s *builderServer, st *state.State) string { + t.Setenv("FAIL", "systemctl daemon-reload") + return "7.10.0" + }, + "stop": func(t *testing.T, s *builderServer, st *state.State) string { + t.Setenv("FAIL", "systemctl stop") + return "7.10.0" + }, + "switch": func(t *testing.T, s *builderServer, st *state.State) string { + hook(t, "systemctl stop", `/bin/mkdir -p "$DIR/current.new/full"`) + return "7.10.0" + }, + "start": func(t *testing.T, s *builderServer, st *state.State) string { + t.Setenv("FAIL", "systemctl start") + return "7.10.0" + }, + "state": func(t *testing.T, s *builderServer, st *state.State) string { + file := filepath.Join(t.TempDir(), "file") + _ = os.WriteFile(file, nil, 0o600) + t.Setenv("XDG_CONFIG_HOME", file) + return "7.10.0" + }, + } + for name, setup := range cases { + t.Run(name, func(t *testing.T) { + s, st := installedBuilder(t) + to := setup(t, s, st) + if _, err := Upgrade(context.Background(), st, to); err == nil { + t.Errorf("%s: upgraded", name) + } + }) + } + t.Run("port", func(t *testing.T) { + s, st := installedBuilder(t) + _ = os.Remove(layout{dir: s.dir}.env("builder")) + st.Port = 1 + ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) + defer cancel() + if _, err := Upgrade(ctx, st, "7.10.0"); err == nil { + t.Error("a builder that does not listen") + } + }) +} + +// TestBuilderStatusAndUninstall checks a Builder's services shown with its port from its +// settings or its state, no backup, and its uninstall: the services removed, and with purge +// its folder and its user, never a database. +func TestBuilderStatusAndUninstall(t *testing.T) { + ctx := context.Background() + s, st := installedBuilder(t) + if err := Status(ctx, st); err != nil { + t.Error(err) + } + if !s.bin.Called("systemctl status --no-pager --lines=0 ansibleforms-buildkitd bx") { + t.Errorf("calls %q", s.bin.Calls()) + } + _ = os.Remove(layout{dir: s.dir}.env("builder")) + st.Port = 1 + if err := Status(ctx, st); err != nil { + t.Error(err) + } + if _, err := Backup(ctx, st); err == nil { + t.Error("a Builder backed up") + } + if err := Uninstall(ctx, st, true); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(s.dir); err == nil || !s.bin.Called("userdel bx") || s.bin.Called("mariadb") || + !s.bin.Called("systemctl disable --now ansibleforms-buildkitd") || !s.bin.Called("systemctl disable --now bx") { + t.Errorf("not purged: %q", s.bin.Calls()) + } + for _, service := range []string{"buildkitd", "builder"} { + if _, err := os.Stat(layout{name: "bx"}.unitPath(service)); err == nil { + t.Errorf("the %s unit stayed", service) + } + } + s2, st2 := installedBuilder(t) + if err := Uninstall(ctx, st2, false); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(layout{dir: s2.dir}.data()); err != nil { + t.Error("the data went without purge") + } +} diff --git a/internal/native/native.go b/internal/native/native.go index 9c2c80e..89b446c 100644 --- a/internal/native/native.go +++ b/internal/native/native.go @@ -1,7 +1,8 @@ // Package native installs, upgrades and backs up AnsibleForms directly on a server, without // containers: the release bundle (the app built for Node.js), Node.js itself, Python, Ansible // and the collections of the RTE images for the Runner, systemd services, and for a controller -// MariaDB from the distribution's packages. +// MariaDB from the distribution's packages. A Builder is the builder's binary and BuildKit +// instead (builder.go). // // The layout of an installation folder (/opt/ansibleforms): // @@ -86,10 +87,14 @@ func (l layout) home() string { return filepath.Join(l.dir, "home") func (l layout) env(service string) string { return filepath.Join(l.dir, service+".env") } func (l layout) backups() string { return filepath.Join(l.dir, "installer-backups") } -// unit is the systemd unit of a service: for the app, -rte for the RTE. +// unit is the systemd unit of a service: for the app and the builder, -rte for +// the RTE, and BuildKit's own name for BuildKit (one per server, as its socket is). func (l layout) unit(service string) string { - if service == "app" { + switch service { + case "app", "builder": return l.name + case "buildkitd": + return buildkitUnit } return l.name + "-" + service } @@ -103,10 +108,14 @@ func (l layout) unitPath(service string) string { // their own. var unitDir = "/etc/systemd/system" -// services are the systemd services of a role: the app and its RTE, or a Runner's RTE alone. +// services are the systemd services of a role: the app and its RTE, a Runner's RTE alone, or +// a Builder's BuildKit and the builder (BuildKit first, as it starts first). func services(role string) []string { - if role == compose.RoleRunner { + switch role { + case compose.RoleRunner: return []string{"rte"} + case compose.RoleBuilder: + return []string{"buildkitd", "builder"} } return []string{"app", "rte"} } @@ -139,6 +148,9 @@ func Install(ctx context.Context, o compose.Options) (*state.State, *compose.Res return nil, nil, errors.New(i18n.T("native.exists", "name", l.unit(s))) } } + if o.Role == compose.RoleBuilder { + return installBuilder(ctx, l, o) + } ui.Step(i18n.T("native.prereqs")) pkgs := basePackages @@ -301,7 +313,7 @@ func own(ctx context.Context, l layout) error { return err } } - for _, s := range []string{"app", "rte"} { + for _, s := range []string{"app", "rte", "builder"} { if _, err := os.Stat(l.env(s)); err == nil { if err := system.Run(ctx, "", "chown", "root:"+l.name, l.env(s)); err != nil { return err @@ -1067,13 +1079,6 @@ func waitPort(ctx context.Context, unit string, port int, timeout time.Duration) return errors.New(i18n.T("native.notReady", "unit", unit)) } -// rtePort reads the RTE's port from its settings. -func rtePort(l layout) int { - env, _ := readEnvFile(l.env("rte")) - p, _ := strconv.Atoi(env["PORT"]) - return p -} - // systemctl runs systemctl on the services of an installation. func systemctl(ctx context.Context, l layout, role, verb string) error { args := []string{verb} @@ -1098,10 +1103,13 @@ func systemctl(ctx context.Context, l layout, role, verb string) error { // // Errors: // -// For a Runner (its controller holds the data), or when the dump fails. +// For a Runner or a Builder (its controller holds the data), or when the dump fails. func Backup(ctx context.Context, st *state.State) (string, error) { - if st.Role == compose.RoleRunner { + switch st.Role { + case compose.RoleRunner: return "", errors.New(i18n.T("compose.runnerNoBackup")) + case compose.RoleBuilder: + return "", errors.New(i18n.T("compose.builderNoBackup")) } l := layout{dir: st.Dir, name: st.Name} if err := os.MkdirAll(l.backups(), 0o700); err != nil { @@ -1148,6 +1156,9 @@ type Undo struct { // // When a step fails. func Upgrade(ctx context.Context, st *state.State, to string) (*Undo, error) { + if st.Role == compose.RoleBuilder { + return upgradeBuilder(ctx, st, to) + } l := layout{dir: st.Dir, name: st.Name} undo := &Undo{Version: st.Version} if err := prepareRelease(ctx, l, to); err != nil { @@ -1266,28 +1277,35 @@ func Status(ctx context.Context, st *state.State) error { if v := currentVersion(l); v != "" { ui.Muted(filepath.Join(l.dir, "releases", v)) } - if st.Role != compose.RoleRunner { + switch st.Role { + case compose.RoleRunner, compose.RoleBuilder: + // a Runner's RTE or the builder : its port takes connections + service := map[bool]string{true: "builder", false: "rte"}[st.Role == compose.RoleBuilder] + if err := waitPort(ctx, l.unit(service), envPort(l, service, st.Port), 3*time.Second); err != nil { + ui.Warn(err.Error()) + } + default: if v, err := waitApp(ctx, URL(st), 5*time.Second); err == nil { ui.Done(i18n.T("status.answers", "url", URL(st), "version", v)) } else { ui.Warn(i18n.T("status.noAnswer", "url", URL(st))) } - } else if err := waitPort(ctx, l.unit("rte"), rtePortOr(l, st.Port), 3*time.Second); err != nil { - ui.Warn(err.Error()) } return nil } -// rtePortOr is the RTE's port from its settings, or a default. -func rtePortOr(l layout, def int) int { - if p := rtePort(l); p != 0 { +// envPort is a service's port from its settings, or a default. +func envPort(l layout, service string, def int) int { + env, _ := readEnvFile(l.env(service)) + if p, _ := strconv.Atoi(env["PORT"]); p != 0 { return p } return def } // Uninstall stops and removes the services and, with purge, the folder, the system user and -// the database with its user. The packages stay: other software may use them. +// the database with its user (a Builder's folder holds BuildKit's state and cache too). The +// packages stay: other software may use them. // // Args: // @@ -1306,7 +1324,7 @@ func Uninstall(ctx context.Context, st *state.State, purge bool) error { } _ = system.Run(ctx, "", "systemctl", "daemon-reload") if purge { - if st.Role != compose.RoleRunner { + if st.Role != compose.RoleRunner && st.Role != compose.RoleBuilder { if err := dropDatabase(ctx, st.Name); err != nil { return err }