~james/core

core/spindle/mill/lost_executor_test.go -rw-r--r-- 7.0 KiB
452f17b7 — james chore(import): snapshot james.dad.town/core at f70c71c7696a 14 hours ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
package mill

import (
	"context"
	"errors"
	"io"
	"log/slog"
	"net/http"
	"net/http/httptest"
	"path/filepath"
	"strings"
	"testing"
	"time"

	"tangled.org/core/notifier"
	"tangled.org/core/spindle/config"
	"tangled.org/core/spindle/db"
	"tangled.org/core/spindle/engine"
	"tangled.org/core/spindle/engines/dummy"
	"tangled.org/core/spindle/mill/executor"
	"tangled.org/core/spindle/models"
	"tangled.org/core/spindle/secrets"
	"tangled.org/core/workflow"
)

// the outcome is published before teardown. a held teardown keeps the lease open after it
type heldTeardownEngine struct {
	*dummy.DummyEngine
	stepErr  error
	teardown chan struct{}
}

func (e *heldTeardownEngine) RunStep(ctx context.Context, wid models.WorkflowId, w *models.Workflow, idx int, s []secrets.UnlockedSecret, wl models.WorkflowLogger) error {
	if e.stepErr != nil {
		return e.stepErr
	}
	return e.DummyEngine.RunStep(ctx, wid, w, idx, s, wl)
}

func (e *heldTeardownEngine) DestroyWorkflow(ctx context.Context, wid models.WorkflowId) error {
	<-e.teardown
	return nil
}

type lostExecutorWorld struct {
	t      *testing.T
	ctx    context.Context
	mill   *Mill
	bdb    *db.DB
	wsURL  string
	wid    models.WorkflowId
	result chan error
}

func newLostExecutorWorld(t *testing.T, grace time.Duration) *lostExecutorWorld {
	t.Helper()
	ctx, cancel := context.WithCancel(context.Background())
	t.Cleanup(cancel)
	l := slog.New(slog.NewTextHandler(io.Discard, nil))
	millDir := t.TempDir()
	bdb, err := db.Make(ctx, filepath.Join(millDir, "mill.db"))
	if err != nil {
		t.Fatalf("mill db: %v", err)
	}
	bn := notifier.New()
	m := New(l, Config{LogDir: millDir, ReconnectGrace: grace, BidTimeout: 2 * time.Second})
	m.Attach(bdb, &bn, testQuotaManager(t, bdb))
	registerTestExecutor(t, bdb, "exec-1", HashToken("test-token"), nil)
	srv := httptest.NewServer(http.HandlerFunc(m.HandleExecutorConn))
	t.Cleanup(srv.Close)
	return &lostExecutorWorld{
		t:     t,
		ctx:   ctx,
		mill:  m,
		bdb:   bdb,
		wsURL: "ws" + strings.TrimPrefix(srv.URL, "http"),
		wid:   models.WorkflowId{PipelineId: models.PipelineId("rkey1"), Name: "build"},
	}
}

func (w *lostExecutorWorld) startExecutor(dbPath string, eng models.Engine) context.CancelFunc {
	w.t.Helper()
	ctx, cancel := context.WithCancel(w.ctx)
	l := slog.New(slog.NewTextHandler(io.Discard, nil))
	edb, err := db.Make(ctx, dbPath)
	if err != nil {
		w.t.Fatalf("exec db: %v", err)
	}
	en := notifier.New()
	cfg := &config.Config{}
	cfg.Server.Dev = true
	cfg.Server.LogDir = filepath.Dir(dbPath)
	cfg.ArtifactStores.Disk.Dir = filepath.Join(filepath.Dir(dbPath), "artifacts")
	cfg.Server.Hostname = "exec-1"
	cfg.Mill.URL = w.wsURL
	cfg.Mill.Seats = 1
	cfg.Mill.SharedSecret = "test-token"
	exec, err := executor.New(cfg, map[string]models.Engine{"dummy": eng}, edb, &en, l, nil, nil)
	if err != nil {
		w.t.Fatalf("executor.New: %v", err)
	}
	go exec.Connect(ctx)
	w.waitFor("executor session", func() bool { return w.mill.sessionForNode("exec-1") != nil })
	return cancel
}

