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
10 changes: 6 additions & 4 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,8 @@ jobs:

# A real playbook in a real job's container, on Docker and on Podman: the Runner's static
# binary copied into the RTE image, the job streamed in, its lines read back as the container's
# logs ; one job ends successfully, one stopped ends as aborted (the integration tag).
# logs ; one job ends successfully, one stopped ends as aborted, one is paused before its next
# task and resumed by the Runner's control command, run by an exec (the integration tag).
playbook:
name: Playbook (${{ matrix.engine }})
runs-on: ubuntu-latest
Expand Down Expand Up @@ -133,12 +134,13 @@ jobs:
run: |
set -euo pipefail
CGO_ENABLED=0 go build -trimpath -o "$AF_RUNNER_BINARY" .
go test -tags integration -count=1 -v -run TestRealPlaybook ./internal/engine/docker
go test -tags integration -count=1 -v -run 'TestRealPlaybook|TestRealPause' ./internal/engine/docker

# A real playbook in a real job's pod on a kind cluster, as the Runner's service account with
# the Role of deploy/kubernetes-rbac.yaml: the Runner's image built and loaded, its binary
# copied into the pod by the init container, the job written on the pod's stdin through the
# API ; one job ends successfully, one stopped ends as aborted, and one reads the volumes of a
# API ; one job ends successfully, one stopped ends as aborted, one is paused before its next
# task and resumed through attaches of their own, and one reads the volumes of a
# pod that stands for the Runner's (RTE_JOB_MOUNTS): a file on its ReadWriteOnce claim and its
# secret's key (the integration tag).
kubernetes:
Expand Down Expand Up @@ -230,7 +232,7 @@ jobs:
AF_K8S_CA: ${{ runner.temp }}/ca.crt
AF_RUNNER_IMAGE: af-ci/ansibleforms-rte-runner:ci
RTE_IMAGE: ghcr.io/ansibleforms/ansibleforms-rte-core:7
run: go test -tags integration -count=1 -v -run 'TestRealPlaybook|TestRealMounts' ./internal/engine/kubernetes
run: go test -tags integration -count=1 -v -run 'TestRealPlaybook|TestRealPause|TestRealMounts' ./internal/engine/kubernetes

- name: The pods, when it failed
if: failure()
Expand Down
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ The changes made to the Runner between two releases wait under Unreleased and go
### Added

- **A repository's folder:** a repository's own checkout is read from the folder the controller names as its root
- **Pause and resume:** a playbook job pauses before its next task, and resumes there or from its checkpoints

## 7.9.0

Expand Down
6 changes: 3 additions & 3 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,15 @@ The Runner is one small Go program; each package under `internal/` holds one par

| Path | Holds |
|---|---|
| `main.go` | the start: its settings, its engine, its probes, its dial; the `job`, `health` and `version` commands |
| `main.go` | the start: its settings, its engine, its probes, its dial; the `job`, `control`, `health` and `version` commands |
| `internal/runner/` | the Runner's peer: the jobs the controller hands over, each one's container followed, its items |
| `internal/engine/` | the engines of the jobs' containers: `docker` (Docker and Podman) and `kubernetes` |
| `internal/jobstream/` | what goes between the Runner and a job's container: the job on stdin, numbered lines out |
| `internal/jobstream/` | what goes between the Runner and a job's container: the job and its pauses on stdin, numbered lines out |
| `internal/agent/` | the `job` command, inside a job's container: reads the job, runs it, writes its lines |
| `internal/ansible/` | a playbook's run, as the controller's own Runner runs it: its arguments, environment, end |
| `internal/files/` | the cache of the playbooks and inventories the controller sends |
| `internal/mask/`, `internal/output/`, `internal/events/` | a job's secrets masked, its output batched, its events read |
| `internal/plugins/` | the callback plugins every run loads |
| `internal/plugins/` | the callback and cache plugins every run loads |
| `internal/sshkey/` | a credential's SSH key, with its passphrase, for a run |
| `internal/settings/` | its environment variables |
| `internal/socket/` | the controller's socket, as the controller speaks it: protocol, session, spool, dial, listen |
Expand Down
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ The controller decides what runs and where; the Runner runs it, each job apart,
- **Docker, Podman or Kubernetes:** through their API, a pod per job on Kubernetes
- **Runs ansible-core:** every playbook, with its inventory, credentials, limit and extra vars
- **Live output:** every line reaches the controller's job as it runs, its secrets masked
- **Pause and resume:** a playbook holds before its next task, or starts again from its checkpoints
- **Survives a restart:** a restarted Runner finds its jobs' containers and reads on where it stopped
- **Survives a drop:** what the controller did not store yet is sent again after a reconnect
- **One small binary:** no Node.js, no Python: the jobs' image brings ansible-core
Expand All @@ -31,7 +32,7 @@ The controller decides what runs and where; the Runner runs it, each job apart,

