Repository navigation
Expand file tree
/
Copy pathagentscripts_test.go
More file actions
722 lines (635 loc) · 22.8 KB
/
Copy pathagentscripts_test.go
File metadata and controls
722 lines (635 loc) · 22.8 KB
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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
package agentscripts_test
import (
"context"
"path/filepath"
"runtime"
"sync"
"testing"
"time"
"github.com/google/uuid"
"github.com/prometheus/client_golang/prometheus"
"github.com/spf13/afero"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.uber.org/goleak"
"github.com/coder/coder/v2/agent/agentexec"
"github.com/coder/coder/v2/agent/agentscripts"
"github.com/coder/coder/v2/agent/agentssh"
"github.com/coder/coder/v2/agent/agenttest"
"github.com/coder/coder/v2/agent/proto"
"github.com/coder/coder/v2/codersdk"
"github.com/coder/coder/v2/codersdk/agentsdk"
"github.com/coder/coder/v2/testutil"
)
func TestMain(m *testing.M) {
goleak.VerifyTestMain(m, testutil.GoleakOptions...)
}
func TestExecuteBasic(t *testing.T) {
t.Parallel()
ctx := testutil.Context(t, testutil.WaitShort)
fLogger := newFakeScriptLogger()
runner := setup(t, func(uuid2 uuid.UUID) agentscripts.ScriptLogger {
return fLogger
})
defer runner.Close()
aAPI := agenttest.NewFakeAgentAPI(t, testutil.Logger(t), nil, nil)
err := runner.Init([]codersdk.WorkspaceAgentScript{{
LogSourceID: uuid.New(),
Script: "echo hello",
}}, aAPI.ScriptCompleted)
require.NoError(t, err)
require.NoError(t, runner.Execute(context.Background(), agentscripts.ExecuteAllScripts))
log := testutil.TryReceive(ctx, t, fLogger.logs)
require.Equal(t, "hello", log.Output)
}
func TestExecuteCreatesMissingLogDir(t *testing.T) {
t.Parallel()
ctx := testutil.Context(t, testutil.WaitShort)
fs := afero.NewOsFs()
logger := testutil.Logger(t)
s, err := agentssh.NewServer(context.Background(), logger, prometheus.NewRegistry(), fs, agentexec.DefaultExecer, nil)
require.NoError(t, err)
t.Cleanup(func() {
_ = s.Close()
})
fLogger := newFakeScriptLogger()
runner := agentscripts.New(agentscripts.Options{
LogDir: t.TempDir(),
DataDirBase: t.TempDir(),
Logger: logger,
SSHServer: s,
Filesystem: fs,
GetScriptLogger: func(uuid.UUID) agentscripts.ScriptLogger {
return fLogger
},
})
defer runner.Close()
logPath := filepath.Join(t.TempDir(), "does", "not", "exist", "install.log")
aAPI := agenttest.NewFakeAgentAPI(t, logger, nil, nil)
err = runner.Init([]codersdk.WorkspaceAgentScript{{
LogSourceID: uuid.New(),
LogPath: logPath,
Script: "echo hello",
}}, aAPI.ScriptCompleted)
require.NoError(t, err)
require.NoError(t, runner.Execute(ctx, agentscripts.ExecuteAllScripts))
log := testutil.TryReceive(ctx, t, fLogger.logs)
require.Equal(t, "hello", log.Output)
exists, err := afero.Exists(fs, logPath)
require.NoError(t, err)
require.True(t, exists, "expected log file to be created at %s", logPath)
}
func TestEnv(t *testing.T) {
t.Parallel()
fLogger := newFakeScriptLogger()
runner := setup(t, func(uuid2 uuid.UUID) agentscripts.ScriptLogger {
return fLogger
})
defer runner.Close()
id := uuid.New()
script := "echo $CODER_SCRIPT_DATA_DIR\necho $CODER_SCRIPT_BIN_DIR\n"
if runtime.GOOS == "windows" {
script = `
cmd.exe /c echo %CODER_SCRIPT_DATA_DIR%
cmd.exe /c echo %CODER_SCRIPT_BIN_DIR%
`
}
aAPI := agenttest.NewFakeAgentAPI(t, testutil.Logger(t), nil, nil)
err := runner.Init([]codersdk.WorkspaceAgentScript{{
LogSourceID: id,
Script: script,
}}, aAPI.ScriptCompleted)
require.NoError(t, err)
ctx := testutil.Context(t, testutil.WaitLong)
done := testutil.Go(t, func() {
err := runner.Execute(ctx, agentscripts.ExecuteAllScripts)
assert.NoError(t, err)
})
defer func() {
select {
case <-ctx.Done():
case <-done:
}
}()
var log []agentsdk.Log
for {
select {
case <-ctx.Done():
require.Fail(t, "timed out waiting for logs")
case l := <-fLogger.logs:
t.Logf("log: %s", l.Output)
log = append(log, l)
}
if len(log) >= 2 {
break
}
}
require.Contains(t, log[0].Output, filepath.Join(runner.DataDir(), id.String()))
require.Contains(t, log[1].Output, runner.ScriptBinDir())
}
func TestTimeout(t *testing.T) {
t.Parallel()
if runtime.GOOS == "darwin" {
t.Skip("this test is flaky on macOS, see https://github.com/coder/internal/issues/329")
}
runner := setup(t, nil)
defer runner.Close()
aAPI := agenttest.NewFakeAgentAPI(t, testutil.Logger(t), nil, nil)
err := runner.Init([]codersdk.WorkspaceAgentScript{{
LogSourceID: uuid.New(),
Script: "sleep infinity",
Timeout: 100 * time.Millisecond,
}}, aAPI.ScriptCompleted)
require.NoError(t, err)
require.ErrorIs(t, runner.Execute(context.Background(), agentscripts.ExecuteAllScripts), agentscripts.ErrTimeout)
}
func TestScriptReportsTiming(t *testing.T) {
t.Parallel()
ctx := testutil.Context(t, testutil.WaitShort)
fLogger := newFakeScriptLogger()
runner := setup(t, func(uuid2 uuid.UUID) agentscripts.ScriptLogger {
return fLogger
})
aAPI := agenttest.NewFakeAgentAPI(t, testutil.Logger(t), nil, nil)
err := runner.Init([]codersdk.WorkspaceAgentScript{{
DisplayName: "say-hello",
LogSourceID: uuid.New(),
Script: "echo hello",
}}, aAPI.ScriptCompleted)
require.NoError(t, err)
require.NoError(t, runner.Execute(ctx, agentscripts.ExecuteAllScripts))
runner.Close()
log := testutil.TryReceive(ctx, t, fLogger.logs)
require.Equal(t, "hello", log.Output)
timings := aAPI.GetTimings()
require.Equal(t, 1, len(timings))
timing := timings[0]
require.Equal(t, int32(0), timing.ExitCode)
if assert.True(t, timing.Start.IsValid(), "start time should be valid") {
require.NotZero(t, timing.Start.AsTime(), "start time should not be zero")
}
if assert.True(t, timing.End.IsValid(), "end time should be valid") {
require.NotZero(t, timing.End.AsTime(), "end time should not be zero")
}
require.GreaterOrEqual(t, timing.End.AsTime(), timing.Start.AsTime())
}
// TestCronClose exists because cron.Run() can happen after cron.Close().
// If this happens, there used to be a deadlock.
func TestCronClose(t *testing.T) {
t.Parallel()
runner := agentscripts.New(agentscripts.Options{})
runner.StartCron()
require.NoError(t, runner.Close(), "close runner")
}
func TestExecuteOptions(t *testing.T) {
t.Parallel()
startScript := codersdk.WorkspaceAgentScript{
ID: uuid.New(),
LogSourceID: uuid.New(),
Script: "echo start",
RunOnStart: true,
}
stopScript := codersdk.WorkspaceAgentScript{
ID: uuid.New(),
LogSourceID: uuid.New(),
Script: "echo stop",
RunOnStop: true,
}
regularScript := codersdk.WorkspaceAgentScript{
ID: uuid.New(),
LogSourceID: uuid.New(),
Script: "echo regular",
}
scripts := []codersdk.WorkspaceAgentScript{
startScript,
stopScript,
regularScript,
}
scriptByID := func(t *testing.T, id uuid.UUID) codersdk.WorkspaceAgentScript {
for _, script := range scripts {
if script.ID == id {
return script
}
}
t.Fatal("script not found")
return codersdk.WorkspaceAgentScript{}
}
wantOutput := map[uuid.UUID]string{
startScript.ID: "start",
stopScript.ID: "stop",
regularScript.ID: "regular",
}
testCases := []struct {
name string
option agentscripts.ExecuteOption
wantRun []uuid.UUID
}{
{
name: "ExecuteAllScripts",
option: agentscripts.ExecuteAllScripts,
wantRun: []uuid.UUID{startScript.ID, stopScript.ID, regularScript.ID},
},
{
name: "ExecuteStartScripts",
option: agentscripts.ExecuteStartScripts,
wantRun: []uuid.UUID{startScript.ID},
},
{
name: "ExecuteStopScripts",
option: agentscripts.ExecuteStopScripts,
wantRun: []uuid.UUID{stopScript.ID},
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
ctx := testutil.Context(t, testutil.WaitMedium)
executedScripts := make(map[uuid.UUID]bool)
fLogger := &executeOptionTestLogger{
tb: t,
executedScripts: executedScripts,
wantOutput: wantOutput,
}
runner := setup(t, func(uuid.UUID) agentscripts.ScriptLogger {
return fLogger
})
defer runner.Close()
aAPI := agenttest.NewFakeAgentAPI(t, testutil.Logger(t), nil, nil)
err := runner.Init(
scripts,
aAPI.ScriptCompleted,
)
require.NoError(t, err)
err = runner.Execute(ctx, tc.option)
require.NoError(t, err)
gotRun := map[uuid.UUID]bool{}
for _, id := range tc.wantRun {
gotRun[id] = true
require.True(t, executedScripts[id],
"script %s should have run when using filter %s", scriptByID(t, id).Script, tc.name)
}
for _, script := range scripts {
if _, ok := gotRun[script.ID]; ok {
continue
}
require.False(t, executedScripts[script.ID],
"script %s should not have run when using filter %s", script.Script, tc.name)
}
})
}
}
type executeOptionTestLogger struct {
tb testing.TB
executedScripts map[uuid.UUID]bool
wantOutput map[uuid.UUID]string
mu sync.Mutex
}
func (l *executeOptionTestLogger) Send(_ context.Context, logs ...agentsdk.Log) error {
l.mu.Lock()
defer l.mu.Unlock()
for _, log := range logs {
l.tb.Log(log.Output)
for id, output := range l.wantOutput {
if log.Output == output {
l.executedScripts[id] = true
break
}
}
}
return nil
}
func (*executeOptionTestLogger) Flush(context.Context) error {
return nil
}
func TestExecuteFastPath(t *testing.T) {
t.Parallel()
t.Run("AddressesWithoutDependencies", func(t *testing.T) {
t.Parallel()
ctx := testutil.Context(t, testutil.WaitShort)
logs := newRecordingScriptLogs()
runner := setup(t, logs.logger)
defer runner.Close()
aAPI := agenttest.NewFakeAgentAPI(t, testutil.Logger(t), nil, nil)
scripts := []codersdk.WorkspaceAgentScript{
{ID: uuid.New(), LogSourceID: uuid.New(), ResourceAddress: "coder_script.a", Script: "echo a", RunOnStart: true},
{ID: uuid.New(), LogSourceID: uuid.New(), ResourceAddress: "coder_script.b", Script: "echo b", RunOnStart: true},
}
require.NoError(t, runner.Init(scripts, aAPI.ScriptCompleted))
require.NoError(t, runner.Execute(ctx, agentscripts.ExecuteStartScripts))
require.Equal(t, []string{"a"}, logs.outputs(scripts[0].LogSourceID))
require.Equal(t, []string{"b"}, logs.outputs(scripts[1].LogSourceID))
})
t.Run("DependencyOnlyAtStop", func(t *testing.T) {
t.Parallel()
ctx := testutil.Context(t, testutil.WaitShort)
logs := newRecordingScriptLogs()
runner := setup(t, logs.logger)
defer runner.Close()
aAPI := agenttest.NewFakeAgentAPI(t, testutil.Logger(t), nil, nil)
// "exit 1" alone runs the same under sh and PowerShell.
save := codersdk.WorkspaceAgentScript{
ID: uuid.New(), LogSourceID: uuid.New(), DisplayName: "Save state",
ResourceAddress: "coder_script.save_state", Script: "exit 1",
RunOnStart: true, RunOnStop: true,
}
stopDB := codersdk.WorkspaceAgentScript{
ID: uuid.New(), LogSourceID: uuid.New(), DisplayName: "Stop database",
ResourceAddress: "coder_script.stop_db", Script: "echo stopping", RunOnStop: true,
Dependencies: []codersdk.WorkspaceAgentScriptDependency{{
PrerequisiteResourceAddress: "coder_script.save_state",
Requirement: codersdk.WorkspaceAgentScriptDependencyRequirementSuccess,
}},
}
require.NoError(t, runner.Init([]codersdk.WorkspaceAgentScript{save, stopDB}, aAPI.ScriptCompleted))
require.Error(t, runner.Execute(ctx, agentscripts.ExecuteStartScripts))
require.Empty(t, logs.outputs(stopDB.LogSourceID))
require.Error(t, runner.Execute(ctx, agentscripts.ExecuteStopScripts))
require.Equal(t, []string{`Skipping script: dependency "Save state" failed.`}, logs.outputs(stopDB.LogSourceID))
})
}
func TestExecuteOrderedTimeoutStartsAfterWaiting(t *testing.T) {
t.Parallel()
if runtime.GOOS == "windows" {
t.Skip("uses sleep")
}
ctx := testutil.Context(t, testutil.WaitShort)
logs := newRecordingScriptLogs()
runner := setup(t, logs.logger)
defer runner.Close()
aAPI := agenttest.NewFakeAgentAPI(t, testutil.Logger(t), nil, nil)
clone := codersdk.WorkspaceAgentScript{
ID: uuid.New(), LogSourceID: uuid.New(), ResourceAddress: "coder_script.clone",
Script: "sleep 2", RunOnStart: true,
}
install := codersdk.WorkspaceAgentScript{
ID: uuid.New(), LogSourceID: uuid.New(), ResourceAddress: "coder_script.install",
Script: "echo installed", RunOnStart: true, Timeout: time.Second,
Dependencies: []codersdk.WorkspaceAgentScriptDependency{{
PrerequisiteResourceAddress: "coder_script.clone",
Requirement: codersdk.WorkspaceAgentScriptDependencyRequirementSuccess,
}},
}
require.NoError(t, runner.Init([]codersdk.WorkspaceAgentScript{clone, install}, aAPI.ScriptCompleted))
require.NoError(t, runner.Execute(ctx, agentscripts.ExecuteStartScripts))
require.Equal(t, []string{"installed"}, logs.outputs(install.LogSourceID))
}
func TestExecuteCanceledScriptReportsCanceled(t *testing.T) {
t.Parallel()
if runtime.GOOS == "windows" {
t.Skip("uses sleep")
}
for _, test := range []struct {
name string
option agentscripts.ExecuteOption
wantStatus proto.Timing_Status
wantStage proto.Timing_Stage
}{
{name: "Start", option: agentscripts.ExecuteStartScripts, wantStatus: proto.Timing_CANCELED, wantStage: proto.Timing_START},
{name: "Stop", option: agentscripts.ExecuteStopScripts, wantStatus: proto.Timing_EXIT_FAILURE, wantStage: proto.Timing_STOP},
} {
t.Run(test.name, func(t *testing.T) {
t.Parallel()
ctx := testutil.Context(t, testutil.WaitShort)
execCtx, cancel := context.WithCancel(ctx)
defer cancel()
fLogger := newFakeScriptLogger()
runner := setup(t, func(uuid.UUID) agentscripts.ScriptLogger { return fLogger })
aAPI := agenttest.NewFakeAgentAPI(t, testutil.Logger(t), nil, nil)
// exec keeps the shell from forking sleep. A SIGHUP that lands
// in that fork window can miss the child, which then holds the
// output pipes open for cmd.WaitDelay and the test times out.
script := codersdk.WorkspaceAgentScript{
ID: uuid.New(), LogSourceID: uuid.New(),
Script: "echo started && exec sleep 30", RunOnStart: true, RunOnStop: true,
}
require.NoError(t, runner.Init([]codersdk.WorkspaceAgentScript{script}, aAPI.ScriptCompleted))
done := make(chan error, 1)
go func() { done <- runner.Execute(execCtx, test.option) }()
require.Equal(t, "started", testutil.RequireReceive(ctx, t, fLogger.logs).Output)
cancel()
require.ErrorIs(t, testutil.RequireReceive(ctx, t, done), context.Canceled)
require.NoError(t, runner.Close())
timings := aAPI.GetTimings()
require.Len(t, timings, 1)
require.Equal(t, test.wantStatus, timings[0].Status)
require.Equal(t, test.wantStage, timings[0].Stage)
require.True(t, timings[0].End.AsTime().After(timings[0].Start.AsTime()), "the real interval is kept")
})
}
t.Run("ExitedBeforeCancel", func(t *testing.T) {
t.Parallel()
ctx := testutil.Context(t, testutil.WaitShort)
execCtx, cancel := context.WithCancel(ctx)
defer cancel()
runner := setup(t, nil)
aAPI := agenttest.NewFakeAgentAPI(t, testutil.Logger(t), nil, nil)
script := codersdk.WorkspaceAgentScript{ID: uuid.New(), LogSourceID: uuid.New(), Script: "exit 1", RunOnStart: true}
require.NoError(t, runner.Init([]codersdk.WorkspaceAgentScript{script}, aAPI.ScriptCompleted))
require.Error(t, runner.Execute(execCtx, agentscripts.ExecuteStartScripts))
cancel()
require.NoError(t, runner.Close())
timings := aAPI.GetTimings()
require.Len(t, timings, 1)
require.Equal(t, proto.Timing_EXIT_FAILURE, timings[0].Status)
require.Equal(t, int32(1), timings[0].ExitCode)
})
}
// TestCloseWaitsForCanceledStartReports follows the agent's shutdown order:
// cancel the start execution and call Close at once, without waiting for
// Execute to return.
func TestCloseWaitsForCanceledStartReports(t *testing.T) {
t.Parallel()
if runtime.GOOS == "windows" {
t.Skip("uses sleep")
}
t.Run("Unordered", func(t *testing.T) {
t.Parallel()
ctx := testutil.Context(t, testutil.WaitShort)
execCtx, cancel := context.WithCancel(ctx)
defer cancel()
fLogger := newFakeScriptLogger()
runner := setup(t, func(uuid.UUID) agentscripts.ScriptLogger { return fLogger })
aAPI := agenttest.NewFakeAgentAPI(t, testutil.Logger(t), nil, nil)
script := codersdk.WorkspaceAgentScript{
ID: uuid.New(), LogSourceID: uuid.New(),
Script: "echo started && exec sleep 30", RunOnStart: true,
}
require.NoError(t, runner.Init([]codersdk.WorkspaceAgentScript{script}, aAPI.ScriptCompleted))
done := make(chan error, 1)
go func() { done <- runner.Execute(execCtx, agentscripts.ExecuteStartScripts) }()
require.Equal(t, "started", testutil.RequireReceive(ctx, t, fLogger.logs).Output)
cancel()
require.NoError(t, runner.Close())
require.ErrorIs(t, testutil.RequireReceive(ctx, t, done), context.Canceled)
timings := aAPI.GetTimings()
require.Len(t, timings, 1)
require.Equal(t, proto.Timing_CANCELED, timings[0].Status)
require.Equal(t, proto.Timing_START, timings[0].Stage)
require.ErrorContains(t, runner.Execute(ctx, agentscripts.ExecuteStartScripts), "execute: closed")
})
t.Run("Ordered", func(t *testing.T) {
t.Parallel()
ctx := testutil.Context(t, testutil.WaitShort)
execCtx, cancel := context.WithCancel(ctx)
defer cancel()
fLogger := newFakeScriptLogger()
running := codersdk.WorkspaceAgentScript{
ID: uuid.New(), LogSourceID: uuid.New(), ResourceAddress: "coder_script.running",
Script: "echo started && exec sleep 30", RunOnStart: true,
}
waiting := codersdk.WorkspaceAgentScript{
ID: uuid.New(), LogSourceID: uuid.New(), ResourceAddress: "coder_script.waiting",
Script: "echo never", RunOnStart: true,
Dependencies: []codersdk.WorkspaceAgentScriptDependency{{
PrerequisiteResourceAddress: running.ResourceAddress,
Requirement: codersdk.WorkspaceAgentScriptDependencyRequirementCompletion,
}},
}
// Only the running script's output goes to the channel the test
// reads, so the waiting line does not block Execute.
runner := setup(t, func(logSourceID uuid.UUID) agentscripts.ScriptLogger {
if logSourceID == running.LogSourceID {
return fLogger
}
return noopScriptLogger{}
})
aAPI := agenttest.NewFakeAgentAPI(t, testutil.Logger(t), nil, nil)
require.NoError(t, runner.Init([]codersdk.WorkspaceAgentScript{running, waiting}, aAPI.ScriptCompleted))
done := make(chan error, 1)
go func() { done <- runner.Execute(execCtx, agentscripts.ExecuteStartScripts) }()
require.Equal(t, "started", testutil.RequireReceive(ctx, t, fLogger.logs).Output)
cancel()
require.NoError(t, runner.Close())
require.ErrorIs(t, testutil.RequireReceive(ctx, t, done), context.Canceled)
timings := aAPI.GetTimings()
require.Len(t, timings, 2)
byScript := make(map[uuid.UUID]*proto.Timing, len(timings))
for _, timing := range timings {
byScript[uuid.UUID(timing.ScriptId)] = timing
}
require.Equal(t, proto.Timing_CANCELED, byScript[running.ID].Status)
require.True(t, byScript[running.ID].End.AsTime().After(byScript[running.ID].Start.AsTime()), "the running script keeps its real interval")
require.Equal(t, proto.Timing_CANCELED, byScript[waiting.ID].Status)
require.Equal(t, byScript[waiting.ID].Start.AsTime(), byScript[waiting.ID].End.AsTime(), "the waiting script never ran")
})
}
// The agent calls Execute and then StartCron from one goroutine while Close
// runs on another, so StartCron can land after Close has started waiting
// for Execute. Close must still return.
func TestStartCronDuringCloseDoesNotBlockClose(t *testing.T) {
t.Parallel()
if runtime.GOOS == "windows" {
t.Skip("uses sleep")
}
ctx := testutil.Context(t, testutil.WaitShort)
execCtx, cancel := context.WithCancel(ctx)
defer cancel()
fLogger := newFakeScriptLogger()
runner := setup(t, func(uuid.UUID) agentscripts.ScriptLogger { return fLogger })
aAPI := agenttest.NewFakeAgentAPI(t, testutil.Logger(t), nil, nil)
script := codersdk.WorkspaceAgentScript{
ID: uuid.New(), LogSourceID: uuid.New(),
Script: "echo started && exec sleep 30", RunOnStart: true,
}
require.NoError(t, runner.Init([]codersdk.WorkspaceAgentScript{script}, aAPI.ScriptCompleted))
done := make(chan error, 1)
go func() {
err := runner.Execute(execCtx, agentscripts.ExecuteStartScripts)
runner.StartCron()
done <- err
}()
require.Equal(t, "started", testutil.RequireReceive(ctx, t, fLogger.logs).Output)
closed := make(chan error, 1)
go func() { closed <- runner.Close() }()
// There are no stop scripts, so this probe runs nothing. It fails only
// once Close has begun and is waiting for the start script.
require.Eventually(t, func() bool {
return runner.Execute(ctx, agentscripts.ExecuteStopScripts) != nil
}, testutil.WaitShort, testutil.IntervalFast)
cancel()
require.ErrorIs(t, testutil.RequireReceive(ctx, t, done), context.Canceled)
require.NoError(t, testutil.RequireReceive(ctx, t, closed))
}
// recordingScriptLogs keeps every line per log source so a test can read a
// script's output and its dependency lines together.
type recordingScriptLogs struct {
mu sync.Mutex
byID map[uuid.UUID][]string
}
func newRecordingScriptLogs() *recordingScriptLogs {
return &recordingScriptLogs{byID: make(map[uuid.UUID][]string)}
}
func (l *recordingScriptLogs) logger(logSourceID uuid.UUID) agentscripts.ScriptLogger {
return recordingScriptLogger{logs: l, logSourceID: logSourceID}
}
func (l *recordingScriptLogs) outputs(logSourceID uuid.UUID) []string {
l.mu.Lock()
defer l.mu.Unlock()
return append([]string(nil), l.byID[logSourceID]...)
}
type recordingScriptLogger struct {
logs *recordingScriptLogs
logSourceID uuid.UUID
}
func (l recordingScriptLogger) Send(_ context.Context, logs ...agentsdk.Log) error {
l.logs.mu.Lock()
defer l.logs.mu.Unlock()
for _, log := range logs {
l.logs.byID[l.logSourceID] = append(l.logs.byID[l.logSourceID], log.Output)
}
return nil
}
func (recordingScriptLogger) Flush(context.Context) error {
return nil
}
func setup(t *testing.T, getScriptLogger func(logSourceID uuid.UUID) agentscripts.ScriptLogger) *agentscripts.Runner {
t.Helper()
if getScriptLogger == nil {
// noop
getScriptLogger = func(uuid.UUID) agentscripts.ScriptLogger {
return noopScriptLogger{}
}
}
fs := afero.NewMemMapFs()
logger := testutil.Logger(t)
s, err := agentssh.NewServer(context.Background(), logger, prometheus.NewRegistry(), fs, agentexec.DefaultExecer, nil)
require.NoError(t, err)
t.Cleanup(func() {
_ = s.Close()
})
return agentscripts.New(agentscripts.Options{
LogDir: t.TempDir(),
DataDirBase: t.TempDir(),
Logger: logger,
SSHServer: s,
Filesystem: fs,
GetScriptLogger: getScriptLogger,
})
}
type noopScriptLogger struct{}
func (noopScriptLogger) Send(context.Context, ...agentsdk.Log) error {
return nil
}
func (noopScriptLogger) Flush(context.Context) error {
return nil
}
type fakeScriptLogger struct {
logs chan agentsdk.Log
}
func (f *fakeScriptLogger) Send(ctx context.Context, logs ...agentsdk.Log) error {
for _, log := range logs {
select {
case <-ctx.Done():
return ctx.Err()
case f.logs <- log:
// OK!
}
}
return nil
}
func (*fakeScriptLogger) Flush(context.Context) error {
return nil
}
func newFakeScriptLogger() *fakeScriptLogger {
return &fakeScriptLogger{make(chan agentsdk.Log, 100)}
}