~james/core

core/spindle/mill/integration_test.go -rw-r--r-- 11.0 KiB
452f17b7 — james chore(import): snapshot james.dad.town/core at f70c71c7696a 15 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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
package mill

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

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

func TestEndToEndDummyJob(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	defer 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()
	mill := New(l, Config{LogDir: millDir, ReconnectGrace: time.Minute, BidTimeout: 2 * time.Second})
	mill.Attach(bdb, &bn, testQuotaManager(t, bdb))
	millMetrics := observability.NewMetrics()
	mill.RegisterMetrics(millMetrics)
	registerTestExecutor(t, bdb, "exec-1", HashToken("test-token"), nil)

	srv := httptest.NewServer(http.HandlerFunc(mill.HandleExecutorConn))
	defer srv.Close()
	wsURL := "ws" + strings.TrimPrefix(srv.URL, "http")

	execDir := t.TempDir()
	edb, err := db.Make(ctx, filepath.Join(execDir, "exec.db"))
	if err != nil {
		t.Fatalf("exec db: %v", err)
	}
	en := notifier.New()
	cfg := &config.Config{}
	cfg.Server.LogDir = execDir
	cfg.ArtifactStores.Disk.Dir = filepath.Join(execDir, "artifacts")
	cfg.Server.Hostname = "exec-1"
	cfg.Mill.URL = wsURL
	cfg.Mill.Seats = 2
	cfg.Mill.SharedSecret = "test-token"

	dummyEng := dummy.New(l)
	dummyEng.StepDelay = 50 * time.Millisecond
	engines := map[string]models.Engine{"dummy": dummyEng}
	exec, err := executor.New(cfg, engines, edb, &en, l, nil, nil)
	if err != nil {
		t.Fatalf("executor.New: %v", err)
	}
	execMetrics := observability.NewMetrics()
	exec.RegisterMetrics(execMetrics)
	go exec.Connect(observability.WithMetrics(ctx, execMetrics))

	be := NewEngine("dummy", mill)
	twf := workflow.WorkflowSpec{
		Name: "build",
		Raw:  "steps:\n  - name: hello\n    command: echo hi\n",
	}
	wf, err := be.InitWorkflow(twf, testPipeline())
	if err != nil {
		t.Fatalf("InitWorkflow: %v", err)
	}
	wid := models.WorkflowId{PipelineId: models.PipelineId("rkey1"), Name: "build"}
	if err := bdb.StatusPending(wid, &bn); err != nil {
		t.Fatal(err)
	}

	placeCtx, placeCancel := context.WithTimeout(ctx, 10*time.Second)
	defer placeCancel()

	slot, err := mill.place(placeCtx, "dummy", wid, wf)
	if err != nil {
		t.Fatalf("place: %v", err)
	}
	defer slot.Release()

	logPath := models.LogFilePath(millDir, wid)
	ch := bn.Subscribe()
	defer bn.Unsubscribe(ch)

	sawLogContent := make(chan bool, 1)
	go func() {
		ticker := time.NewTicker(20 * time.Millisecond)
		defer ticker.Stop()
		timeout := time.After(10 * time.Second)
		for {
			select {
			case <-ch:
			case <-ticker.C:
			case <-timeout:
				sawLogContent <- false
				return
			}
			data, err := os.ReadFile(logPath)
			if err == nil && strings.Contains(string(data), "echo hi") {
				sawLogContent <- true
				return
			}
		}
	}()

	if err := mill.commitAndWait(placeCtx, wf, nil); err != nil {
		t.Fatalf("commitAndWait: %v, want success", err)
	}

	if !<-sawLogContent {
		t.Fatal("mill live log file never received expected content while job was running")
	}

	if !waitForFileRemoval(t, logPath) {
		t.Fatalf("mill live log file was not removed after terminal artifact was recorded")
	}

	archived, err := bdb.GetFinishedLog(wid)
	if err != nil {
		t.Fatalf("GetFinishedLog: %v", err)
	}
	if archived.Workflow != wid.Name || archived.Ref == "" {
		t.Fatalf("archived log = %+v, want artifact for %s", archived, wid)
	}

	if !waitForStatus(t, bdb, wid, "running") {
		events, _ := bdb.GetEvents(0, 1000)
		t.Logf("mill events after completion: %+v", events)
		t.Fatal("mill never saw streamed running status")
	}

	millFamilies, err := millMetrics.Registry().Gather()
	if err != nil {
		t.Fatal(err)
	}
	var millTotal, millClassified, millStartupSamples float64
	for _, family := range millFamilies {
		switch family.GetName() {
		case "spindle_workflows_total":
			for _, metric := range family.GetMetric() {
				millTotal += metric.GetCounter().GetValue()
			}
		case "spindle_workflow_terminations_total":
			for _, metric := range family.GetMetric() {
				millClassified += metric.GetCounter().GetValue()
			}
		case "spindle_workflow_startup_delay_seconds":
			for _, metric := range family.GetMetric() {
				millStartupSamples += float64(metric.GetHistogram().GetSampleCount())
			}
		}
	}
	if millTotal != 1 || millClassified != 1 || millStartupSamples != 1 {
		t.Fatalf(
			"mill metrics = total %v classified %v startup samples %v, want exactly one of each",
			millTotal, millClassified, millStartupSamples,
		)
	}

	executorFamilies, err := execMetrics.Registry().Gather()
	if err != nil {
		t.Fatal(err)
	}
	var executorTotal, executorDurations float64
	for _, family := range executorFamilies {
		switch family.GetName() {
		case "spindle_workflows_total":
			for _, metric := range family.GetMetric() {
				executorTotal += metric.GetCounter().GetValue()
			}
		case "spindle_workflow_duration_seconds":
			for _, metric := range family.GetMetric() {
				executorDurations += float64(metric.GetHistogram().GetSampleCount())
			}
		}
	}
	if executorTotal != 0 || executorDurations != 1 {
		t.Fatalf("executor metrics = terminal %v duration samples %v, want 0 and 1", executorTotal, executorDurations)
	}
}

