-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdaemon_test.go
More file actions
799 lines (725 loc) · 23 KB
/
Copy pathdaemon_test.go
File metadata and controls
799 lines (725 loc) · 23 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
// Copyright 2026 HAProxy Technologies LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"bytes"
"log"
"os"
"path/filepath"
"strings"
"syscall"
"testing"
"time"
"github.com/haproxytech/gopherd/control"
"github.com/haproxytech/gopherd/internal/metrics"
"github.com/haproxytech/gopherd/internal/yml"
"github.com/haproxytech/gopherd/service"
)
func newTestDaemon(procs []service.Process) *daemon {
cfg := &yml.Config{
Processes: procs,
}
d := &daemon{
cfg: cfg,
m: metrics.New(),
pidMap: make(map[int]*service.Service),
restartCh: make(chan restartReq, 64),
services: make(map[string]*service.Service),
shutdownCh: make(chan struct{}),
}
d.buildServices()
return d
}
func TestBuildServices(t *testing.T) {
t.Parallel()
d := newTestDaemon([]service.Process{
{Name: "web", Command: "/bin/web"},
{Name: "worker", Command: "/bin/worker"},
})
if len(d.services) != 2 {
t.Fatalf("expected 2 services, got %d", len(d.services))
}
if _, ok := d.services["web"]; !ok {
t.Error("missing service 'web'")
}
if _, ok := d.services["worker"]; !ok {
t.Error("missing service 'worker'")
}
}
// TestBuildServicesControlSocket verifies the daemon hands its resolved control
// socket path to every service so children can reach the control socket.
func TestBuildServicesControlSocket(t *testing.T) {
t.Parallel()
d := newTestDaemon([]service.Process{
{Name: "web", Command: "/bin/web"},
})
if got := d.services["web"].ControlSocket; got != control.DefaultSocketPath {
t.Errorf("default: ControlSocket = %q, want %q", got, control.DefaultSocketPath)
}
// The startup-bound path wins over the current config: reload re-parses the
// file without the GOPHERD_SOCKET env override, and the socket is bind-once.
d2 := &daemon{
controlSocket: "/bound/at/startup.sock",
cfg: &yml.Config{
Control: control.Config{SocketPath: "/from/reparsed/config.sock"},
Processes: []service.Process{{Name: "web", Command: "/bin/web"}},
},
m: metrics.New(),
services: make(map[string]*service.Service),
}
if err := d2.buildServices(); err != nil {
t.Fatalf("buildServices: %v", err)
}
if got := d2.services["web"].ControlSocket; got != "/bound/at/startup.sock" {
t.Errorf("reload: ControlSocket = %q, want /bound/at/startup.sock", got)
}
}
func TestBuildServicesNameFallback(t *testing.T) {
t.Parallel()
d := newTestDaemon([]service.Process{
{Command: "/bin/myapp"},
})
if _, ok := d.services["/bin/myapp"]; !ok {
t.Error("expected service name to fall back to command")
}
}
func TestBuildServicesEntrypointArgs(t *testing.T) {
t.Parallel()
d := &daemon{
cfg: &yml.Config{
Processes: []service.Process{
{Name: "app", Command: "/bin/app", Args: []string{"--base"}, UseEntrypointArgs: true},
{Name: "sidecar", Command: "/bin/sidecar"},
},
},
m: metrics.New(),
pidMap: make(map[int]*service.Service),
restartCh: make(chan restartReq, 64),
entrypointArgs: []string{"--extra1", "--extra2"},
}
d.buildServices()
app := d.services["app"]
if app == nil {
t.Fatal("missing service 'app'")
}
// The process args should include the entrypoint args.
if app.Proc.Args[len(app.Proc.Args)-1] != "--extra2" {
t.Errorf("expected entrypoint args appended, got %v", app.Proc.Args)
}
sidecar := d.services["sidecar"]
if sidecar == nil {
t.Fatal("missing service 'sidecar'")
}
if len(sidecar.Proc.Args) != 0 {
t.Errorf("sidecar should have no args, got %v", sidecar.Proc.Args)
}
}
func TestBuildServicesNoEntrypointArgsWhenEmpty(t *testing.T) {
t.Parallel()
d := &daemon{
cfg: &yml.Config{
Processes: []service.Process{
{Name: "app", Command: "/bin/app", Args: []string{"--base"}, UseEntrypointArgs: true},
},
},
m: metrics.New(),
pidMap: make(map[int]*service.Service),
restartCh: make(chan restartReq, 64),
entrypointArgs: nil,
}
d.buildServices()
app := d.services["app"]
if len(app.Proc.Args) != 1 || app.Proc.Args[0] != "--base" {
t.Errorf("expected only base args when entrypointArgs is empty, got %v", app.Proc.Args)
}
}
func TestStartOrder(t *testing.T) {
t.Parallel()
d := newTestDaemon([]service.Process{
{Name: "web", Command: "/bin/web", After: []string{"db"}},
{Name: "db", Command: "/bin/db"},
})
ord, err := d.startOrder()
if err != nil {
t.Fatalf("startOrder: %v", err)
}
if len(ord) != 2 {
t.Fatalf("expected 2 entries, got %d", len(ord))
}
// db must come before web.
dbIdx, webIdx := -1, -1
for i, name := range ord {
if name == "db" {
dbIdx = i
}
if name == "web" {
webIdx = i
}
}
if dbIdx >= webIdx {
t.Errorf("expected db before web, got order %v", ord)
}
}
func TestStartOrderCycle(t *testing.T) {
t.Parallel()
d := newTestDaemon([]service.Process{
{Name: "a", Command: "/bin/a", After: []string{"b"}},
{Name: "b", Command: "/bin/b", After: []string{"a"}},
})
_, err := d.startOrder()
if err == nil {
t.Error("expected error for cyclic dependencies")
}
}
func TestInitiateShutdown(t *testing.T) {
t.Parallel()
d := newTestDaemon([]service.Process{
{Name: "app", Command: "/bin/app"},
})
d.initiateShutdown(42)
if !d.shuttingDown.Load() {
t.Error("expected shuttingDown=true")
}
if d.exitCode.Load() != 42 {
t.Errorf("expected exitCode=42, got %d", d.exitCode.Load())
}
}
func TestHandleCheckFailureRestart(t *testing.T) {
t.Parallel()
d := newTestDaemon([]service.Process{
{Name: "app", Command: "/bin/app", OnCheckFailure: map[string]string{"health": "restart"}},
})
// handleCheckFailure should not panic on non-running services.
d.handleCheckFailure("health")
}
func TestHandleCheckFailureShutdown(t *testing.T) {
t.Parallel()
d := newTestDaemon([]service.Process{
{Name: "app", Command: "/bin/app", OnCheckFailure: map[string]string{"health": "shutdown"}},
})
d.handleCheckFailure("health")
if !d.shuttingDown.Load() {
t.Error("expected shutdown on check failure with shutdown action")
}
}
func TestHandleCheckFailureIgnore(t *testing.T) {
t.Parallel()
d := newTestDaemon([]service.Process{
{Name: "app", Command: "/bin/app", OnCheckFailure: map[string]string{"health": "ignore"}},
})
d.handleCheckFailure("health")
if d.shuttingDown.Load() {
t.Error("expected no shutdown on ignore action")
}
}
func TestHandleCheckFailureUnknownCheck(t *testing.T) {
t.Parallel()
d := newTestDaemon([]service.Process{
{Name: "app", Command: "/bin/app"},
})
// Should not panic for checks no service cares about.
d.handleCheckFailure("nonexistent")
if d.shuttingDown.Load() {
t.Error("should not shut down for unrelated check")
}
}
func TestHandleCheckFailureSkipsDuringShutdown(t *testing.T) {
t.Parallel()
d := newTestDaemon([]service.Process{
{Name: "app", Command: "/bin/app", OnCheckFailure: map[string]string{"health": "shutdown"}},
})
d.shuttingDown.Store(true)
d.exitCode.Store(0)
d.handleCheckFailure("health")
// exitCode should not change since we were already shutting down.
if d.exitCode.Load() != 0 {
t.Errorf("expected exitCode to remain 0 during shutdown, got %d", d.exitCode.Load())
}
}
func TestSetupControl(t *testing.T) {
t.Parallel()
d := newTestDaemon([]service.Process{
{Name: "app", Command: "/bin/app"},
})
ctrl := d.setupControl()
if ctrl == nil {
t.Fatal("setupControl returned nil")
}
// Test StatsFn.
stats := ctrl.StatsFn()
if !strings.Contains(stats, "app") {
t.Errorf("StatsFn should include 'app', got %q", stats)
}
// Test StatusFn for existing service.
status, err := ctrl.StatusFn("app")
if err != nil {
t.Errorf("StatusFn(app): %v", err)
}
if !strings.Contains(status, "pending") {
t.Errorf("expected pending status for enabled-but-not-yet-started service, got %q", status)
}
// Test StatusFn for unknown service.
_, err = ctrl.StatusFn("nonexistent")
if err == nil {
t.Error("expected error for unknown service")
}
// Test StopFn for non-running service.
msg, err := ctrl.StopFn("app")
if err != nil {
t.Errorf("StopFn(app): %v", err)
}
if !strings.Contains(msg, "already stopped") {
t.Errorf("expected already stopped, got %q", msg)
}
// Test SignalFn for non-running service.
_, err = ctrl.SignalFn("app", "SIGTERM")
if err == nil {
t.Error("expected error signaling non-running service")
}
// Test unknown service for StartFn.
_, err = ctrl.StartFn("nonexistent")
if err == nil {
t.Error("expected error for unknown service")
}
}
func TestSetupControlStatsEmpty(t *testing.T) {
t.Parallel()
d := newTestDaemon(nil)
ctrl := d.setupControl()
stats := ctrl.StatsFn()
if stats != "no stats" {
t.Errorf("expected 'no stats', got %q", stats)
}
}
func TestWaitStatusCodeExited(t *testing.T) {
t.Parallel()
// WaitStatus where process exited normally with code 0.
ws := syscall.WaitStatus(0) // exited, status 0
code := waitStatusCode(ws)
if code != 0 {
t.Errorf("expected 0, got %d", code)
}
}
func TestWaitStatusCodeExitedNonZero(t *testing.T) {
t.Parallel()
// WaitStatus for exit code 42: code << 8.
ws := syscall.WaitStatus(42 << 8)
code := waitStatusCode(ws)
if code != 42 {
t.Errorf("expected 42, got %d", code)
}
}
func TestWaitStatusCodeSignaled(t *testing.T) {
t.Parallel()
// WaitStatus for killed by SIGKILL (9).
ws := syscall.WaitStatus(int(syscall.SIGKILL))
code := waitStatusCode(ws)
if code != 128+9 {
t.Errorf("expected %d, got %d", 128+9, code)
}
}
func TestBuildServicesWithPrefix(t *testing.T) {
t.Parallel()
cfg := &yml.Config{
Prefix: "global",
Processes: []service.Process{{Name: "app", Command: "/bin/app"}},
}
d := &daemon{
cfg: cfg,
m: metrics.New(),
pidMap: make(map[int]*service.Service),
restartCh: make(chan restartReq, 64),
}
d.buildServices()
if _, ok := d.services["app"]; !ok {
t.Error("missing service 'app'")
}
}
func TestStopAllNoRunning(t *testing.T) {
t.Parallel()
d := newTestDaemon([]service.Process{
{Name: "app", Command: "/bin/app"},
})
// Should not panic when no services are running.
d.stopAll()
}
func TestReverseSeq(t *testing.T) {
t.Parallel()
d := &daemon{shutdownSeq: []string{"db", "app", "web"}}
rev := d.reverseSeq()
want := []string{"web", "app", "db"}
for i, name := range rev {
if name != want[i] {
t.Errorf("reverseSeq()[%d] = %q, want %q", i, name, want[i])
}
}
}
func TestStopAllReverseDep(t *testing.T) {
t.Parallel()
d := newTestDaemon([]service.Process{
{Name: "db", Command: "/bin/db"},
{Name: "app", Command: "/bin/app"},
{Name: "web", Command: "/bin/web"},
})
d.shutdownSeq = []string{"db", "app", "web"}
d.shutdownMode = "" // default = reverse-dep
// Should not panic on non-running services.
d.stopAll()
}
func TestStopAllDep(t *testing.T) {
t.Parallel()
d := newTestDaemon([]service.Process{
{Name: "db", Command: "/bin/db"},
{Name: "app", Command: "/bin/app"},
{Name: "web", Command: "/bin/web"},
})
d.shutdownSeq = []string{"db", "app", "web"}
d.shutdownMode = "dep"
d.stopAll()
}
func TestStopAllSimultaneous(t *testing.T) {
t.Parallel()
d := newTestDaemon([]service.Process{
{Name: "db", Command: "/bin/db"},
{Name: "app", Command: "/bin/app"},
{Name: "web", Command: "/bin/web"},
})
d.shutdownSeq = []string{"db", "app", "web"}
d.shutdownMode = "simultaneous"
d.stopAll()
}
func TestCloseLogTargetsNoTargets(t *testing.T) {
t.Parallel()
d := newTestDaemon([]service.Process{
{Name: "app", Command: "/bin/app"},
})
// Should not panic with no log targets.
d.closeLogTargets()
if d.logTargets != nil {
t.Error("expected logTargets to be nil after close")
}
}
func TestStopChecksEmpty(t *testing.T) {
t.Parallel()
d := newTestDaemon(nil)
// Should not panic with no checkers.
d.stopChecks()
if d.checkers != nil {
t.Error("expected checkers to be nil after stop")
}
}
// TestProcessConfigChangedCommand verifies that changing a service's command
// must be detected as a configuration change requiring a restart.
func TestProcessConfigChangedCommand(t *testing.T) {
t.Parallel()
old := service.Process{Command: "/bin/old", Args: []string{"-v"}}
updated := service.Process{Command: "/bin/new", Args: []string{"-v"}}
if !processConfigChanged(old, updated) {
t.Error("processConfigChanged must return true when command changes")
}
}
// TestProcessConfigChangedArgs verifies that changing a service's arguments
// must be detected as a configuration change requiring a restart.
func TestProcessConfigChangedArgs(t *testing.T) {
t.Parallel()
old := service.Process{Command: "/bin/app", Args: []string{"--port=8080"}}
updated := service.Process{Command: "/bin/app", Args: []string{"--port=9090"}}
if !processConfigChanged(old, updated) {
t.Error("processConfigChanged must return true when args change")
}
}
// TestProcessConfigChangedNoOp verifies that identical configs report no change.
func TestProcessConfigChangedNoOp(t *testing.T) {
t.Parallel()
p := service.Process{Command: "/bin/app", Args: []string{"-x"}}
if processConfigChanged(p, p) {
t.Error("processConfigChanged must return false for identical config")
}
}
// TestIntPtrDiffers verifies that a nil-vs-non-nil difference is detected
// even when the non-nil pointer points to the zero value.
func TestIntPtrDiffers(t *testing.T) {
t.Parallel()
zero := 0
one := 1
// nil vs non-nil (even pointing to zero) is a difference.
if !intPtrDiffers(nil, &zero) {
t.Error("intPtrDiffers(nil, &0) must be true")
}
if !intPtrDiffers(&zero, nil) {
t.Error("intPtrDiffers(&0, nil) must be true")
}
// nil vs nil is not a difference.
if intPtrDiffers(nil, nil) {
t.Error("intPtrDiffers(nil, nil) must be false")
}
// same value is not a difference.
if intPtrDiffers(&zero, &zero) {
t.Error("intPtrDiffers(&0, &0) must be false")
}
// different values is a difference.
if !intPtrDiffers(&zero, &one) {
t.Error("intPtrDiffers(&0, &1) must be true")
}
}
// TestInitiateShutdownClosesShutdownCh verifies that initiateShutdown closes
// the shutdownCh so goroutines blocking on it (e.g. the restart backoff
// sleeper) are unblocked immediately.
func TestInitiateShutdownClosesShutdownCh(t *testing.T) {
t.Parallel()
d := newTestDaemon([]service.Process{
{Name: "app", Command: "/bin/app"},
})
// shutdownCh must be open initially.
select {
case <-d.shutdownCh:
t.Fatal("shutdownCh should be open before initiateShutdown")
default:
}
d.initiateShutdown(0)
// shutdownCh must be closed after initiateShutdown.
select {
case <-d.shutdownCh:
// correct
default:
t.Error("shutdownCh should be closed after initiateShutdown")
}
}
// TestInitiateShutdownIdempotent verifies that a second initiateShutdown call
// does not panic (double-close of shutdownCh).
func TestInitiateShutdownIdempotent(t *testing.T) {
t.Parallel()
d := newTestDaemon([]service.Process{
{Name: "app", Command: "/bin/app"},
})
d.initiateShutdown(1)
// Second call must not panic.
d.initiateShutdown(2)
// First exit code wins.
if d.exitCode.Load() != 1 {
t.Errorf("expected exitCode=1, got %d", d.exitCode.Load())
}
}
// TestStartServiceRejectsReplacedService verifies that startService returns
// errServiceReplaced when the service pointer passed to it is no longer the
// current instance in d.services (simulating a reload that replaced it).
func TestStartServiceRejectsReplacedService(t *testing.T) {
t.Parallel()
d := newTestDaemon([]service.Process{
{Name: "app", Command: "/bin/app"},
})
// Build a stale service pointer that is NOT in d.services.
stale, err := service.New(service.Process{Name: "app", Command: "/bin/app"}, "")
if err != nil {
t.Fatalf("service.New: %v", err)
}
_, err = d.startService(stale)
if err != errServiceReplaced {
t.Errorf("expected errServiceReplaced, got %v", err)
}
}
// TestStartServiceRejectsRemovedService verifies that startService returns
// errServiceReplaced when the service name has been removed from d.services
// entirely (simulating a reload that dropped the service from config).
func TestStartServiceRejectsRemovedService(t *testing.T) {
t.Parallel()
d := newTestDaemon([]service.Process{
{Name: "app", Command: "/bin/app"},
})
svc := d.services["app"]
delete(d.services, "app")
_, err := d.startService(svc)
if err != errServiceReplaced {
t.Errorf("expected errServiceReplaced, got %v", err)
}
}
// TestWaitOneshotSuccess verifies waitOneshot returns code 0 for a process that
// exits cleanly.
func TestWaitOneshotSuccess(t *testing.T) {
t.Parallel()
pid, err := syscall.ForkExec("/bin/true", []string{"true"}, nil)
if err != nil {
t.Skipf("ForkExec: %v", err)
}
code, err := waitOneshot(pid, "")
if err != nil {
t.Fatalf("waitOneshot: %v", err)
}
if code != 0 {
t.Errorf("expected exit code 0, got %d", code)
}
}
// TestWaitOneshotNonZero verifies waitOneshot returns the non-zero exit code
// from a process that exits with a failure status.
func TestWaitOneshotNonZero(t *testing.T) {
t.Parallel()
pid, err := syscall.ForkExec("/bin/sh", []string{"sh", "-c", "exit 3"}, nil)
if err != nil {
t.Skipf("ForkExec: %v", err)
}
code, err := waitOneshot(pid, "")
if err != nil {
t.Fatalf("waitOneshot: %v", err)
}
if code != 3 {
t.Errorf("expected exit code 3, got %d", code)
}
}
// TestWaitOneshotTimeout verifies waitOneshot returns an error (and does not
// block indefinitely) when the process does not exit within the given timeout.
func TestWaitOneshotTimeout(t *testing.T) {
t.Parallel()
pid, err := syscall.ForkExec("/bin/sleep", []string{"sleep", "60"}, nil)
if err != nil {
t.Skipf("ForkExec: %v", err)
}
defer func() {
syscall.Kill(pid, syscall.SIGKILL)
var ws syscall.WaitStatus
syscall.Wait4(pid, &ws, 0, nil)
}()
start := time.Now()
_, err = waitOneshot(pid, "50ms")
if err == nil {
t.Fatal("expected timeout error, got nil")
}
if elapsed := time.Since(start); elapsed > 2*time.Second {
t.Errorf("waitOneshot took too long: %s", elapsed)
}
}
// TestReloadRejectsMultipleEntrypointArgs verifies that reload() rejects a
// config where more than one process has use-entrypoint-args: true, matching
// the same check that run() performs at startup. Without this, a hot-reload
// could silently install an invalid config.
func TestReloadRejectsMultipleEntrypointArgs(t *testing.T) {
t.Parallel()
const cfg = `
processes:
- name: proc1
command: /bin/sh
use-entrypoint-args: true
- name: proc2
command: /bin/sh
use-entrypoint-args: true
`
dir := t.TempDir()
path := filepath.Join(dir, "gopherd.yml")
if err := os.WriteFile(path, []byte(cfg), 0o644); err != nil {
t.Fatalf("write config: %v", err)
}
d := &daemon{
configPath: path,
cfg: &yml.Config{Processes: []service.Process{{Name: "existing", Command: "/bin/sh"}}},
m: metrics.New(),
pidMap: make(map[int]*service.Service),
restartCh: make(chan restartReq, 64),
services: make(map[string]*service.Service),
shutdownCh: make(chan struct{}),
}
d.buildServices()
d.started.Store(true) // reload validation runs post-startup
_, err := d.reload()
if err == nil {
t.Fatal("expected error when more than one process has use-entrypoint-args: true")
}
if !strings.Contains(err.Error(), "use-entrypoint-args") {
t.Errorf("error %q should mention use-entrypoint-args", err.Error())
}
}
// TestStartServiceErrServiceReplacedNotFatal covers O2: startService returns
// errServiceReplaced when a service pointer is stale (replaced by a reload),
// and this must NOT be treated as a fatal failure in the reload toStart loop.
// The fix adds errServiceReplaced to the reload exclusion list alongside
// errShuttingDown, matching the existing handling in the restart goroutine.
func TestStartServiceErrServiceReplacedNotFatal(t *testing.T) {
t.Parallel()
d := newTestDaemon([]service.Process{
{Name: "svc1", Command: "/bin/false"},
})
oldSvc := d.services["svc1"]
// Replace the service in d.services to simulate a concurrent reload.
replacement, err := service.New(service.Process{Name: "svc1", Command: "/bin/false"}, "")
if err != nil {
t.Fatalf("service.New: %v", err)
}
d.mu.Lock()
d.services["svc1"] = replacement
d.mu.Unlock()
_, err = d.startService(oldSvc)
if err != errServiceReplaced {
t.Fatalf("startService with stale pointer: expected errServiceReplaced, got %v", err)
}
// Capture log output while applying the reload toStart loop condition.
var buf bytes.Buffer
log.SetOutput(&buf)
defer log.SetOutput(os.Stderr)
// This mirrors the reload toStart loop guard. errServiceReplaced must be
// excluded so it is not logged as a spurious reload failure. Before the fix
// only errShuttingDown was excluded; after the fix errServiceReplaced is too.
if err != nil && err != errShuttingDown && err != errServiceReplaced {
log.Printf("reload: start %s failed: %v", oldSvc.Name, err)
}
if strings.Contains(buf.String(), "reload: start svc1 failed") {
t.Errorf("errServiceReplaced must not produce a reload failure log; got: %q", buf.String())
}
}
// TestAnyRunningCheckUsesPidMap verifies that the anyRunning sentinel used
// during shutdown is based on d.pidMap and not d.services, so that services
// removed by a reload (still in pidMap but gone from services) are counted.
// This is a structural test: we verify that len(d.pidMap) is the right signal
// by confirming an entry added directly to pidMap is visible when d.services
// is empty.
func TestAnyRunningCheckUsesPidMap(t *testing.T) {
t.Parallel()
d := newTestDaemon(nil)
// Place a fake PID into pidMap without touching services.
fakeSvc, err := service.New(service.Process{Name: "ghost", Command: "/bin/ghost"}, "")
if err != nil {
t.Fatalf("service.New: %v", err)
}
d.mu.Lock()
d.pidMap[99999] = fakeSvc
anyRunning := len(d.pidMap) > 0
d.mu.Unlock()
if !anyRunning {
t.Error("anyRunning should be true when pidMap has entries even if services is empty")
}
// Removing from pidMap should flip the flag.
d.mu.Lock()
delete(d.pidMap, 99999)
anyRunning = len(d.pidMap) > 0
d.mu.Unlock()
if anyRunning {
t.Error("anyRunning should be false after all pidMap entries are removed")
}
}
// TestReloadBlockedDuringStartup verifies reload() refuses until d.started,
// closing the startup-phase concurrent-map-write race on d.services.
func TestReloadBlockedDuringStartup(t *testing.T) {
t.Parallel()
d := newTestDaemon([]service.Process{
{Name: "app", Command: "/bin/true"},
})
// started defaults false: reload must refuse before touching the map.
if _, err := d.reload(); err == nil {
t.Fatal("reload should be blocked before startup completes")
} else if !strings.Contains(err.Error(), "starting up") {
t.Errorf("expected a 'starting up' rejection, got: %v", err)
}
// Past the gate, reload fails on the missing config path instead.
d.started.Store(true)
if _, err := d.reload(); err == nil || strings.Contains(err.Error(), "starting up") {
t.Errorf("after started, reload must pass the gate; got: %v", err)
}
}