Repository navigation
Expand file tree
/
Copy pathown_test.go
More file actions
1277 lines (1200 loc) · 44.3 KB
/
Copy pathown_test.go
File metadata and controls
1277 lines (1200 loc) · 44.3 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
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package daemonkit
import (
"bytes"
"context"
"errors"
"fmt"
"os"
"os/exec"
"os/signal"
"path/filepath"
"regexp"
"strconv"
"strings"
"sync"
"syscall"
"testing"
"time"
"github.com/yasyf/daemonkit/durable"
"github.com/yasyf/daemonkit/internal/proc"
"github.com/yasyf/daemonkit/paths"
)
func ownedScope(t *testing.T) *Owned {
t.Helper()
return ownedScopeAt(t, filepath.Join(t.TempDir(), "daemon.records"))
}
func ownedScopeAt(t *testing.T, path string) *Owned {
t.Helper()
owned, err := OwnProcesses(bounded(t, 30*time.Second), path)
if err != nil {
t.Fatalf("OwnProcesses() = %v", err)
}
t.Cleanup(func() {
closeCtx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
_ = owned.Close(closeCtx)
})
return owned
}
func bounded(t *testing.T, d time.Duration) context.Context {
t.Helper()
ctx, cancel := context.WithTimeout(context.Background(), d)
t.Cleanup(cancel)
return ctx
}
func contendForRecord(t *testing.T, recordPath string) (*Owned, error) {
t.Helper()
ctx := bounded(t, 30*time.Second)
for {
round, cancel := context.WithTimeout(ctx, 100*time.Millisecond)
scope, err := OwnProcesses(round, recordPath)
cancel()
if err == nil || errors.Is(err, durable.ErrLockBusy) {
return scope, err
}
if !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("contended OwnProcesses() = %v, want durable.ErrLockBusy", err)
}
if ctx.Err() != nil {
t.Fatal("no bounded OwnProcesses() observed the held record lock within 30s")
}
}
}
// TestOwnProcessesExcludesASecondScope is D3's first half: the lock identity is
// the record path, so a second owner of one record cannot open and cannot then
// reclaim the first owner's children.
func TestOwnProcessesExcludesASecondScope(t *testing.T) {
path := filepath.Join(t.TempDir(), "daemon.records")
first := ownedScopeAt(t, path)
_, err := contendForRecord(t, path)
if !errors.Is(err, durable.ErrLockBusy) {
t.Fatalf("second OwnProcesses() = %v, want durable.ErrLockBusy", err)
}
if errors.Is(err, ErrBusy) {
t.Fatal("contention reported ErrBusy, which means a live incumbent owns the socket — the wrong register")
}
closeCtx, cancelClose := context.WithTimeout(context.Background(), 20*time.Second)
defer cancelClose()
if err := first.Close(closeCtx); err != nil {
t.Fatalf("Close() = %v", err)
}
if _, err := OwnProcesses(bounded(t, 20*time.Second), path); err != nil {
t.Fatalf("OwnProcesses() after the first scope closed = %v", err)
}
}
// TestOwnProcessesAgainstAServingDaemonIsRefused is D3's second half, and the
// hazard the directive names: Daemon.RecordPath is exported, so the call is
// constructible; the lock is what makes the reclaim that would kill the live
// daemon's children unreachable.
func TestOwnProcessesAgainstAServingDaemonIsRefused(t *testing.T) {
shortHome(t)
d := Daemon{Label: "dkown", Program: testProgram, Schemas: []Schema{"test.v1"}, Shutdown: Grace(5 * time.Second)}
product := &stubProduct{}
done := make(chan error, 1)
go func() {
_, err := Serve(context.Background(), d, func(Ctx) (Product, error) { return product, nil })
done <- err
}()
socket, err := paths.Socket(string(d.Label))
if err != nil {
t.Fatalf("Socket: %v", err)
}
session := awaitSession(t, socket)
if err := session.WaitReady(bounded(t, 20*time.Second)); err != nil {
t.Fatalf("WaitReady() = %v", err)
}
scope, err := contendForRecord(t, d.RecordPath())
if err == nil {
closeCtx, cancelClose := context.WithTimeout(context.Background(), 5*time.Second)
_ = scope.Close(closeCtx)
cancelClose()
t.Fatal("OwnProcesses opened a scope over a serving daemon's record; its reclaim would kill the daemon's live children")
}
if !errors.Is(err, durable.ErrLockBusy) {
t.Fatalf("OwnProcesses() = %v, want durable.ErrLockBusy", err)
}
if _, err := session.Drain(bounded(t, 20*time.Second)); err != nil {
t.Fatalf("Drain() = %v", err)
}
select {
case <-done:
case <-time.After(20 * time.Second):
t.Fatal("Serve did not return after the drain verb")
}
}
func TestOwnProcessesRequiresADeadline(t *testing.T) {
path := filepath.Join(t.TempDir(), "daemon.records")
if _, err := OwnProcesses(context.Background(), path); err == nil {
t.Fatal("OwnProcesses() accepted a context without a deadline")
}
}
func TestOwnedRunReportsStreamsExitAndTruncation(t *testing.T) {
owned := ownedScope(t)
t.Run("clean run", func(t *testing.T) {
result, err := owned.Run(bounded(t, 20*time.Second), Cmd{
Path: "/bin/cat",
Stdin: []byte("through the pipe"),
})
if err != nil {
t.Fatalf("Run() = %v", err)
}
if !bytes.Equal(result.Stdout, []byte("through the pipe")) {
t.Fatalf("Stdout = %q", result.Stdout)
}
if result.Exit.Code != 0 || result.Exit.Signal != 0 {
t.Fatalf("Exit = %+v, want a clean exit", result.Exit)
}
})
t.Run("nonzero exit is an ExitError with the streams", func(t *testing.T) {
result, err := owned.Run(bounded(t, 20*time.Second), Cmd{
Path: "/bin/sh",
Args: []string{"-c", "echo out; echo err >&2; exit 3"},
})
var exitErr *ExitError
if !errors.As(err, &exitErr) {
t.Fatalf("Run() = %v, want an *ExitError", err)
}
if exitErr.Exit.Code != 3 {
t.Fatalf("ExitError.Exit = %+v, want code 3", exitErr.Exit)
}
if strings.TrimSpace(string(result.Stdout)) != "out" || strings.TrimSpace(string(result.Stderr)) != "err" {
t.Fatalf("streams were discarded on failure: stdout=%q stderr=%q", result.Stdout, result.Stderr)
}
})
t.Run("overflow is ErrTruncated with the capped bytes", func(t *testing.T) {
result, err := owned.Run(bounded(t, 20*time.Second), Cmd{
Path: "/bin/sh",
Args: []string{"-c", "printf 0123456789abcdef"},
MaxOutput: 8,
})
if !errors.Is(err, ErrTruncated) {
t.Fatalf("Run() = %v, want ErrTruncated", err)
}
if !bytes.Equal(result.Stdout, []byte("01234567")) {
t.Fatalf("Stdout = %q, want the capped prefix retained beside the error", result.Stdout)
}
})
t.Run("deadline surfaces as context.DeadlineExceeded", func(t *testing.T) {
result, err := owned.Run(bounded(t, 2*time.Second), Cmd{
Path: "/bin/sleep",
Args: []string{"60"},
})
if !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("Run() = %v, want an error matching context.DeadlineExceeded", err)
}
if result.Exit.Reap != ReapTerminated {
t.Fatalf("Exit.Reap = %d, want ReapTerminated", result.Exit.Reap)
}
})
t.Run("no deadline is refused", func(t *testing.T) {
_, err := owned.Run(context.Background(), Cmd{Path: "/usr/bin/true"})
if err == nil {
t.Fatal("Run() accepted a context without a deadline")
}
if !strings.HasPrefix(err.Error(), "daemonkit: ") {
t.Fatalf("Run() = %q, want the daemonkit register, not proc's", err)
}
})
}
func TestOwnedRunRestatesTheBoundaryInThisPackagesRegister(t *testing.T) {
owned := ownedScope(t)
_, err := owned.Run(bounded(t, 5*time.Second), Cmd{Path: "bin/echo"})
if err == nil {
t.Fatal("Run() accepted a relative path")
}
if !strings.HasPrefix(err.Error(), "daemonkit: ") {
t.Fatalf("Run() = %q, want the daemonkit register, not proc's", err)
}
}
func TestSpawnAndAdoptRequireADeadline(t *testing.T) {
owned := ownedScope(t)
ctx := owned.Ctx(context.Background())
undeadlined := map[string]func() error{
"Owned.Spawn": func() error {
_, err := owned.Spawn(context.Background(), Cmd{Path: "/usr/bin/true"}, ChannelNone, nil)
return err
},
"Owned.Adopt": func() error { _, err := owned.Adopt(context.Background(), os.Getpid()); return err },
"Ctx.Spawn": func() error {
_, err := ctx.Spawn(context.Background(), Cmd{Path: "/usr/bin/true"}, ChannelNone, nil)
return err
},
"Ctx.Adopt": func() error { _, err := ctx.Adopt(context.Background(), os.Getpid()); return err },
}
for verb, call := range undeadlined {
err := call()
if err == nil {
t.Fatalf("%s() accepted a context without a deadline", verb)
}
if !strings.HasPrefix(err.Error(), "daemonkit: ") {
t.Fatalf("%s() = %q, want the daemonkit register", verb, err)
}
}
}
func TestZeroCtxRefusesTheVerbs(t *testing.T) {
var zero Ctx
if _, err := zero.Run(bounded(t, time.Second), Cmd{Path: "/usr/bin/true"}); !errors.Is(err, errZeroCtx) {
t.Fatalf("Ctx.Run() = %v, want the zero-Ctx refusal", err)
}
if _, err := zero.Spawn(bounded(t, time.Second), Cmd{Path: "/usr/bin/true"}, ChannelNone, nil); !errors.Is(err, errZeroCtx) {
t.Fatalf("Ctx.Spawn() = %v, want the zero-Ctx refusal", err)
}
if _, err := zero.Adopt(bounded(t, time.Second), os.Getpid()); !errors.Is(err, errZeroCtx) {
t.Fatalf("Ctx.Adopt() = %v, want the zero-Ctx refusal", err)
}
}
// TestOwnedCtxRunsProductCodeUnchanged is D15: a Ctx minted from a CLI-owned
// scope answers the same verbs Serve's does, so product code has one shape.
func TestOwnedCtxRunsProductCodeUnchanged(t *testing.T) {
owned := ownedScope(t)
ctx := owned.Ctx(context.Background())
if ctx.Context == nil || ctx.Report == nil || ctx.Stop == nil {
t.Fatalf("Owned.Ctx() = %+v, want every field populated", ctx)
}
ctx.Report([]byte("no health lane here"))
result, err := ctx.Run(bounded(t, 20*time.Second), Cmd{
Path: "/bin/echo",
Args: []string{"from a CLI scope"},
})
if err != nil {
t.Fatalf("Ctx.Run() = %v", err)
}
if strings.TrimSpace(string(result.Stdout)) != "from a CLI scope" {
t.Fatalf("Stdout = %q", result.Stdout)
}
ctx.Stop(nil)
select {
case <-ctx.Context.Done():
case <-time.After(2 * time.Second):
t.Fatal("Ctx.Stop did not cancel the minted Context")
}
}
// TestOwnedCloseSettlesEverythingItOwns is the CLI scope's whole contract: the
// caller's "did everything drain" answer is err == nil.
func TestOwnedCloseSettlesEverythingItOwns(t *testing.T) {
path := filepath.Join(t.TempDir(), "daemon.records")
owned, err := OwnProcesses(bounded(t, 20*time.Second), path)
if err != nil {
t.Fatalf("OwnProcesses() = %v", err)
}
child, err := owned.Spawn(bounded(t, 20*time.Second), Cmd{
Path: "/bin/sleep",
Args: []string{"600"},
}, ChannelNone, nil)
if err != nil {
t.Fatalf("Spawn() = %v", err)
}
pid := child.PID()
closeCtx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
if err := owned.Close(closeCtx); err != nil {
t.Fatalf("Close() = %v, want every child settled", err)
}
if alive(pid) {
t.Fatalf("pid %d survived the scope's Close", pid)
}
reopened, err := OwnProcesses(bounded(t, 20*time.Second), path)
if err != nil {
t.Fatalf("OwnProcesses() after Close = %v; the lock was not released", err)
}
if len(reopened.Reclaimed()) != 0 {
t.Fatalf("Reclaimed() = %v, want nothing left for the next generation", reopened.Reclaimed())
}
reopenCtx, cancelReopen := context.WithTimeout(context.Background(), 20*time.Second)
defer cancelReopen()
if err := reopened.Close(reopenCtx); err != nil {
t.Fatalf("Close() = %v", err)
}
}
// TestServeSettlesChildrenSpawnedThroughCtx is StageChildren's guarantee: the
// product spawns and never stops, and Serve's own ladder is what proves the
// child gone before the process leaves.
func TestServeSettlesChildrenSpawnedThroughCtx(t *testing.T) {
shortHome(t)
d := Daemon{Label: "dkctxspawn", Program: testProgram, Schemas: []Schema{"test.v1"}, Shutdown: Grace(10 * time.Second)}
spawned := make(chan int, 1)
done := make(chan Drained, 1)
go func() {
drained, _ := Serve(context.Background(), d, func(x Ctx) (Product, error) {
child, err := x.Spawn(bounded(t, 20*time.Second), Cmd{
Path: "/bin/sleep",
Args: []string{"600"},
}, ChannelNone, nil)
if err != nil {
return nil, err
}
spawned <- child.PID()
return &stubProduct{}, nil
})
done <- drained
}()
var pid int
select {
case pid = <-spawned:
case <-time.After(20 * time.Second):
t.Fatal("the product never spawned through Ctx")
}
socket, err := paths.Socket(string(d.Label))
if err != nil {
t.Fatalf("Socket: %v", err)
}
session := awaitSession(t, socket)
ctx := bounded(t, 20*time.Second)
if err := session.WaitReady(ctx); err != nil {
t.Fatalf("WaitReady() = %v", err)
}
if _, err := session.Drain(ctx); err != nil {
t.Fatalf("Drain() = %v", err)
}
select {
case drained := <-done:
if len(drained.Abandoned) != 0 {
t.Fatalf("Abandoned = %v, want nothing abandoned", drained.Abandoned)
}
case <-time.After(30 * time.Second):
t.Fatal("Serve did not return after the drain verb")
}
if alive(pid) {
t.Fatalf("the Ctx-spawned child %d survived Serve's shutdown ladder", pid)
}
}
// parkedRun publishes its own pid and then parks. exec replaces the shell, so
// the published pid is the process settlement must prove gone.
func parkedRun(pidFile string) Cmd {
return Cmd{
Path: "/bin/sh",
Args: []string{"-c", "echo $$ > " + pidFile + "; exec sleep 600"},
}
}
func awaitPID(t *testing.T, path string) int {
t.Helper()
deadline := time.Now().Add(30 * time.Second)
for time.Now().Before(deadline) {
raw, err := os.ReadFile(path)
if err == nil && strings.HasSuffix(string(raw), "\n") {
pid, convErr := strconv.Atoi(strings.TrimSpace(string(raw)))
if convErr == nil && pid > 0 {
t.Cleanup(func() { _ = syscall.Kill(pid, syscall.SIGKILL) })
return pid
}
}
time.Sleep(10 * time.Millisecond)
}
t.Fatalf("the run's child never published its pid to %s", path)
return 0
}
// TestOwnedCloseSettlesAnInFlightRun is Close's contract over the one verb
// that returns nothing to hold: a Run still executing is a live child, so a
// clean-drain answer over it would be a lie.
func TestOwnedCloseSettlesAnInFlightRun(t *testing.T) {
dir := t.TempDir()
owned, err := OwnProcesses(bounded(t, 20*time.Second), filepath.Join(dir, "daemon.records"))
if err != nil {
t.Fatalf("OwnProcesses() = %v", err)
}
pidFile := filepath.Join(dir, "run.pid")
runCtx := bounded(t, 120*time.Second)
type outcome struct {
result RunResult
err error
}
ran := make(chan outcome, 1)
go func() {
result, runErr := owned.Run(runCtx, parkedRun(pidFile))
ran <- outcome{result: result, err: runErr}
}()
pid := awaitPID(t, pidFile)
closeCtx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
if err := owned.Close(closeCtx); err != nil {
t.Fatalf("Close() = %v, want every live child settled", err)
}
if alive(pid) {
t.Fatalf("the in-flight Run's child %d survived a Close that reported a clean drain", pid)
}
select {
case got := <-ran:
var exitErr *ExitError
if !errors.As(got.err, &exitErr) {
t.Fatalf("the settled Run returned %v, want an *ExitError naming the fatal signal", got.err)
}
if exitErr.Exit.Signal != syscall.SIGTERM {
t.Fatalf("ExitError.Exit = %+v, want the settlement ladder's SIGTERM", exitErr.Exit)
}
if got.result.Exit.Reap != ReapTerminated {
t.Fatalf("RunResult.Exit.Reap = %d, want ReapTerminated", got.result.Exit.Reap)
}
case <-time.After(30 * time.Second):
t.Fatal("the in-flight Run never returned after its child was settled")
}
}
// runForksADescendant's child forks a descendant onto its own streams — the
// run's pipes stay with the leader — publishes both pids, then parks. Leader
// and descendant both keep the marker in their argv — neither execs it away —
// so a survivor is identified rather than merely observed at a pid. Neither
// process ignores SIGTERM, so what the descendant's survival measures is
// scope, not ladder patience.
func runForksADescendant(pidFile, holderFile, marker string) Cmd {
publish := func(path, pid string) string {
return "echo " + pid + " > " + path + ".tmp; mv " + path + ".tmp " + path + "; "
}
holder := "/bin/sh -c 'while :; do sleep 60; done # " + marker + "-descendant' >/dev/null 2>&1 & "
script := holder + publish(holderFile, "$!") + publish(pidFile, "$$") + "wait # " + marker + "-leader"
return Cmd{
Path: "/bin/sh",
Args: []string{"-c", script},
}
}
// TestOwnedCloseDrainsARunChildsDescendants is Close's "every live child …
// terminated and proven gone" over the shape that made the claim false. A Run
// child that inherited the caller's process group has no scope of its own, so
// terminating it leaves its own fork running under nobody's ownership — and
// Close still answers nil, which is the lie. Run now spawns into a dedicated
// session, so the descendant is inside the only scope the kernel offers.
func TestOwnedCloseDrainsARunChildsDescendants(t *testing.T) {
dir := t.TempDir()
owned, err := OwnProcesses(bounded(t, 20*time.Second), filepath.Join(dir, "daemon.records"))
if err != nil {
t.Fatalf("OwnProcesses() = %v", err)
}
pidFile := filepath.Join(dir, "run.pid")
holderFile := filepath.Join(dir, "holder.pid")
marker := fmt.Sprintf("dkdrain%d", time.Now().UnixNano())
ran := make(chan struct{})
go func() {
defer close(ran)
_, _ = owned.Run(bounded(t, 120*time.Second), runForksADescendant(pidFile, holderFile, marker))
}()
pid := awaitPID(t, pidFile)
holder := awaitPID(t, holderFile)
closeCtx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
if err := owned.Close(closeCtx); err != nil {
t.Fatalf("Close() = %v, want every live child settled", err)
}
if aliveAs(pid, marker+"-leader") {
t.Fatalf("the in-flight Run's child %d survived Close", pid)
}
if aliveAs(holder, marker+"-descendant") {
t.Fatalf("the Run child's descendant %d survived a Close that answered a clean drain", holder)
}
select {
case <-ran:
case <-time.After(30 * time.Second):
t.Fatal("the settled Run never returned")
}
}
// forkedHolderRun's child forks a descendant that inherits the run's stdout
// pipe and outlives it, then parks ignoring SIGTERM so settlement runs its
// whole ladder — the ignored disposition survives the descendant's own exec.
// Leader and descendant both keep the marker in their argv, so a survivor is
// identified rather than merely observed at a pid.
func forkedHolderRun(pidFile, holderFile, marker string) Cmd {
publish := func(path, pid string) string {
return "echo " + pid + " > " + path + ".tmp; mv " + path + ".tmp " + path + "; "
}
holder := "/bin/sh -c 'while :; do sleep 60; done # " + marker + "-descendant' & "
script := "trap '' TERM; " + holder + publish(holderFile, "$!") + publish(pidFile, "$$") + "wait # " + marker + "-leader"
return Cmd{
Path: "/bin/sh",
Args: []string{"-c", script},
}
}
// TestOwnedCloseDoesNotPinAnInFlightRunToItsOwnDeadline is the other half of
// settling a Run in flight, and the budget a Run child costs. Close terminates
// the child on the scope's budget and then settles its dedicated session on
// the settlement grace no caller deadline covers, so a scope whose Close is
// worth answering nil over is sized for both — and neither the descendant that
// inherited the stdout pipe nor the drain behind it may hold the caller for
// the rest of the run's own, far longer, deadline.
func TestOwnedCloseDoesNotPinAnInFlightRunToItsOwnDeadline(t *testing.T) {
dir := t.TempDir()
owned, err := OwnProcesses(bounded(t, 20*time.Second), filepath.Join(dir, "daemon.records"))
if err != nil {
t.Fatalf("OwnProcesses() = %v", err)
}
pidFile := filepath.Join(dir, "run.pid")
holderFile := filepath.Join(dir, "holder.pid")
marker := fmt.Sprintf("dkpipe%d", time.Now().UnixNano())
ran := make(chan time.Time, 1)
go func() {
_, _ = owned.Run(bounded(t, 60*time.Second), forkedHolderRun(pidFile, holderFile, marker))
ran <- time.Now()
}()
pid := awaitPID(t, pidFile)
holder := awaitPID(t, holderFile)
settleBy := time.Now().Add(10*time.Second + proc.SettleGrace)
closeCtx, cancel := context.WithDeadline(context.Background(), settleBy)
defer cancel()
if err := owned.Close(closeCtx); err != nil {
t.Fatalf("Close() = %v, want every live child settled", err)
}
if aliveAs(pid, marker+"-leader") {
t.Fatalf("the in-flight Run's child %d survived Close", pid)
}
if aliveAs(holder, marker+"-descendant") {
t.Fatalf("the descendant %d holding the run's pipe survived Close", holder)
}
select {
case at := <-ran:
if slack := at.Sub(settleBy); slack > 2*time.Second {
t.Errorf("the settled Run returned %v past the scope's settlement deadline; the descendant holding the pipe pinned it to the run's own 60s budget", slack)
}
case <-time.After(20 * time.Second):
t.Fatal("the settled Run never returned: the descendant holding the pipe pinned the drain")
}
}
// TestServeSettlesAnInFlightCtxRun is the same contract one layer up: a
// product goroutine inside Ctx.Run when the drain reaches StageChildren is a
// live child, and Drained is what cc-orchestrate gates service on.
func TestServeSettlesAnInFlightCtxRun(t *testing.T) {
shortHome(t)
dir := t.TempDir()
pidFile := filepath.Join(dir, "run.pid")
d := Daemon{Label: "dkctxrun", Program: testProgram, Schemas: []Schema{"test.v1"}, Shutdown: Grace(10 * time.Second)}
ran := make(chan error, 1)
done := make(chan Drained, 1)
go func() {
drained, _ := Serve(context.Background(), d, func(x Ctx) (Product, error) {
runCtx := bounded(t, 120*time.Second)
go func() {
_, err := x.Run(runCtx, parkedRun(pidFile))
ran <- err
}()
return &stubProduct{}, nil
})
done <- drained
}()
pid := awaitPID(t, pidFile)
socket, err := paths.Socket(string(d.Label))
if err != nil {
t.Fatalf("Socket: %v", err)
}
session := awaitSession(t, socket)
ctx := bounded(t, 20*time.Second)
if err := session.WaitReady(ctx); err != nil {
t.Fatalf("WaitReady() = %v", err)
}
if _, err := session.Drain(ctx); err != nil {
t.Fatalf("Drain() = %v", err)
}
select {
case drained := <-done:
if len(drained.Abandoned) != 0 {
t.Fatalf("Abandoned = %v, want nothing abandoned", drained.Abandoned)
}
case <-time.After(30 * time.Second):
t.Fatal("Serve did not return after the drain verb")
}
if alive(pid) {
t.Fatalf("the Ctx.Run child %d survived a shutdown ladder that published a clean drain", pid)
}
select {
case err := <-ran:
var exitErr *ExitError
if !errors.As(err, &exitErr) {
t.Fatalf("the settled Ctx.Run returned %v, want an *ExitError naming the fatal signal", err)
}
case <-time.After(30 * time.Second):
t.Fatal("the in-flight Ctx.Run never returned after its child was settled")
}
}
// TestOwnedCloseFaultsOnAChildWhoseExitWasNeverProven is the whole point of
// the clean-drain answer. A settlement whose budget is already spent runs the
// ladder to its end and publishes with nothing proved — the shape a child in
// uninterruptible sleep reaches on any deadline — and a Close that answered
// nil over that terminal would tell the caller everything drained.
func TestOwnedCloseFaultsOnAChildWhoseExitWasNeverProven(t *testing.T) {
dir := t.TempDir()
owned, err := OwnProcesses(bounded(t, 20*time.Second), filepath.Join(dir, "daemon.records"))
if err != nil {
t.Fatalf("OwnProcesses() = %v", err)
}
// The ladder can win the race against its own expired timer, so the
// unproven terminal is retried until it arises rather than assumed — the
// shape unprovenChild reaches the same way. A proven exit settles its child
// and drops it from the scope, so only an unproven one is left for Close.
unproven := false
for attempt := range 20 {
child, err := owned.Spawn(bounded(t, 20*time.Second), Cmd{
Path: "/bin/sleep",
Args: []string{"600"},
}, ChannelNone, nil)
if err != nil {
t.Fatalf("Spawn() attempt %d = %v", attempt, err)
}
spent, cancelSpent := context.WithTimeout(context.Background(), time.Nanosecond)
_, stopErr := child.Stop(spent)
cancelSpent()
if !errors.Is(stopErr, ErrUnsettled) {
t.Fatalf("Stop() = %v, want ErrUnsettled", stopErr)
}
if exit := <-child.Done(); exit.Reap == ReapUndetermined {
unproven = true
break
}
}
if !unproven {
t.Fatal("20 settlements on a spent budget each proved their exit, so there is no unproven terminal to close over")
}
closeCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if closeErr := owned.Close(closeCtx); !errors.Is(closeErr, ErrUnsettled) {
t.Fatalf("Close() = %v over a child whose exit was never proven, want ErrUnsettled", closeErr)
}
}
// publishingRun publishes its pid and exits at once, so a verb that was
// refused and a verb that quietly ran are told apart by the file rather than
// by the error alone.
func publishingRun(pidFile string) Cmd {
return Cmd{
Path: "/bin/sh",
Args: []string{"-c", "echo $$ > " + pidFile},
}
}
func pidWithin(path string, within time.Duration) int {
deadline := time.Now().Add(within)
for {
raw, err := os.ReadFile(path)
if err == nil {
if pid, convErr := strconv.Atoi(strings.TrimSpace(string(raw))); convErr == nil && pid > 0 {
return pid
}
}
if !time.Now().Before(deadline) {
return 0
}
time.Sleep(5 * time.Millisecond)
}
}
// parkedHelper is a live process outside this scope for Adopt to name. It is
// never os.Getpid(): a refusal that failed to refuse would record the test
// process itself as this generation's child, and the settle behind it would
// then stop the test.
func parkedHelper(t *testing.T) int {
t.Helper()
helper := exec.Command("/bin/sleep", "600")
if err := helper.Start(); err != nil {
t.Fatalf("start the adopt helper: %v", err)
}
t.Cleanup(func() {
_ = helper.Process.Kill()
_ = helper.Wait()
})
return helper.Process.Pid
}
// TestSettlingScopeRefusesEveryVerbBeforeItStartsAnything is the scope's own
// boundary, stated over both shapes a settling scope has. A closed scope
// refuses in this package's register rather than leaking the record store's
// wording. A scope that has only settled — Serve's drain order, where the
// store stays open behind the children tail — refuses on the same terms and
// for a harder reason: nothing else there would refuse at all, so a verb
// admitted past this boundary would spawn, register, and be missed.
func TestSettlingScopeRefusesEveryVerbBeforeItStartsAnything(t *testing.T) {
states := []struct {
name string
enter func(*testing.T, *Owned)
}{
{"closed", func(t *testing.T, o *Owned) {
closeCtx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
if err := o.Close(closeCtx); err != nil {
t.Fatalf("Close() = %v", err)
}
}},
{"settled with the record store still open", func(t *testing.T, o *Owned) {
settleCtx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
if err := o.settle(settleCtx); err != nil {
t.Fatalf("settle() = %v", err)
}
}},
}
for _, state := range states {
t.Run(state.name, func(t *testing.T) {
dir := t.TempDir()
owned := ownedScopeAt(t, filepath.Join(dir, "daemon.records"))
helper := parkedHelper(t)
state.enter(t, owned)
verbs := []struct {
name string
call func(pidFile string) error
}{
{"Owned.Run", func(pidFile string) error {
_, err := owned.Run(bounded(t, 10*time.Second), publishingRun(pidFile))
return err
}},
{"Owned.Spawn", func(pidFile string) error {
child, err := owned.Spawn(bounded(t, 10*time.Second), publishingRun(pidFile), ChannelNone, nil)
if child != nil {
t.Errorf("Owned.Spawn() returned child %d on a settling scope", child.PID())
}
return err
}},
{"Owned.Adopt", func(string) error {
tracked, err := owned.Adopt(bounded(t, 10*time.Second), helper)
if tracked != nil {
t.Errorf("Owned.Adopt() tracked %d on a settling scope", tracked.PID())
}
return err
}},
}
for _, verb := range verbs {
pidFile := filepath.Join(dir, verb.name+".pid")
err := verb.call(pidFile)
if !errors.Is(err, errScopeSettling) {
t.Errorf("%s() on a %s scope = %v, want the scope's own refusal", verb.name, state.name, err)
}
if err == nil || !strings.HasPrefix(err.Error(), "daemonkit: ") {
t.Errorf("%s() = %v, want the daemonkit register, not proc's", verb.name, err)
}
if pid := pidWithin(pidFile, 2*time.Second); pid != 0 {
_ = syscall.Kill(-pid, syscall.SIGKILL)
_ = syscall.Kill(pid, syscall.SIGKILL)
t.Errorf("%s() on a %s scope started pid %d; the refusal has to land before anything runs", verb.name, state.name, pid)
}
}
if !alive(helper) {
t.Errorf("the adopt helper %d was stopped by a scope that refused to adopt it", helper)
}
})
}
}
// TestSpentContextIsRefusedInThisPackagesRegister is the same class one ctx
// away: a context whose budget is already gone is refused at the boundary,
// before a child exists to abort, and never as the record store's wording.
func TestSpentContextIsRefusedInThisPackagesRegister(t *testing.T) {
path := filepath.Join(t.TempDir(), "daemon.records")
owned := ownedScopeAt(t, path)
spent, cancel := context.WithTimeout(context.Background(), time.Nanosecond)
defer cancel()
<-spent.Done()
verbs := map[string]func() error{
"Owned.Run": func() error {
_, err := owned.Run(spent, Cmd{Path: "/usr/bin/true"})
return err
},
"Owned.Spawn": func() error {
_, err := owned.Spawn(spent, Cmd{Path: "/usr/bin/true"}, ChannelNone, nil)
return err
},
"Owned.Adopt": func() error { _, err := owned.Adopt(spent, os.Getpid()); return err },
"OwnProcesses": func() error { _, err := OwnProcesses(spent, path); return err },
}
for verb, call := range verbs {
err := call()
if !errors.Is(err, context.DeadlineExceeded) {
t.Errorf("%s() on a spent context = %v, want an error matching context.DeadlineExceeded", verb, err)
continue
}
if !strings.HasPrefix(err.Error(), "daemonkit: ") {
t.Errorf("%s() = %q, want the daemonkit register, not the record store's", verb, err)
}
}
}
// sessionHolderCmd is a dedicated-session leader that forks a descendant into
// its own session, publishes both pids, and parks ignoring SIGTERM.
func sessionHolderCmd(dir string, attempt int) (c Cmd, pidFile, holderFile string) {
pidFile = filepath.Join(dir, "leader"+strconv.Itoa(attempt)+".pid")
holderFile = filepath.Join(dir, "holder"+strconv.Itoa(attempt)+".pid")
publish := func(path, pid string) string {
return "echo " + pid + " > " + path + ".tmp; mv " + path + ".tmp " + path + "; "
}
return Cmd{
Path: "/bin/sh",
Args: []string{"-c", "trap '' TERM; sleep 600 & " + publish(holderFile, "$!") + publish(pidFile, "$$") + "exec sleep 600"},
Session: true,
}, pidFile, holderFile
}
// unprovenChild leaves the scope holding a child whose terminal proved nothing
// and whose session survivor is still live: a settlement demanded on a spent
// budget runs the whole ladder and publishes ReapUndetermined, and drive skips
// session settlement entirely when the leader proved nothing, so the fork is
// never signalled. The ladder can still win the race against its own expired
// timer, so the shape is retried rather than assumed.
func unprovenChild(spawn func(Cmd) (*Child, error), dir string) (holder int, err error) {
for attempt := range 20 {
c, pidFile, holderFile := sessionHolderCmd(dir, attempt)
child, spawnErr := spawn(c)
if spawnErr != nil {
return 0, fmt.Errorf("spawn: %w", spawnErr)
}
leader, leaderErr := readPID(pidFile)
if leaderErr != nil {
return 0, leaderErr
}
holder, err = readPID(holderFile)
if err != nil {
return 0, err
}
spent, cancel := context.WithTimeout(context.Background(), time.Nanosecond)
_, stopErr := child.Stop(spent)
cancel()
if !errors.Is(stopErr, ErrUnsettled) {
return 0, fmt.Errorf("Stop() = %v, want ErrUnsettled", stopErr)
}
if exit := <-child.Done(); exit.Reap == ReapUndetermined {
return holder, nil
}
_ = syscall.Kill(-leader, syscall.SIGKILL)
}
return 0, errors.New("the settlement ladder proved every exit inside a spent budget")
}
func readPID(path string) (int, error) {
deadline := time.Now().Add(30 * time.Second)
for time.Now().Before(deadline) {
raw, err := os.ReadFile(path)
if err == nil {
if pid, convErr := strconv.Atoi(string(raw[:max(len(raw)-1, 0)])); convErr == nil && pid > 0 {
return pid, nil
}
}
time.Sleep(10 * time.Millisecond)
}
return 0, fmt.Errorf("%s never carried a pid", path)
}
// TestOwnedCloseFaultsOverALiveSessionSurvivor is the positive control one
// layer down: the scope answers the same shape honestly.
func TestOwnedCloseFaultsOverALiveSessionSurvivor(t *testing.T) {
dir := t.TempDir()
owned, err := OwnProcesses(bounded(t, 20*time.Second), filepath.Join(dir, "daemon.records"))
if err != nil {
t.Fatalf("OwnProcesses() = %v", err)
}
holder, err := unprovenChild(func(c Cmd) (*Child, error) {
return owned.Spawn(bounded(t, 20*time.Second), c, ChannelNone, nil)
}, dir)
if err != nil {
t.Fatalf("stage an unproven child: %v", err)
}
t.Cleanup(func() { _ = syscall.Kill(holder, syscall.SIGKILL) })
closeCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
closeErr := owned.Close(closeCtx)
if !alive(holder) {
t.Fatalf("the session survivor %d was gone, so this run proved nothing", holder)
}
if !errors.Is(closeErr, ErrUnsettled) {
t.Fatalf("Close() = %v with the session survivor %d live, want ErrUnsettled", closeErr, holder)
}
}
// slowCloseProduct spends the whole work window in Close, so the children
// stage runs on its reserved tail alone, as it does under a host whose worker
// stops fill the close share.
type slowCloseProduct struct{ stubProduct }
func (*slowCloseProduct) Close(b Budget) error {
time.Sleep(b.Left() - 100*time.Millisecond)
return nil
}
// TestServeProvesATermResistantSessionInsideItsChildrenTail is a session leader
// that ignores SIGTERM over a grandchild that inherited the ignore, under the
// 30s grace a real host declares with its work window spent: the children tail
// must kill and prove both on its own clock rather than let the session ladder
// run past it.
func TestServeProvesATermResistantSessionInsideItsChildrenTail(t *testing.T) {
shortHome(t)
guard := make(chan os.Signal, 1)
signal.Notify(guard, syscall.SIGTERM)
defer signal.Stop(guard)
dir := t.TempDir()
d := Daemon{Label: "dkresist", Program: testProgram, Schemas: []Schema{"test.v1"}, Shutdown: Grace(30 * time.Second)}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
staged := make(chan int, 1)
done := serveInBackground(ctx, t, d, func(x Ctx) (Product, error) {
c, _, holderFile := sessionHolderCmd(dir, 0)
if _, err := x.Spawn(bounded(t, 20*time.Second), c, ChannelNone, nil); err != nil {
return nil, err
}
holder, err := readPID(holderFile)
if err != nil {
return nil, err
}
staged <- holder
return &slowCloseProduct{}, nil
})
var holder int
select {
case holder = <-staged:
case <-time.After(30 * time.Second):
t.Fatal("the product never staged its session")
}
t.Cleanup(func() { _ = syscall.Kill(holder, syscall.SIGKILL) })
cancel()
select {
case out := <-done:
if out.err != nil {
t.Fatalf("Serve() = %v", out.err)
}
if len(out.drained.Abandoned) != 0 {
t.Fatalf("Abandoned = %v, want none for a session the tail could kill", out.drained.Abandoned)
}
case <-time.After(45 * time.Second):
_ = syscall.Kill(os.Getpid(), syscall.SIGTERM)
t.Fatal("Serve parked over a TERM-resistant session its children tail should have killed")
}