func TestExecutorConfiguredLabelsAreStoredOnSession(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	defer 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()
	mill := New(l, Config{LogDir: millDir, ReconnectGrace: time.Minute, BidTimeout: 2 * time.Second})
	mill.Attach(bdb, &bn, testQuotaManager(t, bdb))
	registerTestExecutor(t, bdb, "exec-labels", HashToken("test-token"), []string{"linux", "arm64", "gpu"})

	srv := httptest.NewServer(http.HandlerFunc(mill.HandleExecutorConn))
	defer srv.Close()
	wsURL := "ws" + strings.TrimPrefix(srv.URL, "http")

	execDir := t.TempDir()
	edb, err := db.Make(ctx, filepath.Join(execDir, "exec.db"))
	if err != nil {
		t.Fatalf("exec db: %v", err)
	}
	en := notifier.New()
	cfg := &config.Config{}
	cfg.Server.Dev = true
	cfg.Server.LogDir = execDir
	cfg.ArtifactStores.Disk.Dir = filepath.Join(execDir, "artifacts")
	cfg.Server.Hostname = "exec-labels"
	cfg.Mill.URL = wsURL
	cfg.Mill.Seats = 2
	cfg.Mill.SharedSecret = "test-token"
	cfg.Mill.Labels = []string{"linux", "arm64", "gpu"}

	engines := map[string]models.Engine{"dummy": dummy.New(l)}
	exec, err := executor.New(cfg, engines, edb, &en, l, nil, nil)
	if err != nil {
		t.Fatalf("executor.New: %v", err)
	}
	go exec.Connect(ctx)

	if !waitForSessionLabels(t, mill, "exec-labels", []string{"linux", "arm64", "gpu"}) {
		t.Fatal("mill session never stored executor labels from hello")
	}
}

