Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 15 additions & 12 deletions .github/workflows/app-release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -99,24 +99,27 @@ jobs:
if: steps.target.outputs.base == '' && fromJSON(steps.target.outputs.major) <= fromJSON(steps.target.outputs.current)
run: echo "::notice::No installer line follows AnsibleForms ${{ steps.target.outputs.major }} any more, nothing to bump."

# The RTE images are published by ansibleforms/rte, a few minutes after the app's own
# image. The installer of this version installs ansibleforms-rte-full of the same
# version, so the bump waits until it is published : a release never points at an image
# that is not there yet
- name: Wait for the RTE of the version
# The RTE images are published by ansibleforms/rte, and the RTE Runner by
# ansibleforms/runner, a few minutes after the app's own image. The installer of this
# version installs the Runner of the same version, its jobs running ansibleforms-rte-full,
# so the bump waits until both are published : a release never points at an image that is
# not there yet
- name: Wait for the RTE and the Runner of the version
if: steps.target.outputs.base != ''
env:
VERSION: ${{ steps.target.outputs.version }}
run: |
set -euo pipefail
for i in $(seq 1 60); do
if docker manifest inspect "ghcr.io/ansibleforms/ansibleforms-rte-full:${VERSION}" >/dev/null 2>&1; then
echo "ghcr.io/ansibleforms/ansibleforms-rte-full:${VERSION} is published."; exit 0
fi
sleep 30
for image in ansibleforms-rte-full ansibleforms-rte-runner; do
for i in $(seq 1 60); do
if docker manifest inspect "ghcr.io/ansibleforms/${image}:${VERSION}" >/dev/null 2>&1; then
echo "ghcr.io/ansibleforms/${image}:${VERSION} is published."; continue 2
fi
sleep 30
done
echo "::error::ghcr.io/ansibleforms/${image}:${VERSION} was not published within 30 minutes. Once it is, run this workflow again by hand with ${VERSION}."
exit 1
done
echo "::error::ghcr.io/ansibleforms/ansibleforms-rte-full:${VERSION} was not published within 30 minutes. Once ansibleforms/rte published it, run this workflow again by hand with ${VERSION}."
exit 1

- uses: actions/create-github-app-token@v3
id: app
Expand Down
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,13 @@

## Unreleased

### Changed

- **The RTE is the Runner written in Go, on Docker and Podman**: it starts each playbook in a
container of its own from `ansibleforms-rte-full`, through the engine's socket, which gives it
that engine's rights on the server. An upgrade switches an existing RTE in place, under the same
name, token and runner; `data/ansible`, the SSH key and the pip libraries still reach every job.

## 7.8.0