The controller hands each job to a Runner, its files and credentials sealed for it, and the Runner runs it in a container of its own.
It writes the job on the container's stdin and reads its output from the container's logs: nothing is shared on the network or a disk,
and aborting a job just stops its container.
and aborting a job just stops its container. A pause or a resume reaches the job on its stdin on Kubernetes, and through an exec of the Runner's control command on Docker and Podman.

A Runner joins its controller in one of two modes (`RTE_MODE`):

Expand Down
213 changes: 210 additions & 3 deletions internal/agent/agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,24 +3,31 @@
// would run it (internal/ansible), and writes its items, their secrets masked, as numbered lines
// on its stdout, which the Runner reads as the container's logs. A SIGTERM (the container
// stopped: the job aborted) stops the playbook's process group, the job then ended as aborted.
// Its pauses and resumes come after the job on its stdin (Kubernetes), or through its control
// pipe, which the control command writes (Docker and Podman run it in the container): a pause
// makes the playbook's pause file, which holds it before its next task, a resume removes it. Its
// checkpoints go out sealed with the job's own key, as the controller's own Runner seals them.
package agent

import (
"encoding/json"
"errors"
"fmt"
"io"
"os"
"os/signal"
"path/filepath"
"sync"
"syscall"
"time"

"github.com/ansibleforms/runner/internal/ansible"
"github.com/ansibleforms/runner/internal/jobstream"
"github.com/ansibleforms/runner/internal/logger"
"github.com/ansibleforms/runner/internal/mask"
"github.com/ansibleforms/runner/internal/output"
"github.com/ansibleforms/runner/internal/plugins"
"github.com/ansibleforms/runner/internal/socket"
)

// What the tests replace: how the playbook runs, where the job's folder is made, and how its
Expand All @@ -30,15 +37,106 @@ var (
tempDir = os.TempDir
kill = syscall.Kill
pluginsWrite = plugins.Write
cacheWrite = plugins.WriteCache
// controlWait is how long the control command waits for the job to read its control pipe.
controlWait = 30 * time.Second
)

// lines is a job's IO: each item a numbered line, its secrets masked ; an abort its flag.
// controlPipe is the job's control pipe: a named pipe the job reads its pauses and resumes from,
// one JSON line each, at a path the control command knows.
//
// Returns:
//
// The path.
func controlPipe() string { return filepath.Join(tempDir(), "ansibleforms-control") }

// openControls makes the job's control pipe and reads it in the background: each pause or resume
// handed to the job. Opened for reading and writing, it never ends when a writer goes.
//
// Args:
//
// l: the job's IO.
//
// Returns:
//
// What closes it ; nothing when it cannot be made (a pause then reaches the job on its stdin
// only).
func openControls(l *lines) func() {
pipe := controlPipe()
if err := syscall.Mkfifo(pipe, 0o600); err != nil && !errors.Is(err, os.ErrExist) {
logger.Warning("The job's control pipe cannot be made: %v", err)
return func() {}
}
f, err := os.OpenFile(pipe, os.O_RDWR, 0)
if err != nil {
logger.Warning("The job's control pipe cannot be read: %v", err)
return func() {}
}
go jobstream.ReadControls(f, func(c jobstream.Control) { l.setPaused(c.Paused, c.By) })
return func() {
_ = f.Close()
_ = os.Remove(pipe)
}
}

