-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
Copy pathdecommission.go
1413 lines (1263 loc) · 44.9 KB
/
decommission.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 2018 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package tests
import (
"context"
gosql "database/sql"
"fmt"
"math/rand"
"reflect"
"regexp"
"strconv"
"strings"
"time"
"github.com/cockroachdb/cockroach/pkg/cli"
"github.com/cockroachdb/cockroach/pkg/cmd/roachtest/cluster"
"github.com/cockroachdb/cockroach/pkg/cmd/roachtest/option"
"github.com/cockroachdb/cockroach/pkg/cmd/roachtest/registry"
"github.com/cockroachdb/cockroach/pkg/cmd/roachtest/test"
"github.com/cockroachdb/cockroach/pkg/roachprod/install"
"github.com/cockroachdb/cockroach/pkg/testutils/sqlutils"
"github.com/cockroachdb/cockroach/pkg/util/retry"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"github.com/cockroachdb/errors"
"github.com/kr/pretty"
"github.com/stretchr/testify/require"
"golang.org/x/sync/errgroup"
)
func registerDecommission(r registry.Registry) {
{
numNodes := 4
duration := time.Hour
r.Add(registry.TestSpec{
Name: fmt.Sprintf("decommission/nodes=%d/duration=%s", numNodes, duration),
Owner: registry.OwnerKV,
Cluster: r.MakeClusterSpec(numNodes),
Run: func(ctx context.Context, t test.Test, c cluster.Cluster) {
if c.IsLocal() {
duration = 5 * time.Minute
t.L().Printf("running with duration=%s in local mode\n", duration)
}
runDecommission(ctx, t, c, numNodes, duration)
},
})
}
{
numNodes := 9
duration := 30 * time.Minute
r.Add(registry.TestSpec{
Name: fmt.Sprintf("drain-and-decommission/nodes=%d", numNodes),
Owner: registry.OwnerKV,
Cluster: r.MakeClusterSpec(numNodes),
Run: func(ctx context.Context, t test.Test, c cluster.Cluster) {
runDrainAndDecommission(ctx, t, c, numNodes, duration)
},
})
}
{
numNodes := 4
r.Add(registry.TestSpec{
Name: "decommission/drains",
Owner: registry.OwnerServer,
Cluster: r.MakeClusterSpec(numNodes),
Run: func(ctx context.Context, t test.Test, c cluster.Cluster) {
runDecommissionDrains(ctx, t, c)
},
})
}
{
numNodes := 6
r.Add(registry.TestSpec{
Name: "decommission/randomized",
Owner: registry.OwnerKV,
Timeout: 10 * time.Minute,
Cluster: r.MakeClusterSpec(numNodes),
Run: func(ctx context.Context, t test.Test, c cluster.Cluster) {
runDecommissionRandomized(ctx, t, c)
},
})
}
{
numNodes := 4
r.Add(registry.TestSpec{
Name: "decommission/mixed-versions",
Owner: registry.OwnerKV,
Cluster: r.MakeClusterSpec(numNodes),
Run: func(ctx context.Context, t test.Test, c cluster.Cluster) {
runDecommissionMixedVersions(ctx, t, c, *t.BuildVersion())
},
})
}
{
numNodes := 6
r.Add(registry.TestSpec{
Name: "decommission/slow",
Owner: registry.OwnerServer,
Cluster: r.MakeClusterSpec(numNodes),
Run: func(ctx context.Context, t test.Test, c cluster.Cluster) {
runDecommissionSlow(ctx, t, c)
},
})
}
}
// runDrainAndDecommission marks 3 nodes in the test cluster as "draining" and
// then attempts to decommission a fourth node from the cluster. This test is
// meant to ensure that, in the allocator, we consider "draining" nodes as
// "live" for the purposes of determining whether a range can achieve quorum.
// Note that, if "draining" nodes were not considered live for this purpose,
// decommissioning would stall forever since the allocator would incorrectly
// think that at least a handful of ranges (that need to be moved off the
// decommissioning node) are unavailable.
func runDrainAndDecommission(
ctx context.Context, t test.Test, c cluster.Cluster, nodes int, duration time.Duration,
) {
const defaultReplicationFactor = 5
if defaultReplicationFactor > nodes {
t.Fatal("improper configuration: replication factor greater than number of nodes in the test")
}
pinnedNode := 1
c.Put(ctx, t.Cockroach(), "./cockroach", c.All())
for i := 1; i <= nodes; i++ {
c.Start(ctx, t.L(), option.DefaultStartOpts(), install.MakeClusterSettings(), c.Node(i))
}
c.Run(ctx, c.Node(pinnedNode), `./cockroach workload init kv --drop --splits 1000`)
run := func(stmt string) {
db := c.Conn(ctx, t.L(), pinnedNode)
defer db.Close()
t.Status(stmt)
_, err := db.ExecContext(ctx, stmt)
if err != nil {
t.Fatal(err)
}
t.L().Printf("run: %s\n", stmt)
}
run(fmt.Sprintf(`ALTER RANGE default CONFIGURE ZONE USING num_replicas=%d`, defaultReplicationFactor))
run(fmt.Sprintf(`ALTER DATABASE system CONFIGURE ZONE USING num_replicas=%d`, defaultReplicationFactor))
// Speed up the decommissioning.
run(`SET CLUSTER SETTING kv.snapshot_rebalance.max_rate='2GiB'`)
run(`SET CLUSTER SETTING kv.snapshot_recovery.max_rate='2GiB'`)
t.Status("waiting for initial up-replication")
db := c.Conn(ctx, t.L(), pinnedNode)
defer func() {
_ = db.Close()
}()
for {
fullReplicated := false
if err := db.QueryRow(
// Check if all ranges are fully replicated.
"SELECT min(array_length(replicas, 1)) >= $1 FROM crdb_internal.ranges",
defaultReplicationFactor,
).Scan(&fullReplicated); err != nil {
t.Fatal(err)
}
if fullReplicated {
break
}
time.Sleep(time.Second)
}
var m *errgroup.Group
m, ctx = errgroup.WithContext(ctx)
m.Go(
func() error {
return c.RunE(ctx, c.Node(pinnedNode),
fmt.Sprintf("./cockroach workload run kv --max-rate 500 --tolerate-errors --duration=%s {pgurl:1-%d}",
duration.String(), nodes-4,
),
)
},
)
// Let the workload run for a small amount of time.
time.Sleep(1 * time.Minute)
// Drain the last 3 nodes from the cluster.
for nodeID := nodes - 2; nodeID <= nodes; nodeID++ {
id := nodeID
m.Go(func() error {
drain := func(id int) error {
t.Status(fmt.Sprintf("draining node %d", id))
return c.RunE(ctx, c.Node(id), "./cockroach node drain --insecure")
}
return drain(id)
})
}
// Sleep for long enough that all the other nodes in the cluster learn about
// the draining status of the two nodes we just drained.
time.Sleep(30 * time.Second)
m.Go(func() error {
// Decommission the fourth-to-last node from the cluster.
id := nodes - 3
decom := func(id int) error {
t.Status(fmt.Sprintf("decommissioning node %d", id))
return c.RunE(ctx, c.Node(id), "./cockroach node decommission --self --insecure")
}
return decom(id)
})
if err := m.Wait(); err != nil {
t.Fatal(err)
}
}
// runDecommission decommissions and wipes nodes in a cluster repeatedly,
// alternating between the node being shut down gracefully before and after the
// decommissioning operation, while some light load is running against the
// cluster (to manually verify that the qps don't dip too much).
//
// TODO(tschottdorf): verify that the logs don't contain the messages
// that would spam the log before #23605. I wonder if we should really
// start grepping the logs. An alternative is to introduce a metric
// that would have signaled this and check that instead.
func runDecommission(
ctx context.Context, t test.Test, c cluster.Cluster, nodes int, duration time.Duration,
) {
const defaultReplicationFactor = 3
if defaultReplicationFactor > nodes {
t.Fatal("improper configuration: replication factor greater than number of nodes in the test")
}
// The number of nodes we're going to cycle through. Since we're sometimes
// killing the nodes and then removing them, this means having to be careful
// with loss of quorum. So only ever touch a fixed minority of nodes and
// swap them out for as long as the test runs. The math boils down to `1`,
// but conceivably we'll want to run a test with replication factor five
// at some point.
numDecom := (defaultReplicationFactor - 1) / 2
// node1 is kept pinned (i.e. not decommissioned/restarted), and is the node
// through which we run the workload and other queries.
pinnedNode := 1
c.Put(ctx, t.Cockroach(), "./cockroach", c.All())
c.Put(ctx, t.DeprecatedWorkload(), "./workload", c.Node(pinnedNode))
for i := 1; i <= nodes; i++ {
startOpts := option.DefaultStartOpts()
startOpts.RoachprodOpts.ExtraArgs = append(startOpts.RoachprodOpts.ExtraArgs, fmt.Sprintf("--attrs=node%d", i))
c.Start(ctx, t.L(), startOpts, install.MakeClusterSettings(), c.Node(i))
}
c.Run(ctx, c.Node(pinnedNode), `./workload init kv --drop`)
waitReplicatedAwayFrom := func(downNodeID int) error {
db := c.Conn(ctx, t.L(), pinnedNode)
defer func() {
_ = db.Close()
}()
for {
var count int
if err := db.QueryRow(
// Check if the down node has any replicas.
"SELECT count(*) FROM crdb_internal.ranges WHERE array_position(replicas, $1) IS NOT NULL",
downNodeID,
).Scan(&count); err != nil {
return err
}
if count == 0 {
fullReplicated := false
if err := db.QueryRow(
// Check if all ranges are fully replicated.
"SELECT min(array_length(replicas, 1)) >= 3 FROM crdb_internal.ranges",
).Scan(&fullReplicated); err != nil {
return err
}
if fullReplicated {
break
}
}
time.Sleep(time.Second)
}
return nil
}
waitUpReplicated := func(targetNode, targetNodeID int) error {
db := c.Conn(ctx, t.L(), pinnedNode)
defer func() {
_ = db.Close()
}()
var count int
for {
// Check to see that there are no ranges where the target node is
// not part of the replica set.
stmtReplicaCount := fmt.Sprintf(
`SELECT count(*) FROM crdb_internal.ranges WHERE array_position(replicas, %d) IS NULL and database_name = 'kv';`, targetNodeID)
if err := db.QueryRow(stmtReplicaCount).Scan(&count); err != nil {
return err
}
t.Status(fmt.Sprintf("node%d missing %d replica(s)", targetNode, count))
if count == 0 {
break
}
time.Sleep(time.Second)
}
return nil
}
if err := waitReplicatedAwayFrom(0 /* no down node */); err != nil {
t.Fatal(err)
}
workloads := []string{
// TODO(tschottdorf): in remote mode, the ui shows that we consistently write
// at 330 qps (despite asking for 500 below). Locally we get 500qps (and a lot
// more without rate limiting). Check what's up with that.
fmt.Sprintf("./workload run kv --max-rate 500 --tolerate-errors --duration=%s {pgurl:1-%d}", duration.String(), nodes),
}
run := func(stmt string) {
db := c.Conn(ctx, t.L(), pinnedNode)
defer db.Close()
t.Status(stmt)
_, err := db.ExecContext(ctx, stmt)
if err != nil {
t.Fatal(err)
}
t.L().Printf("run: %s\n", stmt)
}
var m *errgroup.Group // see comment in version.go
m, ctx = errgroup.WithContext(ctx)
for _, cmd := range workloads {
cmd := cmd // copy is important for goroutine
m.Go(func() error {
return c.RunE(ctx, c.Node(pinnedNode), cmd)
})
}
m.Go(func() error {
getNodeID := func(node int) (int, error) {
dbNode := c.Conn(ctx, t.L(), node)
defer dbNode.Close()
var nodeID int
if err := dbNode.QueryRow(`SELECT node_id FROM crdb_internal.node_runtime_info LIMIT 1`).Scan(&nodeID); err != nil {
return 0, err
}
return nodeID, nil
}
stop := func(node int) error {
port := fmt.Sprintf("{pgport:%d}", node)
defer time.Sleep(time.Second) // work around quit returning too early
return c.RunE(ctx, c.Node(node), "./cockroach quit --insecure --host=:"+port)
}
decom := func(id int) error {
port := fmt.Sprintf("{pgport:%d}", pinnedNode) // always use the pinned node
t.Status(fmt.Sprintf("decommissioning node %d", id))
return c.RunE(ctx, c.Node(pinnedNode), fmt.Sprintf("./cockroach node decommission --insecure --wait=all --host=:%s %d", port, id))
}
tBegin, whileDown := timeutil.Now(), true
node := nodes
for timeutil.Since(tBegin) <= duration {
// Alternate between the node being shut down gracefully before and
// after the decommissioning operation.
whileDown = !whileDown
// Cycle through the last numDecom nodes.
node = nodes - (node % numDecom)
if node == pinnedNode {
t.Fatalf("programming error: not expecting to decommission/wipe node%d", pinnedNode)
}
t.Status(fmt.Sprintf("decommissioning %d (down=%t)", node, whileDown))
nodeID, err := getNodeID(node)
if err != nil {
return err
}
run(fmt.Sprintf(`ALTER RANGE default CONFIGURE ZONE = 'constraints: {"+node%d"}'`, node))
if err := waitUpReplicated(node, nodeID); err != nil {
return err
}
if whileDown {
if err := stop(node); err != nil {
return err
}
}
run(fmt.Sprintf(`ALTER RANGE default CONFIGURE ZONE = 'constraints: {"-node%d"}'`, node))
if err := decom(nodeID); err != nil {
return err
}
if err := waitReplicatedAwayFrom(nodeID); err != nil {
return err
}
if !whileDown {
if err := stop(node); err != nil {
return err
}
}
// Wipe the node and re-add to cluster with a new node ID.
if err := c.RunE(ctx, c.Node(node), "rm -rf {store-dir}"); err != nil {
return err
}
db := c.Conn(ctx, t.L(), pinnedNode)
defer db.Close()
internalAddrs, err := c.InternalAddr(ctx, t.L(), c.Node(pinnedNode))
if err != nil {
return err
}
startOpts := option.DefaultStartOpts()
startOpts.RoachprodOpts.ExtraArgs = append(startOpts.RoachprodOpts.ExtraArgs, fmt.Sprintf("--join %s --attrs=node%d", internalAddrs[0], node))
if err := c.StartE(ctx, t.L(), startOpts, install.MakeClusterSettings(), c.Node(node)); err != nil {
return err
}
}
// TODO(tschottdorf): run some ui sanity checks about decommissioned nodes
// having disappeared. Verify that the workloads don't dip their qps or
// show spikes in latencies.
return nil
})
if err := m.Wait(); err != nil {
t.Fatal(err)
}
}
// runDecommissionRandomized tests a bunch of node
// decommissioning/recommissioning procedures, all the while checking for
// replica movement and appropriate membership status detection behavior. We go
// through partial decommissioning of random nodes, ensuring we're able to undo
// those operations. We then fully decommission nodes, verifying it's an
// irreversible operation.
func runDecommissionRandomized(ctx context.Context, t test.Test, c cluster.Cluster) {
c.Put(ctx, t.Cockroach(), "./cockroach")
settings := install.MakeClusterSettings()
settings.Env = append(settings.Env, "COCKROACH_SCAN_MAX_IDLE_TIME=5ms")
c.Start(ctx, t.L(), option.DefaultStartOpts(), settings)
h := newDecommTestHelper(t, c)
firstNodeID := h.nodeIDs[0]
retryOpts := retry.Options{
InitialBackoff: time.Second,
MaxBackoff: 5 * time.Second,
Multiplier: 2,
}
warningFilter := []string{
"^warning: node [0-9]+ is already decommissioning or decommissioned$",
}
// Partially decommission then recommission n1, from another
// random node. Run a couple of status checks while doing so.
// We hard-code n1 to guard against the hypothetical case in which
// targetNode has no replicas (yet) to begin with, which would make
// it permanently decommissioned even with `--wait=none`.
// We can choose runNode freely (including chosing targetNode) since
// the decommission process won't succeed.
{
targetNode, runNode := h.nodeIDs[0], h.getRandNode()
t.L().Printf("partially decommissioning n%d from n%d\n", targetNode, runNode)
o, err := h.decommission(ctx, c.Node(targetNode), runNode,
"--wait=none", "--format=csv")
if err != nil {
t.Fatalf("decommission failed: %v", err)
}
exp := [][]string{
decommissionHeader,
{strconv.Itoa(targetNode), "true", `\d+`, "true", "decommissioning", "false"},
}
if err := cli.MatchCSV(o, exp); err != nil {
t.Fatal(err)
}
// Check that `node status` reflects an ongoing decommissioning status
// for the second node.
{
runNode = h.getRandNode()
t.L().Printf("checking that `node status` (from n%d) shows n%d as decommissioning\n",
runNode, targetNode)
o, err := execCLI(ctx, t, c, runNode, "node", "status", "--format=csv", "--decommission")
if err != nil {
t.Fatalf("node-status failed: %v", err)
}
numCols, err := cli.GetCsvNumCols(o)
require.NoError(t, err)
exp := h.expectCell(targetNode-1, /* node IDs are 1-indexed */
statusHeaderMembershipColumnIdx, `decommissioning`, c.Spec().NodeCount, numCols)
if err := cli.MatchCSV(o, exp); err != nil {
t.Fatal(err)
}
}
// Recommission the target node, cancel the in-flight decommissioning
// process.
{
runNode = h.getRandNode()
t.L().Printf("recommissioning n%d (from n%d)\n", targetNode, runNode)
if _, err := h.recommission(ctx, c.Node(targetNode), runNode); err != nil {
t.Fatalf("recommission failed: %v", err)
}
}
// Check that `node status` now reflects a 'active' status for the
// target node.
{
runNode = h.getRandNode()
t.L().Printf("checking that `node status` (from n%d) shows n%d as active\n",
targetNode, runNode)
o, err := execCLI(ctx, t, c, runNode, "node", "status", "--format=csv", "--decommission")
if err != nil {
t.Fatalf("node-status failed: %v", err)
}
numCols, err := cli.GetCsvNumCols(o)
require.NoError(t, err)
exp := h.expectCell(targetNode-1, /* node IDs are 1-indexed */
statusHeaderMembershipColumnIdx, `active`, c.Spec().NodeCount, numCols)
if err := cli.MatchCSV(o, exp); err != nil {
t.Fatal(err)
}
}
}
// Check to see that operators aren't able to decommission into
// availability. We'll undo the attempted decommissioning event by
// recommissioning the targeted nodes. Note that the decommission
// attempt will not result in any individual nodes being marked
// as decommissioned, as this would only happen if *all* targeted
// nodes report no replicas, which is impossible since we're targeting
// the whole cluster here.
{
// Attempt to decommission all the nodes.
{
// NB: the retry loop here is mostly silly, but since some of the fields below
// are async, we may for example find an 'active' node instead of 'decommissioning'.
if err := retry.WithMaxAttempts(ctx, retryOpts, 50, func() error {
runNode := h.getRandNode()
t.L().Printf("attempting to decommission all nodes from n%d\n", runNode)
o, err := h.decommission(ctx, c.All(), runNode,
"--wait=none", "--format=csv")
if err != nil {
t.Fatalf("decommission failed: %v", err)
}
exp := [][]string{decommissionHeader}
for i := 1; i <= c.Spec().NodeCount; i++ {
rowRegex := []string{strconv.Itoa(i), "true", `\d+`, "true", "decommissioning", "false"}
exp = append(exp, rowRegex)
}
if err := cli.MatchCSV(o, exp); err != nil {
t.Fatalf("decommission failed: %v", err)
}
return nil
}); err != nil {
t.Fatal(err)
}
}
// Check that `node status` reflects an ongoing decommissioning status for
// all nodes.
{
runNode := h.getRandNode()
t.L().Printf("checking that `node status` (from n%d) shows all nodes as decommissioning\n",
runNode)
o, err := execCLI(ctx, t, c, runNode, "node", "status", "--format=csv", "--decommission")
if err != nil {
t.Fatalf("node-status failed: %v", err)
}
numCols, err := cli.GetCsvNumCols(o)
require.NoError(t, err)
var colRegex []string
for i := 1; i <= c.Spec().NodeCount; i++ {
colRegex = append(colRegex, `decommissioning`)
}
exp := h.expectColumn(statusHeaderMembershipColumnIdx, colRegex, c.Spec().NodeCount, numCols)
if err := cli.MatchCSV(o, exp); err != nil {
t.Fatal(err)
}
}
// Check that we can still do stuff, creating a database should be good
// enough.
{
runNode := h.getRandNode()
t.L().Printf("checking that we're able to create a database (from n%d)\n", runNode)
db := c.Conn(ctx, t.L(), runNode)
defer db.Close()
if _, err := db.Exec(`create database still_working;`); err != nil {
t.Fatal(err)
}
}
// Cancel in-flight decommissioning process of all nodes.
{
runNode := h.getRandNode()
t.L().Printf("recommissioning all nodes (from n%d)\n", runNode)
if _, err := h.recommission(ctx, c.All(), runNode); err != nil {
t.Fatalf("recommission failed: %v", err)
}
}
// Check that `node status` now reflects an 'active' status for all
// nodes.
{
runNode := h.getRandNode()
t.L().Printf("checking that `node status` (from n%d) shows all nodes as active\n",
runNode)
o, err := execCLI(ctx, t, c, runNode, "node", "status", "--format=csv", "--decommission")
if err != nil {
t.Fatalf("node-status failed: %v", err)
}
numCols, err := cli.GetCsvNumCols(o)
require.NoError(t, err)
var colRegex []string
for i := 1; i <= c.Spec().NodeCount; i++ {
colRegex = append(colRegex, `active`)
}
exp := h.expectColumn(statusHeaderMembershipColumnIdx, colRegex, c.Spec().NodeCount, numCols)
if err := cli.MatchCSV(o, exp); err != nil {
t.Fatal(err)
}
}
}
// Fully decommission two random nodes, from a random node, randomly choosing
// between using --wait={all,none}. We pin these two nodes to not re-use
// them for the block after, as they will have been fully decommissioned and
// by definition, non-operational.
decommissionedNodeA := h.getRandNode()
h.blockFromRandNode(decommissionedNodeA)
decommissionedNodeB := h.getRandNode() // note A != B
h.blockFromRandNode(decommissionedNodeB)
{
targetNodeA, targetNodeB := decommissionedNodeA, decommissionedNodeB
if targetNodeB < targetNodeA {
targetNodeB, targetNodeA = targetNodeA, targetNodeB
}
runNode := h.getRandNode()
waitStrategy := "all" // Blocking decommission.
if i := rand.Intn(2); i == 0 {
waitStrategy = "none" // Polling decommission.
}
t.L().Printf("fully decommissioning [n%d,n%d] from n%d, using --wait=%s\n",
targetNodeA, targetNodeB, runNode, waitStrategy)
// When using --wait=none, we poll the decommission status.
maxAttempts := 50
if waitStrategy == "all" {
// --wait=all is a one shot attempt at decommissioning, that polls
// internally.
maxAttempts = 1
}
// Decommission two nodes.
if err := retry.WithMaxAttempts(ctx, retryOpts, maxAttempts, func() error {
o, err := h.decommission(ctx, c.Nodes(targetNodeA, targetNodeB), runNode,
fmt.Sprintf("--wait=%s", waitStrategy), "--format=csv")
if err != nil {
t.Fatalf("decommission failed: %v", err)
}
exp := [][]string{
decommissionHeader,
{strconv.Itoa(targetNodeA), "true|false", "0", "true", "decommissioned", "false"},
{strconv.Itoa(targetNodeB), "true|false", "0", "true", "decommissioned", "false"},
decommissionFooter,
}
return cli.MatchCSV(cli.RemoveMatchingLines(o, warningFilter), exp)
}); err != nil {
t.Fatal(err)
}
// Check that the two decommissioned nodes vanish from `node ls` (since they
// will not remain live as the cluster refuses connections from them).
{
if err := retry.WithMaxAttempts(ctx, retry.Options{}, 50, func() error {
runNode = h.getRandNode()
t.L().Printf("checking that `node ls` (from n%d) shows n-2 nodes\n", runNode)
o, err := execCLI(ctx, t, c, runNode, "node", "ls", "--format=csv")
if err != nil {
t.Fatalf("node-ls failed: %v", err)
}
exp := [][]string{{"id"}}
for i := 1; i <= c.Spec().NodeCount; i++ {
if _, ok := h.randNodeBlocklist[i]; ok {
// Decommissioned, so should go away in due time.
continue
}
exp = append(exp, []string{strconv.Itoa(i)})
}
return cli.MatchCSV(o, exp)
}); err != nil {
t.Fatal(err)
}
}
// Ditto for `node status`.
{
if err := retry.WithMaxAttempts(ctx, retry.Options{}, 50, func() error {
runNode = h.getRandNode()
t.L().Printf("checking that `node status` (from n%d) shows only live nodes\n", runNode)
o, err := execCLI(ctx, t, c, runNode, "node", "status", "--format=csv")
if err != nil {
t.Fatalf("node-status failed: %v", err)
}
numCols, err := cli.GetCsvNumCols(o)
require.NoError(t, err)
colRegex := []string{}
for i := 1; i <= c.Spec().NodeCount; i++ {
if _, ok := h.randNodeBlocklist[i]; ok {
continue // decommissioned
}
colRegex = append(colRegex, strconv.Itoa(i))
}
exp := h.expectIDsInStatusOut(colRegex, numCols)
return cli.MatchCSV(o, exp)
}); err != nil {
t.Fatal(err)
}
}
// Attempt to recommission the fully decommissioned nodes (expecting it
// to fail).
{
runNode = h.getRandNode()
t.L().Printf("expected to fail: recommissioning [n%d,n%d] (from n%d)\n",
targetNodeA, targetNodeB, runNode)
if _, err := h.recommission(ctx, c.Nodes(targetNodeA, targetNodeB), runNode); err == nil {
t.Fatal("expected recommission to fail")
}
}
// Decommissioning the same nodes again should be a no-op. We do it from
// a random node.
{
runNode = h.getRandNode()
t.L().Printf("checking that decommissioning [n%d,n%d] (from n%d) is a no-op\n",
targetNodeA, targetNodeB, runNode)
o, err := h.decommission(ctx, c.Nodes(targetNodeA, targetNodeB), runNode,
"--wait=all", "--format=csv")
if err != nil {
t.Fatalf("decommission failed: %v", err)
}
exp := [][]string{
decommissionHeader,
// NB: the "false" is liveness. We waited above for these nodes to
// vanish from `node ls`, so definitely not live at this point.
{strconv.Itoa(targetNodeA), "false", "0", "true", "decommissioned", "false"},
{strconv.Itoa(targetNodeB), "false", "0", "true", "decommissioned", "false"},
decommissionFooter,
}
if err := cli.MatchCSV(cli.RemoveMatchingLines(o, warningFilter), exp); err != nil {
t.Fatal(err)
}
}
// We restart the nodes and attempt to recommission (should still fail).
{
runNode = h.getRandNode()
t.L().Printf("expected to fail: restarting [n%d,n%d] and attempting to recommission through n%d\n",
targetNodeA, targetNodeB, runNode)
c.Stop(ctx, t.L(), option.DefaultStopOpts(), c.Nodes(targetNodeA, targetNodeB))
c.Start(ctx, t.L(), option.DefaultStartOpts(), settings, c.Nodes(targetNodeA, targetNodeB))
if _, err := h.recommission(ctx, c.Nodes(targetNodeA, targetNodeB), runNode); err == nil {
t.Fatalf("expected recommission to fail")
}
// Now stop+wipe them for good to keep the logs simple and the dead node detector happy.
c.Stop(ctx, t.L(), option.DefaultStopOpts(), c.Nodes(targetNodeA, targetNodeB))
c.Wipe(ctx, c.Nodes(targetNodeA, targetNodeB))
}
}
// Decommission a downed node (random selected), randomly choosing between
// bringing the node back to life or leaving it permanently dead.
//
// TODO(irfansharif): We could pull merge this "deadness" check into the
// previous block, when fully decommissioning multiple nodes, to reduce the
// total number of nodes needed in the cluster.
{
restartDownedNode := false
if i := rand.Intn(2); i == 0 {
restartDownedNode = true
}
if !restartDownedNode {
// We want to test decommissioning a truly dead node. Make sure we
// don't waste too much time waiting for the node to be recognized
// as dead. Note that we don't want to set this number too low or
// everything will seem dead to the allocator at all times, so
// nothing will ever happen.
func() {
db := c.Conn(ctx, t.L(), h.getRandNode())
defer db.Close()
const stmt = "SET CLUSTER SETTING server.time_until_store_dead = '1m15s'"
if _, err := db.ExecContext(ctx, stmt); err != nil {
t.Fatal(err)
}
}()
}
// We also have to exclude the first node seeing as how we're going to
// wiping it below. Roachprod attempts to initialize a cluster when
// starting a "fresh" first node (without an existing bootstrap marker
// on disk, which we happen to also be wiping away).
targetNode := h.getRandNodeOtherThan(firstNodeID)
h.blockFromRandNode(targetNode)
t.L().Printf("intentionally killing n%d to later decommission it when down\n", targetNode)
c.Stop(ctx, t.L(), option.DefaultStopOpts(), c.Node(targetNode))
// Pick a runNode that is still in commission and will
// remain so (or it won't be able to contact cluster).
runNode := h.getRandNode()
t.L().Printf("decommissioning n%d (from n%d) in absentia\n", targetNode, runNode)
if _, err := h.decommission(ctx, c.Node(targetNode), runNode,
"--wait=all", "--format=csv"); err != nil {
t.Fatalf("decommission failed: %v", err)
}
if restartDownedNode {
t.L().Printf("restarting n%d for verification\n", targetNode)
// Bring targetNode it back up to verify that its replicas still get
// removed.
c.Start(ctx, t.L(), option.DefaultStartOpts(), settings, c.Node(targetNode))
}
// Run decommission a second time to wait until the replicas have
// all been GC'ed. Note that we specify "all" because even though
// the target node is now running, it may not be live by the time
// the command runs.
o, err := h.decommission(ctx, c.Node(targetNode), runNode,
"--wait=all", "--format=csv")
if err != nil {
t.Fatalf("decommission failed: %v", err)
}
exp := [][]string{
decommissionHeader,
{strconv.Itoa(targetNode), "true|false", "0", "true", "decommissioned", "false"},
decommissionFooter,
}
if err := cli.MatchCSV(cli.RemoveMatchingLines(o, warningFilter), exp); err != nil {
t.Fatal(err)
}
if !restartDownedNode {
// Check that (at least after a bit) the node disappears from `node
// ls` because it is decommissioned and not live.
if err := retry.WithMaxAttempts(ctx, retryOpts, 50, func() error {
runNode := h.getRandNode()
o, err := execCLI(ctx, t, c, runNode, "node", "ls", "--format=csv")
if err != nil {
t.Fatalf("node-ls failed: %v", err)
}
var exp [][]string
// We expect an entry for every node we haven't decommissioned yet.
for i := 1; i <= c.Spec().NodeCount-len(h.randNodeBlocklist); i++ {
exp = append(exp, []string{fmt.Sprintf("[^%d]", targetNode)})
}
return cli.MatchCSV(o, exp)
}); err != nil {
t.Fatal(err)
}
// Ditto for `node status`
if err := retry.WithMaxAttempts(ctx, retryOpts, 50, func() error {
runNode := h.getRandNode()
o, err := execCLI(ctx, t, c, runNode, "node", "status", "--format=csv")
if err != nil {
t.Fatalf("node-status failed: %v", err)
}
numCols, err := cli.GetCsvNumCols(o)
require.NoError(t, err)
var expC []string
for i := 1; i <= c.Spec().NodeCount-len(h.randNodeBlocklist); i++ {
expC = append(expC, fmt.Sprintf("[^%d].*", targetNode))
}
exp := h.expectIDsInStatusOut(expC, numCols)
return cli.MatchCSV(o, exp)
}); err != nil {
t.Fatal(err)
}
}
{
t.L().Printf("wiping n%d and adding it back to the cluster as a new node\n", targetNode)
c.Stop(ctx, t.L(), option.DefaultStopOpts(), c.Node(targetNode))
c.Wipe(ctx, c.Node(targetNode))
joinNode := h.getRandNode()
internalAddrs, err := c.InternalAddr(ctx, t.L(), c.Node(joinNode))
if err != nil {
t.Fatal(err)
}
joinAddr := internalAddrs[0]
startOpts := option.DefaultStartOpts()
startOpts.RoachprodOpts.ExtraArgs = append(startOpts.RoachprodOpts.ExtraArgs, fmt.Sprintf("--join %s", joinAddr))
c.Start(ctx, t.L(), startOpts, install.MakeClusterSettings(), c.Node(targetNode))
}
if err := retry.WithMaxAttempts(ctx, retryOpts, 50, func() error {
o, err := execCLI(ctx, t, c, h.getRandNode(), "node", "status", "--format=csv")
if err != nil {
t.Fatalf("node-status failed: %v", err)
}
numCols, err := cli.GetCsvNumCols(o)
require.NoError(t, err)
var expC []string
// The decommissioned nodes should all disappear. (We
// abuse that nodeIDs are single-digit in this test).
re := `[^`
for id := range h.randNodeBlocklist {
re += fmt.Sprint(id)
}
re += `].*`
// We expect to all the decommissioned nodes to
// disappear, but we let one rejoin as a fresh node.
for i := 1; i <= c.Spec().NodeCount-len(h.randNodeBlocklist)+1; i++ {
expC = append(expC, re)
}
exp := h.expectIDsInStatusOut(expC, numCols)
return cli.MatchCSV(o, exp)
}); err != nil {
t.Fatal(err)
}
}
// We'll verify the set of events, in order, we expect to get posted to
// system.eventlog.
if err := retry.ForDuration(time.Minute, func() error {
// Verify the event log has recorded exactly one decommissioned or
// recommissioned event for each membership operation.
db := c.Conn(ctx, t.L(), h.getRandNode())
defer db.Close()
rows, err := db.Query(`
SELECT "eventType" FROM system.eventlog WHERE "eventType" IN ($1, $2, $3) ORDER BY timestamp
`, "node_decommissioned", "node_decommissioning", "node_recommissioned",
)
if err != nil {
t.L().Printf("retrying: %v\n", err)
return err
}
defer rows.Close()
matrix, err := sqlutils.RowsToStrMatrix(rows)
if err != nil {
return err
}
expMatrix := [][]string{
// Partial decommission attempt of a single node.
{"node_decommissioning"},
{"node_recommissioned"},
// Cluster wide decommissioning attempt.
{"node_decommissioning"},
{"node_decommissioning"},
{"node_decommissioning"},
{"node_decommissioning"},
{"node_decommissioning"},
{"node_decommissioning"},
// Cluster wide recommissioning, to undo previous decommissioning attempt.
{"node_recommissioned"},
{"node_recommissioned"},
{"node_recommissioned"},
{"node_recommissioned"},
{"node_recommissioned"},
{"node_recommissioned"},