AnsibleForms 7.8.0.
Expand Down
64 changes: 49 additions & 15 deletions internal/compose/compose.go
Original file line number Diff line number Diff line change
Expand Up @@ -386,6 +386,9 @@ func writeController(ctx context.Context, o Options) (*Result, error) {
return nil, err
}
}
if err := prepareEngine(ctx, o.Runtime, o.Dir); err != nil {
return nil, err
}
return &Result{
URL: fmt.Sprintf("%s://localhost:%d", scheme, o.Port),
AdminUser: orDefault(GetEnv(string(env), "ADMIN_USERNAME"), "admin"),
Expand Down Expand Up @@ -430,43 +433,73 @@ func pinCompose(dir, version, name string) error {
return os.WriteFile(p, []byte(PrepareCompose(string(data), version, name)), 0o644)
}

// runnerCompose is a runner's compose file: the RTE alone, talking to the app over one
// WebSocket (RTE_MODE in .env), with no database credentials. An inbound runner serves HTTPS
// (HTTPS=1 in .env) with ./data/certificates, where the app's image reads its certificate.
const runnerCompose = `# AnsibleForms RTE runner, written by the AnsibleForms installer.
// runnerCompose is a runner's compose file: the RTE Runner alone, talking to the app over one
// WebSocket (RTE_MODE in .env), with no database credentials, starting each job in a container
// of its own through the engine's socket (engine.go). An inbound runner serves HTTPS (HTTPS=1 in
// .env) with ./data/certificates.
const runnerCompose = `# AnsibleForms RTE Runner, written by the AnsibleForms installer.
# It runs the playbooks of the app at APP_URL (see .env) over one WebSocket : it dials the app
# (RTE_MODE=outbound) or the app dials it (RTE_MODE=inbound). It holds no database credentials.
# The job's files come from the app with each job ; ./data keeps what is not acked yet
# (rte-spool), the files received (rte-files), and its ansible.cfg, roles and collections.
# It starts each job in a container of its own from RTE_IMAGE, through the engine's socket
# (ENGINE_SOCKET in .env), which gives it that engine's full rights on this server. The job's
# files come from the app with each job ; ./data keeps what is not acked yet (rte-spool), the
# files received (rte-files), and the ansible.cfg, roles, collections, SSH key and python
# libraries every job gets (RTE_JOB_MOUNTS).
# Inbound, it serves HTTPS (HTTPS=1 in .env) with the certificate in ./data/certificates.
services:
rte:
image: {{IMAGE}}
container_name: {{NAME}}_rte
restart: unless-stopped
user: "${RTE_USER:-1000}"
group_add:
- "${ENGINE_SOCKET_GID:-0}"
ports:
- ${RTE_LOCAL_PORT}:8000
env_file:
- ./.env
environment:
- PORT=8000
- HTTPS=${HTTPS:-0}
- RTE_ENGINE_SOCKET=/run/engine.sock
- RTE_IMAGE={{JOB_IMAGE}}
- RTE_JOB_MOUNTS=` + jobMounts + `
- PYTHONPATH=/app/dist/persistent/python/lib
healthcheck:
test: ["CMD", "node", "./healthcheck.js"]
test: ["CMD", "ansibleforms-rte-runner", "health"]
interval: 10s
timeout: 5s
retries: 30
start_period: 30s
volumes:
- ./data:/app/dist/persistent
- ./data/ssh:/home/node/.ssh
- ./data/git/.gitconfig:/home/node/.gitconfig
- ./data/ansible/ansible.cfg:/etc/ansible/ansible.cfg
- ./data/ansible/roles:/etc/ansible/roles
- ./data/ansible/collections:/etc/ansible/collections
- ${ENGINE_SOCKET:-/var/run/docker.sock}:/run/engine.sock
`

// jobMounts is what every job gets from ./data, as the playbooks had it in the RTE's own
// container before 7.9.0 : the ansible.cfg, roles and collections, the SSH key and the git
// settings, and the libraries the pip install playbook adds.
const jobMounts = "/app/dist/persistent/ansible/ansible.cfg:/etc/ansible/ansible.cfg," +
"/app/dist/persistent/ansible/roles:/etc/ansible/roles," +
"/app/dist/persistent/ansible/collections:/etc/ansible/collections," +
"/app/dist/persistent/ssh:/home/node/.ssh:rw," +
"/app/dist/persistent/git/.gitconfig:/home/node/.gitconfig," +
"/app/dist/persistent/python:/app/dist/persistent/python:rw"

// runnerComposeFor is a runner's compose file for a version and an instance.
//
// Args:
//
// version: the AnsibleForms version.
// name: the instance's name.
//
// Returns:
//
// The compose file.
func runnerComposeFor(version, name string) string {
return strings.NewReplacer("{{IMAGE}}", RunnerImage(version), "{{JOB_IMAGE}}", RteImage(version), "{{NAME}}", name).Replace(runnerCompose)
}

// runnerData are the docker repository's folders a runner keeps: the ansible configuration,
// roles and collections, and the SSH and git settings (its playbooks come from the app).
var runnerData = []string{"data", "data/ansible", "data/ssh", "data/git"}
Expand Down Expand Up @@ -500,7 +533,7 @@ func writeRunner(ctx context.Context, o Options, carry map[string]string) (*Resu
if _, _, err := Fetch(ctx, o.Version, o.Dir, only, o.KeepData); err != nil {
return nil, err
}
content := strings.NewReplacer("{{IMAGE}}", RteImage(o.Version), "{{NAME}}", o.Name).Replace(runnerCompose)
content := runnerComposeFor(o.Version, o.Name)
r := o.Runner
token := r.Token
if token == "" {
Expand All @@ -513,8 +546,6 @@ func writeRunner(ctx context.Context, o Options, carry map[string]string) (*Resu
}
lines := []string{
"# AnsibleForms RTE runner, written by the AnsibleForms installer",
"AF_ROLE=rte",
"NODE_ENV=production",
"# outbound : it dials the app ; inbound : the app dials it at RTE_URL",
"RTE_MODE=" + r.Mode,
"# the app's address",
Expand Down Expand Up @@ -561,6 +592,9 @@ func writeRunner(ctx context.Context, o Options, carry map[string]string) (*Resu
// installer's own, just written)
_ = os.Chmod(p, f.mode)
}
if err := prepareEngine(ctx, o.Runtime, o.Dir); err != nil {
return nil, err
}
return res, nil
}

Expand Down
12 changes: 10 additions & 2 deletions internal/compose/compose_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,8 +88,9 @@ func newHost(t *testing.T) *host {
"data/seed.yaml": read(t, "seed-7.3.yaml"),
"data/mysql/conf.d/my.cnf": "[mysqld]\n",
})
wasSource, wasEuid, wasWait, wasPoll, wasSystemd := Source, geteuid, waitApp, pollEvery, systemdDir
wasSource, wasEuid, wasWait, wasPoll, wasSystemd, wasGID := Source, geteuid, waitApp, pollEvery, systemdDir, socketGID
Source, pollEvery, systemdDir = h.repo, 10*time.Millisecond, t.TempDir()+"/"
socketGID = func(string) (int, error) { return 998, nil }
geteuid = func() int { return 1001 }
t.Setenv("ANSWERS", "7.3.0")
waitApp = func(_ context.Context, url string, _ time.Duration) (string, error) {
Expand All @@ -99,7 +100,7 @@ func newHost(t *testing.T) *host {
return "", errors.New("no answer at " + url)
}
t.Cleanup(func() {
Source, geteuid, waitApp, pollEvery, systemdDir = wasSource, wasEuid, wasWait, wasPoll, wasSystemd
Source, geteuid, waitApp, pollEvery, systemdDir, socketGID = wasSource, wasEuid, wasWait, wasPoll, wasSystemd, wasGID
})
return h
}
Expand Down Expand Up @@ -239,6 +240,13 @@ func TestInstallFails(t *testing.T) {
"up": func(t *testing.T, h *host, o *Options) { t.Setenv("FAIL", "compose -p af up") },
"state": func(t *testing.T, h *host, o *Options) { t.Setenv("XDG_CONFIG_HOME", filepath.Join(h.repo, ".env")) },
"no answer": func(t *testing.T, h *host, o *Options) { t.Setenv("ANSWERS", "") },
"engine": func(t *testing.T, h *host, o *Options) {
socketGID = func(string) (int, error) { return 0, errors.New("no socket") }
},
"runner engine": func(t *testing.T, h *host, o *Options) {
o.Role, o.Runner = RoleRunner, RunnerOptions{Mode: "outbound"}
socketGID = func(string) (int, error) { return 0, errors.New("no socket") }
},
"runner fetch": func(t *testing.T, h *host, o *Options) {
o.Role, o.Runner = RoleRunner, RunnerOptions{Mode: "outbound"}
Source = filepath.Join(t.TempDir(), "none")
Expand Down
121 changes: 121 additions & 0 deletions internal/compose/engine.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
package compose

// ─── the engine the Runner starts the jobs on ─────────────────────────────────
//
// From 7.9.0 the RTE of a compose installation is the RTE Runner written in Go: it starts each
// job in a container of its own, through the engine's socket mounted into its container. The
// compose files (the docker repository's, and a Runner's own below) read where that socket is,
// and how the Runner's container may use it, from the .env : RTE_ENGINE, ENGINE_SOCKET,
// ENGINE_SOCKET_GID and RTE_USER.

import (
"context"
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
"syscall"

"github.com/ansibleforms/installer/internal/system"
)

// socketGID reads the group a socket belongs to ; the tests give their own.
var socketGID = func(path string) (int, error) {
info, err := os.Stat(path)
if err != nil {
return 0, err
}
return int(info.Sys().(*syscall.Stat_t).Gid), nil
}

// engineAccess is how a Runner's container reaches the engine that starts its jobs.
type engineAccess struct {
// Engine is docker or podman.
Engine string
// Socket is the engine's socket on this server.
Socket string
// GID is the socket's group, which the Runner's user joins.
GID int
// User is the Runner's user in its container: 1000, or 0 with rootless Podman, whose
// container root is the user running Podman.
User string
}

// findEngine finds the engine's socket on this server: Docker's (DOCKER_HOST when it names a
// unix socket, else /var/run/docker.sock), rootful Podman's (/run/podman/podman.sock) or
// rootless Podman's (/run/user/<uid>/podman/podman.sock), Podman's systemd socket started for
// it first (a server without systemd may run it otherwise: the socket itself decides).
//
// Args:
//
// ctx: the context, to cancel.
// r: the runtime.
//
// Returns:
//
// How the Runner's container reaches it.
//
// Errors:
//
// When the socket cannot be read.
func findEngine(ctx context.Context, r system.Runtime) (engineAccess, error) {
a := engineAccess{Engine: string(r), User: "1000"}
switch {
case r == system.Podman && geteuid() == 0:
a.Socket = "/run/podman/podman.sock"
_ = system.Run(ctx, "", "systemctl", "enable", "--now", "podman.socket")
case r == system.Podman:
a.Socket, a.User = fmt.Sprintf("/run/user/%d/podman/podman.sock", geteuid()), "0"
_ = system.Run(ctx, "", "systemctl", "--user", "enable", "--now", "podman.socket")
default:
a.Engine, a.Socket = string(system.Docker), "/var/run/docker.sock"
if v := os.Getenv("DOCKER_HOST"); strings.HasPrefix(v, "unix://") {
a.Socket = strings.TrimPrefix(v, "unix://")
}
}
gid, err := socketGID(a.Socket)
if err != nil {
return a, fmt.Errorf("the %s socket %s cannot be read: %w", a.Engine, a.Socket, err)
}
a.GID = gid
return a, nil
}

// env is what the compose files read of it, for the .env.
//
// Returns:
//
// RTE_ENGINE, ENGINE_SOCKET, ENGINE_SOCKET_GID and RTE_USER.
func (a engineAccess) env() map[string]string {
return map[string]string{"RTE_ENGINE": a.Engine, "ENGINE_SOCKET": a.Socket, "ENGINE_SOCKET_GID": strconv.Itoa(a.GID), "RTE_USER": a.User}
}

// prepareEngine readies an installation folder for the Runner: the engine's settings in its
// .env, and data/python/lib, the folder every job gets for the libraries the pip install
// playbook adds (made here, so the engine does not make it as root).
//
// Args:
//
// ctx: the context, to cancel.
// r: the runtime.
// dir: the installation folder.
//
// Errors:
//
// When the engine cannot be found, or a file cannot be written.
func prepareEngine(ctx context.Context, r system.Runtime, dir string) error {
a, err := findEngine(ctx, r)
if err != nil {
return err
}
envPath := filepath.Join(dir, ".env")
env, err := os.ReadFile(envPath)
if err != nil {
return err
}
if err := os.WriteFile(envPath, []byte(SetEnv(string(env), a.env())), 0o600); err != nil {
return err
}
return os.MkdirAll(filepath.Join(dir, "data", "python", "lib"), 0o755)
}
Loading