// Control is the control command (ansibleforms-rte-runner control <line>), which the Runner runs
// in a job's container: it writes a pause or a resume on the job's control pipe, made when the job
// did not make it yet, waiting up to controlWait for the job to read it.
//
// Args:
//
// args: the control's line (jobstream.ControlLine), without its end.
// out: where it says why it failed.
//
// Returns:
//
// The exit code: 0 once written, 1 when it could not be.
func Control(args []string, out io.Writer) int {
if len(args) != 1 {
fmt.Fprintln(out, "the control command takes one control line")
return 1
}
pipe := controlPipe()
if err := syscall.Mkfifo(pipe, 0o600); err != nil && !errors.Is(err, os.ErrExist) {
fmt.Fprintf(out, "the job's control pipe cannot be made: %v\n", err)
return 1
}
// without a reader a write-only open fails at once (ENXIO): tried again until the job reads it
deadline := time.Now().Add(controlWait)
for {
f, err := os.OpenFile(pipe, os.O_WRONLY|syscall.O_NONBLOCK, 0)
if err == nil {
// a line shorter than a pipe's atomic write: written whole or not at all
_, err = f.Write([]byte(args[0] + "\n"))
f.Close()
}
if err == nil {
return 0
}
if time.Now().After(deadline) {
fmt.Fprintf(out, "the job does not read its control pipe: %v\n", err)
return 1
}
time.Sleep(100 * time.Millisecond)
}
}

// lines is a job's IO: each item a numbered line, its secrets masked ; an abort its flag ; a
// pause its file.
type lines struct {
w *jobstream.Writer
mask *mask.Job
mu sync.Mutex
pid int
abort bool
// id is the job, key its own key that seals its checkpoints (none: it records none)
id int64
key []byte
// paused tells a pause is wanted, by who asked it ; pauseFile is the playbook's pause file
// while it runs
paused bool
by string
pauseFile string
}

// Output sends an output record.
Expand Down Expand Up @@ -99,6 +197,93 @@ func (l *lines) ResetAbort() {
l.abort = false
}

// PauseFile follows the playbook's pause file: a pause wanted before it started made at once ;
// none once it ended, its pause forgotten.
func (l *lines) PauseFile(file string) {
l.mu.Lock()
defer l.mu.Unlock()
l.pauseFile = file
if file == "" {
l.paused = false
return
}
if l.paused {
writeWho(file, l.by)
}
}

// Paused says the playbook holds before its next task.
func (l *lines) Paused(after, next string) {
l.w.Write(map[string]any{"kind": "paused", "after": l.mask.Text(after), "next": l.mask.Text(next)})
}

// Resumed says the playbook goes on.
func (l *lines) Resumed() {
l.w.Write(map[string]any{"kind": "resumed"})
}

// Checkpoints sends a batch of checkpoints, sealed with the job's key: the controller opens them,
// nothing of them is read on the way.
func (l *lines) Checkpoints(batch []map[string]any) {
sealed, err := socket.SealWithKey(batch, l.key, l.id)
if err != nil {
logger.Error("[Job %d] Its checkpoints cannot be sealed: %v", l.id, err)
return
}
l.w.Write(map[string]any{"kind": "checkpoints", "sealed": sealed})
}

// setPaused holds the playbook before its next task, or lets it go on, as the controller's own
// Runner does: its pause file made (who asked it in it) or removed (who resumed it written beside
// it, for the line the plugin prints) ; kept until the playbook starts when it has not yet.
//
// Args:
//
// paused: true to hold it, false to let it go on.
// by: who asked the pause, or resumes it.
func (l *lines) setPaused(paused bool, by string) {
l.mu.Lock()
defer l.mu.Unlock()
was := l.paused
if paused {
if by != "" {
l.by = by
}
l.paused = true
if l.pauseFile != "" && !was {
logger.Notice("[Job %d] Pauses before its next task", l.id)
writeWho(l.pauseFile, l.by)
}
return
}
l.paused = false
if l.pauseFile != "" && was {
logger.Notice("[Job %d] Goes on", l.id)
writeWho(l.pauseFile+".resumed", by)
if err := os.Remove(l.pauseFile); err != nil {
logger.Error("[Job %d] The resume could not be set: %v", l.id, err)
}
}
}

