-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
client_test.go
2148 lines (1847 loc) · 60.7 KB
/
client_test.go
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
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: BUSL-1.1
package client
import (
"fmt"
"net"
"os"
"path/filepath"
"runtime"
"sort"
"testing"
"time"
memdb "github.com/hashicorp/go-memdb"
"github.com/shoenig/test"
"github.com/shoenig/test/must"
"github.com/shoenig/test/wait"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/hashicorp/nomad/ci"
"github.com/hashicorp/nomad/client/allocrunner"
"github.com/hashicorp/nomad/client/allocrunner/interfaces"
trstate "github.com/hashicorp/nomad/client/allocrunner/taskrunner/state"
"github.com/hashicorp/nomad/client/config"
"github.com/hashicorp/nomad/client/fingerprint"
regMock "github.com/hashicorp/nomad/client/serviceregistration/mock"
cstate "github.com/hashicorp/nomad/client/state"
"github.com/hashicorp/nomad/command/agent/consul"
"github.com/hashicorp/nomad/helper/pluginutils/catalog"
"github.com/hashicorp/nomad/helper/pluginutils/singleton"
"github.com/hashicorp/nomad/helper/testlog"
"github.com/hashicorp/nomad/helper/uuid"
"github.com/hashicorp/nomad/nomad"
"github.com/hashicorp/nomad/nomad/mock"
"github.com/hashicorp/nomad/nomad/structs"
nconfig "github.com/hashicorp/nomad/nomad/structs/config"
"github.com/hashicorp/nomad/plugins/device"
psstructs "github.com/hashicorp/nomad/plugins/shared/structs"
"github.com/hashicorp/nomad/testutil"
)
func testACLServer(t *testing.T, cb func(*nomad.Config)) (*nomad.Server, string, *structs.ACLToken, func()) {
server, token, cleanup := nomad.TestACLServer(t, cb)
return server, server.GetConfig().RPCAddr.String(), token, cleanup
}
func testServer(t *testing.T, cb func(*nomad.Config)) (*nomad.Server, string, func()) {
server, cleanup := nomad.TestServer(t, cb)
return server, server.GetConfig().RPCAddr.String(), cleanup
}
func TestClient_StartStop(t *testing.T) {
ci.Parallel(t)
client, cleanup := TestClient(t, nil)
defer cleanup()
if err := client.Shutdown(); err != nil {
t.Fatalf("err: %v", err)
}
}
// Certain labels for metrics are dependant on client initial setup. This tests
// that the client has properly initialized before we assign values to labels
func TestClient_BaseLabels(t *testing.T) {
ci.Parallel(t)
assert := assert.New(t)
client, cleanup := TestClient(t, nil)
if err := client.Shutdown(); err != nil {
t.Fatalf("err: %v", err)
}
defer cleanup()
// directly invoke this function, as otherwise this will fail on a CI build
// due to a race condition
client.emitStats()
baseLabels := client.baseLabels
assert.NotEqual(0, len(baseLabels))
nodeID := client.Node().ID
for _, e := range baseLabels {
if e.Name == "node_id" {
assert.Equal(nodeID, e.Value)
}
}
}
func TestClient_RPC(t *testing.T) {
ci.Parallel(t)
_, addr, cleanupS1 := testServer(t, nil)
defer cleanupS1()
c1, cleanupC1 := TestClient(t, func(c *config.Config) {
c.Servers = []string{addr}
})
defer cleanupC1()
// RPC should succeed
testutil.WaitForResult(func() (bool, error) {
var out struct{}
err := c1.RPC("Status.Ping", &structs.GenericRequest{}, &out)
return err == nil, err
}, func(err error) {
t.Fatalf("err: %v", err)
})
}
func TestClient_RPC_FireRetryWatchers(t *testing.T) {
ci.Parallel(t)
_, addr, cleanupS1 := testServer(t, nil)
defer cleanupS1()
c1, cleanupC1 := TestClient(t, func(c *config.Config) {
c.Servers = []string{addr}
})
defer cleanupC1()
watcher := c1.rpcRetryWatcher()
// RPC should succeed
testutil.WaitForResult(func() (bool, error) {
var out struct{}
err := c1.RPC("Status.Ping", &structs.GenericRequest{}, &out)
return err == nil, err
}, func(err error) {
t.Fatalf("err: %v", err)
})
select {
case <-watcher:
default:
t.Fatal("watcher should be fired")
}
}
func TestClient_RPC_Passthrough(t *testing.T) {
ci.Parallel(t)
s1, _, cleanupS1 := testServer(t, nil)
defer cleanupS1()
c1, cleanupC1 := TestClient(t, func(c *config.Config) {
c.RPCHandler = s1
})
defer cleanupC1()
// RPC should succeed
testutil.WaitForResult(func() (bool, error) {
var out struct{}
err := c1.RPC("Status.Ping", &structs.GenericRequest{}, &out)
return err == nil, err
}, func(err error) {
t.Fatalf("err: %v", err)
})
}
func TestClient_Fingerprint(t *testing.T) {
ci.Parallel(t)
c, cleanup := TestClient(t, nil)
defer cleanup()
// Ensure we are fingerprinting
testutil.WaitForResult(func() (bool, error) {
node := c.Node()
if _, ok := node.Attributes["kernel.name"]; !ok {
return false, fmt.Errorf("Expected value for kernel.name")
}
if _, ok := node.Attributes["cpu.arch"]; !ok {
return false, fmt.Errorf("Expected value for cpu.arch")
}
return true, nil
}, func(err error) {
t.Fatalf("err: %v", err)
})
}
// TestClient_Fingerprint_Periodic asserts that driver node attributes are
// periodically fingerprinted.
func TestClient_Fingerprint_Periodic(t *testing.T) {
ci.Parallel(t)
c1, cleanup := TestClient(t, func(c *config.Config) {
confs := []*nconfig.PluginConfig{
{
Name: "mock_driver",
Config: map[string]interface{}{
"shutdown_periodic_after": true,
"shutdown_periodic_duration": time.Second,
},
},
}
c.PluginLoader = catalog.TestPluginLoaderWithOptions(t, "", nil, confs)
})
defer cleanup()
// Ensure the mock driver is registered on the client
testutil.WaitForResult(func() (bool, error) {
node := c1.Node()
// assert that the driver is set on the node attributes
mockDriverInfoAttr := node.Attributes["driver.mock_driver"]
if mockDriverInfoAttr == "" {
return false, fmt.Errorf("mock driver is empty when it should be set on the node attributes")
}
mockDriverInfo := node.Drivers["mock_driver"]
// assert that the Driver information for the node is also set correctly
if mockDriverInfo == nil {
return false, fmt.Errorf("mock driver is nil when it should be set on node Drivers")
}
if !mockDriverInfo.Detected {
return false, fmt.Errorf("mock driver should be set as detected")
}
if !mockDriverInfo.Healthy {
return false, fmt.Errorf("mock driver should be set as healthy")
}
if mockDriverInfo.HealthDescription == "" {
return false, fmt.Errorf("mock driver description should not be empty")
}
return true, nil
}, func(err error) {
t.Fatalf("err: %v", err)
})
testutil.WaitForResult(func() (bool, error) {
mockDriverInfo := c1.Node().Drivers["mock_driver"]
// assert that the Driver information for the node is also set correctly
if mockDriverInfo == nil {
return false, fmt.Errorf("mock driver is nil when it should be set on node Drivers")
}
if mockDriverInfo.Detected {
return false, fmt.Errorf("mock driver should not be set as detected")
}
if mockDriverInfo.Healthy {
return false, fmt.Errorf("mock driver should not be set as healthy")
}
if mockDriverInfo.HealthDescription == "" {
return false, fmt.Errorf("mock driver description should not be empty")
}
return true, nil
}, func(err error) {
t.Fatalf("err: %v", err)
})
}
// TestClient_MixedTLS asserts that when a server is running with TLS enabled
// it will reject any RPC connections from clients that lack TLS. See #2525
func TestClient_MixedTLS(t *testing.T) {
ci.Parallel(t)
const (
cafile = "../helper/tlsutil/testdata/nomad-agent-ca.pem"
fooservercert = "../helper/tlsutil/testdata/regionFoo-server-nomad.pem"
fooserverkey = "../helper/tlsutil/testdata/regionFoo-server-nomad-key.pem"
)
s1, addr, cleanupS1 := testServer(t, func(c *nomad.Config) {
c.TLSConfig = &nconfig.TLSConfig{
EnableHTTP: true,
EnableRPC: true,
VerifyServerHostname: true,
CAFile: cafile,
CertFile: fooservercert,
KeyFile: fooserverkey,
}
})
defer cleanupS1()
testutil.WaitForLeader(t, s1.RPC)
c1, cleanup := TestClient(t, func(c *config.Config) {
c.Servers = []string{addr}
})
defer cleanup()
// tell the client we've registered to unblock the RPC we test below
c1.registeredOnce.Do(func() { close(c1.registeredCh) })
req := structs.NodeSpecificRequest{
NodeID: c1.Node().ID,
QueryOptions: structs.QueryOptions{Region: "global"},
}
var out structs.SingleNodeResponse
testutil.AssertUntil(100*time.Millisecond,
func() (bool, error) {
err := c1.RPC("Node.GetNode", &req, &out)
if err == nil || structs.IsErrPermissionDenied(err) {
return false, fmt.Errorf("client RPC succeeded when it should have failed:\n%+v", out)
}
return true, nil
},
func(err error) {
t.Fatalf(err.Error())
},
)
}
// TestClient_BadTLS asserts that when a client and server are running with TLS
// enabled -- but their certificates are signed by different CAs -- they're
// unable to communicate.
func TestClient_BadTLS(t *testing.T) {
ci.Parallel(t)
const (
cafile = "../helper/tlsutil/testdata/nomad-agent-ca.pem"
fooclientcert = "../helper/tlsutil/testdata/regionFoo-client-nomad.pem"
fooclientkey = "../helper/tlsutil/testdata/regionFoo-client-nomad-key.pem"
badca = "../helper/tlsutil/testdata/bad-agent-ca.pem"
badcert = "../helper/tlsutil/testdata/badRegion-client-bad.pem"
badkey = "../helper/tlsutil/testdata/badRegion-client-bad-key.pem"
)
s1, addr, cleanupS1 := testServer(t, func(c *nomad.Config) {
c.TLSConfig = &nconfig.TLSConfig{
EnableHTTP: true,
EnableRPC: true,
VerifyServerHostname: true,
CAFile: cafile,
CertFile: fooclientcert,
KeyFile: fooclientkey,
}
})
defer cleanupS1()
testutil.WaitForLeader(t, s1.RPC)
c1, cleanupC1 := TestClient(t, func(c *config.Config) {
c.Servers = []string{addr}
c.TLSConfig = &nconfig.TLSConfig{
EnableHTTP: true,
EnableRPC: true,
VerifyServerHostname: true,
CAFile: badca,
CertFile: badcert,
KeyFile: badkey,
}
})
defer cleanupC1()
// tell the client we've registered to unblock the RPC we test below
c1.registeredOnce.Do(func() { close(c1.registeredCh) })
req := structs.NodeSpecificRequest{
NodeID: c1.Node().ID,
QueryOptions: structs.QueryOptions{Region: "global"},
}
var out structs.SingleNodeResponse
testutil.AssertUntil(100*time.Millisecond,
func() (bool, error) {
err := c1.RPC("Node.GetNode", &req, &out)
if err == nil || structs.IsErrPermissionDenied(err) {
return false, fmt.Errorf("client RPC succeeded when it should have failed:\n%+v", out)
}
return true, nil
},
func(err error) {
t.Fatalf(err.Error())
},
)
}
func TestClient_Register(t *testing.T) {
ci.Parallel(t)
s1, _, cleanupS1 := testServer(t, nil)
defer cleanupS1()
testutil.WaitForLeader(t, s1.RPC)
c1, cleanupC1 := TestClient(t, func(c *config.Config) {
c.RPCHandler = s1
})
defer cleanupC1()
req := structs.NodeSpecificRequest{
NodeID: c1.Node().ID,
QueryOptions: structs.QueryOptions{Region: "global"},
}
var out structs.SingleNodeResponse
// Register should succeed
testutil.WaitForResult(func() (bool, error) {
err := s1.RPC("Node.GetNode", &req, &out)
if err != nil {
return false, err
}
if out.Node == nil {
return false, fmt.Errorf("missing reg")
}
return out.Node.ID == req.NodeID, nil
}, func(err error) {
t.Fatalf("err: %v", err)
})
}
func TestClient_Register_NodePool(t *testing.T) {
ci.Parallel(t)
s1, _, cleanupS1 := testServer(t, nil)
defer cleanupS1()
testutil.WaitForLeader(t, s1.RPC)
// Create client with a node pool configured.
c1, cleanupC1 := TestClient(t, func(c *config.Config) {
c.RPCHandler = s1
c.Node.NodePool = "dev"
})
defer cleanupC1()
// Create client with no node pool configured.
c2, cleanupC2 := TestClient(t, func(c *config.Config) {
c.RPCHandler = s1
c.Node.NodePool = ""
})
defer cleanupC2()
nodeReq := structs.NodeSpecificRequest{
QueryOptions: structs.QueryOptions{Region: "global"},
}
var nodeResp structs.SingleNodeResponse
poolReq := structs.NodePoolSpecificRequest{
Name: "dev",
QueryOptions: structs.QueryOptions{Region: "global"},
}
var poolResp structs.SingleNodePoolResponse
// Register should succeed and node pool should be created.
// Client without node pool configuration should be in the default pool.
testutil.WaitForResult(func() (bool, error) {
// Fetch node1.
nodeReq.NodeID = c1.Node().ID
err := s1.RPC("Node.GetNode", &nodeReq, &nodeResp)
if err != nil {
return false, err
}
if nodeResp.Node == nil {
return false, fmt.Errorf("c1 is missing")
}
if nodeResp.Node.NodePool != "dev" {
return false, fmt.Errorf("c1 has wrong node pool")
}
// Fetch node1 node pool.
err = s1.RPC("NodePool.GetNodePool", &poolReq, &poolResp)
if err != nil {
return false, err
}
if poolResp.NodePool == nil {
return false, fmt.Errorf("dev node pool is nil")
}
// Fetch node2.
nodeReq.NodeID = c2.Node().ID
err = s1.RPC("Node.GetNode", &nodeReq, &nodeResp)
if err != nil {
return false, err
}
if nodeResp.Node == nil {
return false, fmt.Errorf("c2 is missing")
}
if nodeResp.Node.NodePool != structs.NodePoolDefault {
return false, fmt.Errorf("c2 has wrong node pool")
}
return true, nil
}, func(err error) {
t.Fatalf("err: %v", err)
})
}
func TestClient_Heartbeat(t *testing.T) {
ci.Parallel(t)
s1, _, cleanupS1 := testServer(t, func(c *nomad.Config) {
c.MinHeartbeatTTL = 50 * time.Millisecond
})
defer cleanupS1()
testutil.WaitForLeader(t, s1.RPC)
c1, cleanupC1 := TestClient(t, func(c *config.Config) {
c.RPCHandler = s1
})
defer cleanupC1()
req := structs.NodeSpecificRequest{
NodeID: c1.Node().ID,
QueryOptions: structs.QueryOptions{Region: "global"},
}
var out structs.SingleNodeResponse
// Register should succeed
testutil.WaitForResult(func() (bool, error) {
err := s1.RPC("Node.GetNode", &req, &out)
if err != nil {
return false, err
}
if out.Node == nil {
return false, fmt.Errorf("missing reg")
}
return out.Node.Status == structs.NodeStatusReady, nil
}, func(err error) {
t.Fatalf("err: %v", err)
})
}
// TestClient_UpdateAllocStatus that once running allocations send updates to
// the server.
func TestClient_UpdateAllocStatus(t *testing.T) {
ci.Parallel(t)
s1, _, cleanupS1 := testServer(t, nil)
defer cleanupS1()
_, cleanup := TestClient(t, func(c *config.Config) {
c.RPCHandler = s1
})
defer cleanup()
job := mock.Job()
// allow running job on any node including self client, that may not be a Linux box
job.Constraints = nil
job.TaskGroups[0].Constraints = nil
job.TaskGroups[0].Count = 1
task := job.TaskGroups[0].Tasks[0]
task.Driver = "mock_driver"
task.Config = map[string]interface{}{
"run_for": "10s",
}
task.Services = nil
// WaitForRunning polls the server until the ClientStatus is running
testutil.WaitForRunning(t, s1.RPC, job)
}
func TestClient_WatchAllocs(t *testing.T) {
ci.Parallel(t)
s1, _, cleanupS1 := testServer(t, nil)
defer cleanupS1()
testutil.WaitForLeader(t, s1.RPC)
c1, cleanup := TestClient(t, func(c *config.Config) {
c.RPCHandler = s1
})
defer cleanup()
// Wait until the node is ready
waitTilNodeReady(c1, t)
// Create mock allocations
job := mock.Job()
job.TaskGroups[0].Count = 3
job.TaskGroups[0].Tasks[0].Driver = "mock_driver"
job.TaskGroups[0].Tasks[0].Config = map[string]interface{}{
"run_for": "10s",
}
alloc1 := mock.Alloc()
alloc1.JobID = job.ID
alloc1.Job = job
alloc1.NodeID = c1.Node().ID
alloc2 := mock.Alloc()
alloc2.NodeID = c1.Node().ID
alloc2.JobID = job.ID
alloc2.Job = job
state := s1.State()
if err := state.UpsertJob(structs.MsgTypeTestSetup, 100, nil, job); err != nil {
t.Fatal(err)
}
if err := state.UpsertJobSummary(101, mock.JobSummary(alloc1.JobID)); err != nil {
t.Fatal(err)
}
err := state.UpsertAllocs(structs.MsgTypeTestSetup, 102, []*structs.Allocation{alloc1, alloc2})
if err != nil {
t.Fatalf("err: %v", err)
}
// Both allocations should get registered
testutil.WaitForResult(func() (bool, error) {
c1.allocLock.RLock()
num := len(c1.allocs)
c1.allocLock.RUnlock()
return num == 2, nil
}, func(err error) {
t.Fatalf("err: %v", err)
})
// Delete one allocation
if err := state.DeleteEval(103, nil, []string{alloc1.ID}, false); err != nil {
t.Fatalf("err: %v", err)
}
// Update the other allocation. Have to make a copy because the allocs are
// shared in memory in the test and the modify index would be updated in the
// alloc runner.
alloc2_2 := alloc2.Copy()
alloc2_2.DesiredStatus = structs.AllocDesiredStatusStop
if err := state.UpsertAllocs(structs.MsgTypeTestSetup, 104, []*structs.Allocation{alloc2_2}); err != nil {
t.Fatalf("err upserting stopped alloc: %v", err)
}
// One allocation should get GC'd and removed
testutil.WaitForResult(func() (bool, error) {
c1.allocLock.RLock()
num := len(c1.allocs)
c1.allocLock.RUnlock()
return num == 1, nil
}, func(err error) {
t.Fatalf("err: %v", err)
})
// One allocations should get updated
testutil.WaitForResult(func() (bool, error) {
c1.allocLock.RLock()
ar := c1.allocs[alloc2.ID]
c1.allocLock.RUnlock()
return ar.Alloc().DesiredStatus == structs.AllocDesiredStatusStop, nil
}, func(err error) {
t.Fatalf("err: %v", err)
})
}
func waitTilNodeReady(client *Client, t *testing.T) {
testutil.WaitForResult(func() (bool, error) {
n := client.Node()
if n.Status != structs.NodeStatusReady {
return false, fmt.Errorf("node not registered")
}
return true, nil
}, func(err error) {
t.Fatalf("err: %v", err)
})
}
// TestClient_SaveRestoreState exercises the allocrunner restore code paths
// after a client restart. It runs several jobs in different states and asserts
// the expected final state and server updates.
func TestClient_SaveRestoreState(t *testing.T) {
ci.Parallel(t)
s1, _, cleanupS1 := testServer(t, nil)
t.Cleanup(cleanupS1)
testutil.WaitForLeader(t, s1.RPC)
c1, cleanupC1 := TestClient(t, func(c *config.Config) {
c.DevMode = false
c.RPCHandler = s1
})
t.Cleanup(func() {
for _, ar := range c1.getAllocRunners() {
ar.Destroy()
}
for _, ar := range c1.getAllocRunners() {
<-ar.DestroyCh()
}
cleanupC1()
})
// Wait until the node is ready
waitTilNodeReady(c1, t)
migrateStrategy := structs.DefaultMigrateStrategy()
migrateStrategy.MinHealthyTime = time.Millisecond
migrateStrategy.HealthCheck = structs.MigrateStrategyHealthStates
// Create mock jobs and allocations that will start up fast
setup := func(id string) *structs.Job {
job := mock.MinJob()
job.ID = id
job.TaskGroups[0].Migrate = migrateStrategy
must.NoError(t, s1.RPC("Job.Register", &structs.JobRegisterRequest{
Job: job,
WriteRequest: structs.WriteRequest{Region: "global", Namespace: job.Namespace},
}, &structs.JobRegisterResponse{}))
return job
}
// job1: will be left running
// job2: will be stopped before shutdown
// job3: will be stopped after shutdown
// job4: will be stopped and GC'd after shutdown
job1, job2, job3, job4 := setup("job1"), setup("job2"), setup("job3"), setup("job4")
// Allocations should be placed
must.Wait(t, wait.InitialSuccess(
wait.ErrorFunc(func() error {
c1.allocLock.RLock()
defer c1.allocLock.RUnlock()
if len(c1.allocs) != 4 {
return fmt.Errorf("expected 4 alloc runners")
}
for _, ar := range c1.allocs {
if ar.AllocState().ClientStatus != structs.AllocClientStatusRunning {
return fmt.Errorf("expected running client status, got %v",
ar.AllocState().ClientStatus)
}
}
return nil
}),
wait.Timeout(time.Second*10),
wait.Gap(time.Millisecond*30),
))
store := s1.State()
allocIDforJob := func(job *structs.Job) string {
allocs, err := store.AllocsByJob(nil, job.Namespace, job.ID, false)
must.NoError(t, err)
must.Len(t, 1, allocs) // we should only ever get 1 in this test
return allocs[0].ID
}
alloc1 := allocIDforJob(job1)
alloc2 := allocIDforJob(job2)
alloc3 := allocIDforJob(job3)
alloc4 := allocIDforJob(job4)
t.Logf("alloc1=%s alloc2=%s alloc3=%s alloc4=%s", alloc1, alloc2, alloc3, alloc4)
// Stop the 2nd job before we shut down
must.NoError(t, s1.RPC("Job.Deregister", &structs.JobDeregisterRequest{
JobID: job2.ID,
WriteRequest: structs.WriteRequest{Region: "global", Namespace: job2.Namespace},
}, &structs.JobDeregisterResponse{}))
var alloc2ModifyIndex uint64
var alloc2AllocModifyIndex uint64
// Wait till we're sure the client has received the stop and updated the server
must.Wait(t, wait.InitialSuccess(
wait.ErrorFunc(func() error {
alloc, err := store.AllocByID(nil, alloc2)
must.NotNil(t, alloc)
must.NoError(t, err)
if alloc.ClientStatus != structs.AllocClientStatusComplete {
// note that the allocrunner is non-nil until it's been
// client-GC'd, so we're just looking to make sure the client
// has updated the server
return fmt.Errorf("alloc2 should have been marked completed")
}
alloc2ModifyIndex = alloc.ModifyIndex
alloc2AllocModifyIndex = alloc.AllocModifyIndex
return nil
}),
wait.Timeout(time.Second*20),
wait.Gap(time.Millisecond*30),
))
t.Log("shutting down client")
must.NoError(t, c1.Shutdown()) // note: this saves the client state DB
// Stop the 3rd job while we're down
must.NoError(t, s1.RPC("Job.Deregister", &structs.JobDeregisterRequest{
JobID: job3.ID,
WriteRequest: structs.WriteRequest{Region: "global", Namespace: job3.Namespace},
}, &structs.JobDeregisterResponse{}))
// Stop and purge the 4th job while we're down
must.NoError(t, s1.RPC("Job.Deregister", &structs.JobDeregisterRequest{
JobID: job4.ID,
Purge: true,
WriteRequest: structs.WriteRequest{Region: "global", Namespace: job4.Namespace},
}, &structs.JobDeregisterResponse{}))
// Ensure the allocation has been deleted as well
must.NoError(t, s1.RPC("Eval.Reap", &structs.EvalReapRequest{
Allocs: []string{alloc4},
WriteRequest: structs.WriteRequest{Region: "global"},
}, &structs.GenericResponse{}))
var alloc3AllocModifyIndex uint64
var alloc3ModifyIndex uint64
// Wait till we're sure the scheduler has marked alloc3 for stop and deleted alloc4
must.Wait(t, wait.InitialSuccess(
wait.ErrorFunc(func() error {
alloc, err := store.AllocByID(nil, alloc3)
must.NotNil(t, alloc)
must.NoError(t, err)
if alloc.DesiredStatus != structs.AllocDesiredStatusStop {
return fmt.Errorf("alloc3 should have been marked for stop")
}
alloc3ModifyIndex = alloc.ModifyIndex
alloc3AllocModifyIndex = alloc.AllocModifyIndex
alloc, err = store.AllocByID(nil, alloc4)
must.NoError(t, err)
if alloc != nil {
return fmt.Errorf("alloc4 should have been deleted")
}
return nil
}),
wait.Timeout(time.Second*5),
wait.Gap(time.Millisecond*30),
))
a1, err := store.AllocByID(nil, alloc1)
var alloc1AllocModifyIndex uint64
var alloc1ModifyIndex uint64
alloc1ModifyIndex = a1.ModifyIndex
alloc1AllocModifyIndex = a1.AllocModifyIndex
t.Log("starting new client")
logger := testlog.HCLogger(t)
c1.config.Logger = logger
consulCatalog := consul.NewMockCatalog(logger)
mockService := regMock.NewServiceRegistrationHandler(logger)
// ensure we use non-shutdown driver instances
c1.config.PluginLoader = catalog.TestPluginLoaderWithOptions(t, "", c1.config.Options, nil)
c1.config.PluginSingletonLoader = singleton.NewSingletonLoader(logger, c1.config.PluginLoader)
c2, err := NewClient(c1.config, consulCatalog, nil, mockService, nil)
must.NoError(t, err)
t.Cleanup(func() {
for _, ar := range c2.getAllocRunners() {
ar.Destroy()
}
for _, ar := range c2.getAllocRunners() {
<-ar.DestroyCh()
}
c2.Shutdown()
})
// Ensure only the expected allocation is running
must.Wait(t, wait.InitialSuccess(
wait.ErrorFunc(func() error {
c2.allocLock.RLock()
defer c2.allocLock.RUnlock()
if len(c2.allocs) != 3 {
// the GC'd alloc will not have restored AR
return fmt.Errorf("expected 3 alloc runners")
}
for allocID, ar := range c2.allocs {
if ar == nil {
return fmt.Errorf("nil alloc runner")
}
switch allocID {
case alloc1:
if ar.AllocState().ClientStatus != structs.AllocClientStatusRunning {
return fmt.Errorf("expected running client status, got %v",
ar.AllocState().ClientStatus)
}
case alloc3:
if ar.AllocState().ClientStatus != structs.AllocClientStatusComplete {
return fmt.Errorf("expected complete client status, got %v",
ar.AllocState().ClientStatus)
}
// because the client's update will be batched, we need to
// ensure we wait for the server update too
a3, err := store.AllocByID(nil, alloc3)
must.NoError(t, err)
must.NotNil(t, a3)
if alloc3AllocModifyIndex != a3.AllocModifyIndex ||
alloc3ModifyIndex >= a3.ModifyIndex {
return fmt.Errorf(
"alloc %s stopped during shutdown should have updated", a3.ID[:8])
}
default:
if ar.AllocState().ClientStatus != structs.AllocClientStatusComplete {
return fmt.Errorf("expected complete client status, got %v",
ar.AllocState().ClientStatus)
}
}
}
return nil
}),
wait.Timeout(time.Second*10),
wait.Gap(time.Millisecond*30),
))
// Because we're asserting that no changes have been made, we have to wait a
// sufficient amount of time to verify that
must.Wait(t, wait.ContinualSuccess(
wait.ErrorFunc(func() error {
a1, err = store.AllocByID(nil, alloc1)
must.NoError(t, err)
must.NotNil(t, a1)
if alloc1AllocModifyIndex != a1.AllocModifyIndex ||
alloc1ModifyIndex != a1.ModifyIndex {
return fmt.Errorf("alloc still running should not have updated")
}
a2, err := store.AllocByID(nil, alloc2)
must.NoError(t, err)
must.NotNil(t, a2)
if alloc2AllocModifyIndex != a2.AllocModifyIndex ||
alloc2ModifyIndex != a2.ModifyIndex {
return fmt.Errorf(
"alloc %s stopped before shutdown should not have updated", a2.ID[:8])
}
// TODO: the alloc has been GC'd so the server will reject any
// update. It'd be nice if we could instrument the server here to
// ensure we didn't send one either.
a4, err := store.AllocByID(nil, alloc4)
must.NoError(t, err)
if a4 != nil {
return fmt.Errorf("garbage collected alloc should not exist")
}
return nil
}),
wait.Timeout(time.Second*3),
wait.Gap(time.Millisecond*100),
))
}
func TestClient_AddAllocError(t *testing.T) {
ci.Parallel(t)
require := require.New(t)
s1, _, cleanupS1 := testServer(t, nil)
defer cleanupS1()
testutil.WaitForLeader(t, s1.RPC)
c1, cleanupC1 := TestClient(t, func(c *config.Config) {
c.DevMode = false
c.RPCHandler = s1
})
defer cleanupC1()
// Wait until the node is ready
waitTilNodeReady(c1, t)
// Create mock allocation with invalid task group name
job := mock.Job()
alloc1 := mock.Alloc()
alloc1.NodeID = c1.Node().ID
alloc1.Job = job
alloc1.JobID = job.ID
alloc1.Job.TaskGroups[0].Tasks[0].Driver = "mock_driver"
alloc1.Job.TaskGroups[0].Tasks[0].Config = map[string]interface{}{
"run_for": "10s",
}
alloc1.ClientStatus = structs.AllocClientStatusPending
// Set these two fields to nil to cause alloc runner creation to fail
alloc1.AllocatedResources = nil
alloc1.TaskResources = nil
state := s1.State()
err := state.UpsertJob(structs.MsgTypeTestSetup, 100, nil, job)
require.Nil(err)
err = state.UpsertJobSummary(101, mock.JobSummary(alloc1.JobID))
require.Nil(err)
err = state.UpsertAllocs(structs.MsgTypeTestSetup, 102, []*structs.Allocation{alloc1})
require.Nil(err)
// Push this alloc update to the client
allocUpdates := &allocUpdates{
pulled: map[string]*structs.Allocation{
alloc1.ID: alloc1,
},
}
c1.runAllocs(allocUpdates)
// Ensure the allocation has been marked as invalid and failed on the server
testutil.WaitForResult(func() (bool, error) {
c1.allocLock.RLock()
ar := c1.allocs[alloc1.ID]
_, isInvalid := c1.invalidAllocs[alloc1.ID]
c1.allocLock.RUnlock()
if ar != nil {
return false, fmt.Errorf("expected nil alloc runner")
}
if !isInvalid {
return false, fmt.Errorf("expected alloc to be marked as invalid")
}
alloc, err := s1.State().AllocByID(nil, alloc1.ID)
require.Nil(err)
failed := alloc.ClientStatus == structs.AllocClientStatusFailed
if !failed {
return false, fmt.Errorf("Expected failed client status, but got %v", alloc.ClientStatus)
}
return true, nil
}, func(err error) {
require.NoError(err)
})
}
func TestClient_Init(t *testing.T) {
ci.Parallel(t)
dir := t.TempDir()
allocDir := filepath.Join(dir, "alloc")