func TestEndToEndDummyJobUsesRequiredLabelsAcrossExecutors(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	defer 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()
	mill := New(l, Config{LogDir: millDir, ReconnectGrace: time.Minute, BidTimeout: 2 * time.Second})
	mill.Attach(bdb, &bn, testQuotaManager(t, bdb))
	registerTestExecutor(t, bdb, "exec-x86", HashToken("token-x86"), []string{"linux/amd64", "kvm"})
	registerTestExecutor(t, bdb, "exec-arm", HashToken("token-arm"), []string{"linux/arm64", "kvm"})

	srv := httptest.NewServer(http.HandlerFunc(mill.HandleExecutorConn))
	defer srv.Close()
	wsURL := "ws" + strings.TrimPrefix(srv.URL, "http")

	startExecutor := func(name, token string, labels []string) {
		t.Helper()
		execDir := t.TempDir()
		edb, err := db.Make(ctx, filepath.Join(execDir, "exec.db"))
		if err != nil {
			t.Fatalf("%s exec db: %v", name, err)
		}
		en := notifier.New()
		cfg := &config.Config{}
		cfg.Server.Dev = true
		cfg.Server.LogDir = execDir
		cfg.ArtifactStores.Disk.Dir = filepath.Join(execDir, "artifacts")
		cfg.Server.Hostname = name
		cfg.Mill.URL = wsURL
		cfg.Mill.Seats = 1
		cfg.Mill.SharedSecret = token
		cfg.Mill.Labels = labels

		engines := map[string]models.Engine{"dummy": dummy.New(l)}
		exec, err := executor.New(cfg, engines, edb, &en, l, nil, nil)
		if err != nil {
			t.Fatalf("executor.New: %v", err)
		}
		go exec.Connect(ctx)
	}
	startExecutor("exec-x86", "token-x86", []string{"linux/amd64", "kvm"})
	startExecutor("exec-arm", "token-arm", []string{"linux/arm64", "kvm"})

	if !waitForSessionLabels(t, mill, "exec-x86", []string{"linux/amd64", "kvm"}) {
		t.Fatal("x86 executor did not connect with labels")
	}
	if !waitForSessionLabels(t, mill, "exec-arm", []string{"linux/arm64", "kvm"}) {
		t.Fatal("arm executor did not connect with labels")
	}

	be := NewEngine("dummy", mill)
	twf := workflow.WorkflowSpec{
		Name:   "build-arm",
		RunsOn: []string{"linux/arm64"},
		Raw:    "steps:\n  - name: hello\n    command: echo hi\n",
	}
	wf, err := be.InitWorkflow(twf, testPipeline())
	if err != nil {
		t.Fatalf("InitWorkflow: %v", err)
	}
	wid := models.WorkflowId{PipelineId: models.PipelineId("rkey-arm"), Name: "build-arm"}

	placeCtx, placeCancel := context.WithTimeout(ctx, 10*time.Second)
	defer placeCancel()

	slot, err := mill.place(placeCtx, "dummy", wid, wf)
	if err != nil {
		t.Fatalf("place: %v", err)
	}
	defer slot.Release()

	lease := wf.Data.(*millWorkflowState).Lease
	if lease == nil {
		t.Fatal("place did not attach lease to workflow state")
	}
	if lease.nodeID != "exec-arm" {
		t.Fatalf("placed on %q, want exec-arm", lease.nodeID)
	}

	if err := mill.commitAndWait(placeCtx, wf, nil); err != nil {
		t.Fatalf("commitAndWait: %v, want success", err)
	}
}

func waitForSessionLabels(t *testing.T, m *Mill, nodeID string, want []string) bool {
	t.Helper()
	deadline := time.Now().Add(3 * time.Second)
	for time.Now().Before(deadline) {
		m.mu.Lock()
		sess := m.sessions[nodeID]
		var got []string
		if sess != nil {
			got = append([]string(nil), sess.labels...)
		}
		m.mu.Unlock()
		if sameStringMultiset(got, want) {
			return true
		}
		time.Sleep(10 * time.Millisecond)
	}
	return false
}

func waitForStatus(t *testing.T, d *db.DB, wid models.WorkflowId, want string) bool {
	t.Helper()
	deadline := time.Now().Add(3 * time.Second)
	for time.Now().Before(deadline) {
		evs, err := d.GetEvents(0, 1000)
		if err != nil {
			t.Fatalf("GetEvents: %v", err)
		}
		for _, ev := range evs {
			if ev.Pipeline == string(wid.PipelineId) && ev.Workflow == wid.Name && ev.Status == want {
				return true
			}
		}
		time.Sleep(50 * time.Millisecond)
	}
	return false
}

func waitForFileRemoval(t *testing.T, path string) bool {
	t.Helper()
	deadline := time.Now().Add(5 * time.Second)
	for time.Now().Before(deadline) {
		_, err := os.Stat(path)
		if os.IsNotExist(err) {
			return true
		}
		time.Sleep(20 * time.Millisecond)
	}
	return false
}