// writeWho writes a pause file, or the file of who resumed: who, as JSON, readable by its owner
// only.
//
// Args:
//
// file: the file.
// by: who ; none for null.
func writeWho(file, by string) {
var who any
if by != "" {
who = by
}
data, _ := json.Marshal(map[string]any{"by": who})
if err := os.WriteFile(file, data, 0o600); err != nil {
logger.Error("The pause could not be set: %v", err)
}
}

// stop aborts the job: its flag set, its playbook's process group signalled when it runs.
func (l *lines) stop() {
l.mu.Lock()
Expand All @@ -124,6 +309,8 @@ func (l *lines) stop() {
func Run(stdin io.Reader, stdout io.Writer, signals <-chan os.Signal) int {
w := jobstream.NewWriter(stdout)
io := &lines{w: w, mask: &mask.Job{}}
// its pauses and resumes, as they come, from its start (Docker and Podman)
defer openControls(io)()
fail := func(order int64, err error) int {
io.End(order, "stderr", "failed", "[ERROR]: "+err.Error(), map[string]any{})
return 1
Expand All @@ -135,10 +322,19 @@ func Run(stdin io.Reader, stdout io.Writer, signals <-chan os.Signal) int {
return fail(1, err)
}
defer os.RemoveAll(work)
h, err := jobstream.ReadJob(stdin, work)
br := jobstream.NewReader(stdin)
h, err := jobstream.ReadJobFrom(br, work)
if err != nil {
return fail(h.LastOrder+1, err)
}
io.id, io.key = h.ID, h.Key
var resume *ansible.Resume
if len(h.Resume) > 0 {
resume = &ansible.Resume{}
if err := json.Unmarshal(h.Resume, resume); err != nil {
return fail(h.LastOrder+1, fmt.Errorf("the job's checkpoints cannot be read: %v", err))
}
}
var sec ansible.Secrets
if len(h.Secrets) > 0 {
if err := json.Unmarshal(h.Secrets, &sec); err != nil {
Expand All @@ -152,8 +348,18 @@ func Run(stdin io.Reader, stdout io.Writer, signals <-chan os.Signal) int {
return fail(h.LastOrder+1, err)
}
ansible.PluginsDir = pluginsDir
// and the fact cache of a playbook that records checkpoints
if len(h.Key) > 0 {
cacheDir := filepath.Join(work, ".cache_plugins")
if err := cacheWrite(cacheDir); err != nil {
return fail(h.LastOrder+1, err)
}
ansible.CachePluginsDir = cacheDir
}

// step 3 : an abort while it runs
// step 3 : an abort while it runs ; a pause or a resume, as they come after the job on its stdin
// (Kubernetes)
go jobstream.ReadControls(br, func(c jobstream.Control) { io.setPaused(c.Paused, c.By) })
done := make(chan struct{})
defer close(done)
go func() {
Expand All @@ -170,6 +376,7 @@ func Run(stdin io.Reader, stdout io.Writer, signals <-chan os.Signal) int {
roots = append(roots, ansible.Root{Repository: inv.Repository, Dir: filepath.Join(work, inv.Folder)})
}
job := ansible.Job{ID: h.ID, Extravars: h.Extravars, LastOrder: h.LastOrder, Mask: io.mask, InventoryRoots: roots,
Checkpoints: len(h.Key) > 0, Resume: resume,
PlaybookDir: func(sub string) (string, error) {
if h.Playbook == "" {
return "", fmt.Errorf("the job came without its playbooks")
Expand Down
Loading