func (w *lostExecutorWorld) runUntilOutcomeThenKill(dbPath string, stepErr error) {
	w.t.Helper()
	eng := &heldTeardownEngine{DummyEngine: dummy.New(slog.New(slog.NewTextHandler(io.Discard, nil))), stepErr: stepErr, teardown: make(chan struct{})}
	kill := w.startExecutor(dbPath, eng)

	wf, err := NewEngine("dummy", w.mill).InitWorkflow(workflow.WorkflowSpec{
		Name: "build",
		Raw:  "steps:\n  - name: hello\n    command: echo hi\n",
	}, testPipeline())
	if err != nil {
		w.t.Fatalf("InitWorkflow: %v", err)
	}
	placeCtx, placeCancel := context.WithTimeout(w.ctx, 10*time.Second)
	defer placeCancel()
	slot, err := w.mill.place(placeCtx, "dummy", w.wid, wf)
	if err != nil {
		w.t.Fatalf("place: %v", err)
	}
	w.t.Cleanup(slot.Release)
	w.result = make(chan error, 1)
	go func() {
		ctx, cancel := context.WithTimeout(w.ctx, time.Minute)
		defer cancel()
		w.result <- w.mill.commitAndWait(ctx, wf, nil)
	}()

	outcome := models.StatusKindSuccess
	if stepErr != nil {
		outcome = models.StatusKindFailed
	}
	w.waitFor("recorded outcome", func() bool {
		st, err := w.bdb.GetStatus(w.wid)
		return err == nil && st == outcome
	})
	kill()
	w.waitFor("session loss", func() bool { return w.mill.sessionForNode("exec-1") == nil })
}

func (w *lostExecutorWorld) waitFor(what string, cond func() bool) {
	w.t.Helper()
	deadline := time.Now().Add(5 * time.Second)
	for time.Now().Before(deadline) {
		if cond() {
			return
		}
		time.Sleep(10 * time.Millisecond)
	}
	w.t.Fatalf("timed out waiting for %s", what)
}

func (w *lostExecutorWorld) runStepResult() error {
	w.t.Helper()
	select {
	case err := <-w.result:
		return err
	case <-time.After(5 * time.Second):
		w.t.Fatal("RunStep did not return after the lease was finished")
		return nil
	}
}

type statusRow struct {
	status string
	err    string
}

func (w *lostExecutorWorld) statusHistory() []statusRow {
	w.t.Helper()
	rows, err := w.bdb.Query(
		`select status, coalesce(error, '') from workflow_statuses where pipeline_id = ? and workflow = ? order by id`,
		string(w.wid.PipelineId), w.wid.Name,
	)
	if err != nil {
		w.t.Fatal(err)
	}
	defer rows.Close()
	var out []statusRow
	for rows.Next() {
		var r statusRow
		if err := rows.Scan(&r.status, &r.err); err != nil {
			w.t.Fatal(err)
		}
		out = append(out, r)
	}
	return out
}

func (w *lostExecutorWorld) assertSuccessKept() {
	w.t.Helper()
	if err := w.runStepResult(); err != nil {
		w.t.Fatalf("RunStep = %v, want success", err)
	}
	h := w.statusHistory()
	if last := h[len(h)-1]; last.status != string(models.StatusKindSuccess) {
		w.t.Fatalf("status history %+v, want it to end in success", h)
	}
}

func TestExecutorRestartAfterOutcomeKeepsSuccess(t *testing.T) {
	w := newLostExecutorWorld(t, time.Minute)
	dbPath := filepath.Join(t.TempDir(), "exec.db")
	w.runUntilOutcomeThenKill(dbPath, nil)
	w.startExecutor(dbPath, dummy.New(slog.New(slog.NewTextHandler(io.Discard, nil))))
	w.assertSuccessKept()
}

func TestWipedExecutorAfterOutcomeKeepsSuccess(t *testing.T) {
	w := newLostExecutorWorld(t, time.Minute)
	w.runUntilOutcomeThenKill(filepath.Join(t.TempDir(), "exec.db"), nil)
	w.startExecutor(filepath.Join(t.TempDir(), "exec.db"), dummy.New(slog.New(slog.NewTextHandler(io.Discard, nil))))
	w.assertSuccessKept()
}

func TestExecutorLostAfterOutcomeKeepsSuccess(t *testing.T) {
	w := newLostExecutorWorld(t, time.Second)
	w.runUntilOutcomeThenKill(filepath.Join(t.TempDir(), "exec.db"), nil)
	w.assertSuccessKept()
}

func TestExecutorRestartAfterFailedOutcomeKeepsItsError(t *testing.T) {
	w := newLostExecutorWorld(t, time.Minute)
	dbPath := filepath.Join(t.TempDir(), "exec.db")
	w.runUntilOutcomeThenKill(dbPath, errors.New("make: *** [test] Error 2"))
	recorded := w.statusHistory()
	w.startExecutor(dbPath, dummy.New(slog.New(slog.NewTextHandler(io.Discard, nil))))

	if err := w.runStepResult(); !errors.Is(err, engine.ErrWorkflowFailed) {
		t.Fatalf("RunStep = %v, want %v", err, engine.ErrWorkflowFailed)
	}
	h := w.statusHistory()
	last := h[len(h)-1]
	if len(h) != len(recorded) || last != recorded[len(recorded)-1] || !strings.Contains(last.err, "Error 2") {
		t.Fatalf("status history %+v, want it unchanged from %+v", h, recorded)
	}
}