forked from apache/zookeeper
/
QuorumPeerMainTest.java
1839 lines (1566 loc) · 74 KB
/
QuorumPeerMainTest.java
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
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 org.apache.zookeeper.server.quorum;
import static org.apache.zookeeper.test.ClientBase.CONNECTION_TIMEOUT;
import static org.apache.zookeeper.test.ClientBase.createEmptyTestDir;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doCallRealMethod;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.LineNumberReader;
import java.io.StringReader;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.file.Paths;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.regex.Pattern;
import javax.security.sasl.SaslException;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.WriterAppender;
import org.apache.zookeeper.AsyncCallback;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.PortAssignment;
import org.apache.zookeeper.ZooDefs.OpCode;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper.States;
import org.apache.zookeeper.common.Time;
import org.apache.zookeeper.common.X509Exception;
import org.apache.zookeeper.data.Stat;
import org.apache.zookeeper.metrics.BaseTestMetricsProvider;
import org.apache.zookeeper.metrics.impl.NullMetricsProvider;
import org.apache.zookeeper.server.persistence.FileTxnSnapLog;
import org.apache.zookeeper.server.quorum.Leader.Proposal;
import org.apache.zookeeper.test.ClientBase;
import org.junit.Assert;
import org.junit.Test;
/**
* Test stand-alone server.
*
*/
public class QuorumPeerMainTest extends QuorumPeerTestBase {
/**
* Verify the ability to start a cluster.
*/
public void testQuorumInternal(String addr) throws Exception {
ClientBase.setupTestEnv();
final int CLIENT_PORT_QP1 = PortAssignment.unique();
final int CLIENT_PORT_QP2 = PortAssignment.unique();
String quorumCfgSection = String.format("server.1=%1$s:%2$s:%3$s;%4$s",
addr,
PortAssignment.unique(),
PortAssignment.unique(),
CLIENT_PORT_QP1) + "\n" +
String.format("server.2=%1$s:%2$s:%3$s;%4$s",
addr,
PortAssignment.unique(),
PortAssignment.unique(),
CLIENT_PORT_QP2);
MainThread q1 = new MainThread(1, CLIENT_PORT_QP1, quorumCfgSection);
MainThread q2 = new MainThread(2, CLIENT_PORT_QP2, quorumCfgSection);
q1.start();
q2.start();
Assert.assertTrue("waiting for server 1 being up",
ClientBase.waitForServerUp(addr + ":" + CLIENT_PORT_QP1,
CONNECTION_TIMEOUT));
Assert.assertTrue("waiting for server 2 being up",
ClientBase.waitForServerUp(addr + ":" + CLIENT_PORT_QP2,
CONNECTION_TIMEOUT));
QuorumPeer quorumPeer = q1.main.quorumPeer;
int tickTime = quorumPeer.getTickTime();
Assert.assertEquals(
"Default value of minimumSessionTimeOut is not considered",
tickTime * 2, quorumPeer.getMinSessionTimeout());
Assert.assertEquals(
"Default value of maximumSessionTimeOut is not considered",
tickTime * 20, quorumPeer.getMaxSessionTimeout());
ZooKeeper zk = new ZooKeeper(addr + ":" + CLIENT_PORT_QP1,
ClientBase.CONNECTION_TIMEOUT, this);
waitForOne(zk, States.CONNECTED);
zk.create("/foo_q1", "foobar1".getBytes(), Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT);
Assert.assertEquals(new String(zk.getData("/foo_q1", null, null)), "foobar1");
zk.close();
zk = new ZooKeeper(addr + ":" + CLIENT_PORT_QP2,
ClientBase.CONNECTION_TIMEOUT, this);
waitForOne(zk, States.CONNECTED);
zk.create("/foo_q2", "foobar2".getBytes(), Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT);
Assert.assertEquals(new String(zk.getData("/foo_q2", null, null)), "foobar2");
zk.close();
q1.shutdown();
q2.shutdown();
Assert.assertTrue("waiting for server 1 down",
ClientBase.waitForServerDown(addr + ":" + CLIENT_PORT_QP1,
ClientBase.CONNECTION_TIMEOUT));
Assert.assertTrue("waiting for server 2 down",
ClientBase.waitForServerDown(addr + ":" + CLIENT_PORT_QP2,
ClientBase.CONNECTION_TIMEOUT));
}
/**
* Verify the ability to start a cluster.
*/
@Test
public void testQuorum() throws Exception {
testQuorumInternal("127.0.0.1");
}
/**
* Verify the ability to start a cluster. IN V6!!!!
*/
@Test
public void testQuorumV6() throws Exception {
testQuorumInternal("[::1]");
}
/**
* Test early leader abandonment.
*/
@Test
public void testEarlyLeaderAbandonment() throws Exception {
ClientBase.setupTestEnv();
final int SERVER_COUNT = 3;
final int clientPorts[] = new int[SERVER_COUNT];
StringBuilder sb = new StringBuilder();
for(int i = 0; i < SERVER_COUNT; i++) {
clientPorts[i] = PortAssignment.unique();
sb.append("server."+i+"=127.0.0.1:"+PortAssignment.unique()+":"+PortAssignment.unique()+";"+clientPorts[i]+"\n");
}
String quorumCfgSection = sb.toString();
MainThread mt[] = new MainThread[SERVER_COUNT];
ZooKeeper zk[] = new ZooKeeper[SERVER_COUNT];
for (int i = 0; i < SERVER_COUNT; i++) {
mt[i] = new MainThread(i, clientPorts[i], quorumCfgSection);
mt[i].start();
zk[i] = new ZooKeeper("127.0.0.1:" + clientPorts[i], ClientBase.CONNECTION_TIMEOUT, this);
}
waitForAll(zk, States.CONNECTED);
// we need to shutdown and start back up to make sure that the create session isn't the first transaction since
// that is rather innocuous.
for (int i = 0; i < SERVER_COUNT; i++) {
mt[i].shutdown();
}
waitForAll(zk, States.CONNECTING);
for (int i = 0; i < SERVER_COUNT; i++) {
mt[i].start();
// Recreate a client session since the previous session was not persisted.
zk[i] = new ZooKeeper("127.0.0.1:" + clientPorts[i], ClientBase.CONNECTION_TIMEOUT, this);
}
waitForAll(zk, States.CONNECTED);
// ok lets find the leader and kill everything else, we have a few
// seconds, so it should be plenty of time
int leader = -1;
Map<Long, Proposal> outstanding = null;
for (int i = 0; i < SERVER_COUNT; i++) {
if (mt[i].main.quorumPeer.leader == null) {
mt[i].shutdown();
} else {
leader = i;
outstanding = mt[leader].main.quorumPeer.leader.outstandingProposals;
}
}
try {
zk[leader].create("/zk" + leader, "zk".getBytes(), Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT);
Assert.fail("create /zk" + leader + " should have failed");
} catch (KeeperException e) {}
// just make sure that we actually did get it in process at the
// leader
Assert.assertTrue(outstanding.size() == 1);
Assert.assertTrue(((Proposal) outstanding.values().iterator().next()).request.getHdr().getType() == OpCode.create);
// make sure it has a chance to write it to disk
Thread.sleep(1000);
mt[leader].shutdown();
waitForAll(zk, States.CONNECTING);
for (int i = 0; i < SERVER_COUNT; i++) {
if (i != leader) {
mt[i].start();
}
}
for (int i = 0; i < SERVER_COUNT; i++) {
if (i != leader) {
// Recreate a client session since the previous session was not persisted.
zk[i] = new ZooKeeper("127.0.0.1:" + clientPorts[i], ClientBase.CONNECTION_TIMEOUT, this);
waitForOne(zk[i], States.CONNECTED);
zk[i].create("/zk" + i, "zk".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
}
mt[leader].start();
waitForAll(zk, States.CONNECTED);
// make sure everything is consistent
for (int i = 0; i < SERVER_COUNT; i++) {
for (int j = 0; j < SERVER_COUNT; j++) {
if (i == leader) {
Assert.assertTrue((j == leader ? ("Leader (" + leader + ")") : ("Follower " + j)) + " should not have /zk" + i, zk[j].exists("/zk" + i, false) == null);
} else {
Assert.assertTrue((j == leader ? ("Leader (" + leader + ")") : ("Follower " + j)) + " does not have /zk" + i, zk[j].exists("/zk" + i, false) != null);
}
}
}
for (int i = 0; i < SERVER_COUNT; i++) {
zk[i].close();
}
for (int i = 0; i < SERVER_COUNT; i++) {
mt[i].shutdown();
}
}
/**
* Test the case of server with highest zxid not present at leader election and joining later.
* This test case is for reproducing the issue and fixing the bug mentioned in ZOOKEEPER-1154
* and ZOOKEEPER-1156.
*/
@Test
public void testHighestZxidJoinLate() throws Exception {
numServers = 3;
servers = LaunchServers(numServers);
String path = "/hzxidtest";
int leader = servers.findLeader();
// make sure there is a leader
Assert.assertTrue("There should be a leader", leader >= 0);
int nonleader = (leader + 1) % numServers;
byte[] input = new byte[1];
input[0] = 1;
byte[] output;
// Create a couple of nodes
servers.zk[leader].create(path + leader, input, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
servers.zk[leader].create(path + nonleader, input, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
// make sure the updates indeed committed. If it is not
// the following statement will throw.
output = servers.zk[leader].getData(path + nonleader, false, null);
// Shutdown every one else but the leader
for (int i = 0; i < numServers; i++) {
if (i != leader) {
servers.mt[i].shutdown();
}
}
input[0] = 2;
// Update the node on the leader
servers.zk[leader].setData(path + leader, input, -1, null, null);
// wait some time to let this get written to disk
Thread.sleep(500);
// shut the leader down
servers.mt[leader].shutdown();
System.gc();
waitForAll(servers.zk, States.CONNECTING);
// Start everyone but the leader
for (int i = 0; i < numServers; i++) {
if (i != leader) {
servers.mt[i].start();
}
}
// wait to connect to one of these
waitForOne(servers.zk[nonleader], States.CONNECTED);
// validate that the old value is there and not the new one
output = servers.zk[nonleader].getData(path + leader, false, null);
Assert.assertEquals(
"Expecting old value 1 since 2 isn't committed yet",
output[0], 1);
// Do some other update, so we bump the maxCommttedZxid
// by setting the value to 2
servers.zk[nonleader].setData(path + nonleader, input, -1);
// start the old leader
servers.mt[leader].start();
// connect to it
waitForOne(servers.zk[leader], States.CONNECTED);
// make sure it doesn't have the new value that it alone had logged
output = servers.zk[leader].getData(path + leader, false, null);
Assert.assertEquals(
"Validating that the deposed leader has rolled back that change it had written",
output[0], 1);
// make sure the leader has the subsequent changes that were made while it was offline
output = servers.zk[leader].getData(path + nonleader, false, null);
Assert.assertEquals(
"Validating that the deposed leader caught up on changes it missed",
output[0], 2);
}
/**
* This test validates that if a quorum member determines that it is leader without the support of the rest of the
* quorum (the other members do not believe it to be the leader) it will stop attempting to lead and become a follower.
*
* @throws IOException
* @throws InterruptedException
*/
@Test
public void testElectionFraud() throws IOException, InterruptedException {
// capture QuorumPeer logging
ByteArrayOutputStream os = new ByteArrayOutputStream();
WriterAppender appender = getConsoleAppender(os, Level.INFO);
Logger qlogger = Logger.getLogger(QuorumPeer.class);
qlogger.addAppender(appender);
numServers = 3;
// used for assertions later
boolean foundLeading = false;
boolean foundLooking = false;
boolean foundFollowing = false;
try {
// spin up a quorum, we use a small ticktime to make the test run faster
servers = LaunchServers(numServers, 500);
// find the leader
int trueLeader = servers.findLeader();
Assert.assertTrue("There should be a leader", trueLeader >= 0);
// find a follower
int falseLeader = (trueLeader + 1) % numServers;
Assert.assertTrue("All servers should join the quorum", servers.mt[falseLeader].main.quorumPeer.follower != null);
// to keep the quorum peer running and force it to go into the looking state, we kill leader election
servers.mt[falseLeader].main.quorumPeer.electionAlg.shutdown();
servers.mt[falseLeader].main.quorumPeer.follower.getSocket().close();
// wait for the falseLeader to disconnect
waitForOne(servers.zk[falseLeader], States.CONNECTING);
// convince falseLeader that it is the leader
servers.mt[falseLeader].main.quorumPeer.setPeerState(QuorumPeer.ServerState.LEADING);
// provide time for the falseleader to realize no followers have connected
// (this is twice the timeout used in Leader#getEpochToPropose)
Thread.sleep(2 * servers.mt[falseLeader].main.quorumPeer.initLimit * servers.mt[falseLeader].main.quorumPeer.tickTime);
// Restart leader election
servers.mt[falseLeader].main.quorumPeer.startLeaderElection();
// The previous client connection to falseLeader likely closed, create a new one
servers.zk[falseLeader] = new ZooKeeper("127.0.0.1:" + servers.mt[falseLeader].getClientPort(), ClientBase.CONNECTION_TIMEOUT, this);
// Wait for falseLeader to rejoin the quorum
waitForOne(servers.zk[falseLeader], States.CONNECTED);
// and ensure trueLeader is still the leader
Assert.assertTrue(servers.mt[trueLeader].main.quorumPeer.leader != null);
// Look through the logs for output that indicates the falseLeader is LEADING, then LOOKING, then FOLLOWING
LineNumberReader r = new LineNumberReader(new StringReader(os.toString()));
Pattern leading = Pattern.compile(".*myid=" + falseLeader + ".*LEADING.*");
Pattern looking = Pattern.compile(".*myid=" + falseLeader + ".*LOOKING.*");
Pattern following = Pattern.compile(".*myid=" + falseLeader + ".*FOLLOWING.*");
String line;
while ((line = r.readLine()) != null) {
if (!foundLeading) {
foundLeading = leading.matcher(line).matches();
} else if(!foundLooking) {
foundLooking = looking.matcher(line).matches();
} else if (following.matcher(line).matches()){
foundFollowing = true;
break;
}
}
} finally {
qlogger.removeAppender(appender);
}
Assert.assertTrue("falseLeader never attempts to become leader", foundLeading);
Assert.assertTrue("falseLeader never gives up on leadership", foundLooking);
Assert.assertTrue("falseLeader never rejoins the quorum", foundFollowing);
}
/**
* Verify handling of bad quorum address
*/
@Test
public void testBadPeerAddressInQuorum() throws Exception {
ClientBase.setupTestEnv();
// setup the logger to capture all logs
ByteArrayOutputStream os = new ByteArrayOutputStream();
WriterAppender appender = getConsoleAppender(os, Level.WARN);
Logger qlogger = Logger.getLogger("org.apache.zookeeper.server.quorum");
qlogger.addAppender(appender);
try {
final int CLIENT_PORT_QP1 = PortAssignment.unique();
final int CLIENT_PORT_QP2 = PortAssignment.unique();
String quorumCfgSection =
"server.1=127.0.0.1:" + PortAssignment.unique()
+ ":" + PortAssignment.unique() + ";" + CLIENT_PORT_QP1
+ "\nserver.2=fee.fii.foo.fum:" + PortAssignment.unique()
+ ":" + PortAssignment.unique() + ";" + CLIENT_PORT_QP2;
MainThread q1 = new MainThread(1, CLIENT_PORT_QP1, quorumCfgSection);
q1.start();
boolean isup =
ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP1,
30000);
Assert.assertFalse("Server never came up", isup);
q1.shutdown();
Assert.assertTrue("waiting for server 1 down",
ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT_QP1,
ClientBase.CONNECTION_TIMEOUT));
} finally {
qlogger.removeAppender(appender);
}
LineNumberReader r = new LineNumberReader(new StringReader(os.toString()));
String line;
boolean found = false;
Pattern p = Pattern.compile(".*None of the addresses .* are reachable for sid 2");
while ((line = r.readLine()) != null) {
found = p.matcher(line).matches();
if (found) {
break;
}
}
Assert.assertTrue("complains about host", found);
}
/**
* Verify handling of inconsistent peer type
*/
@Test
public void testInconsistentPeerType() throws Exception {
ClientBase.setupTestEnv();
// setup the logger to capture all logs
ByteArrayOutputStream os = new ByteArrayOutputStream();
WriterAppender appender = getConsoleAppender(os, Level.INFO);
Logger qlogger = Logger.getLogger("org.apache.zookeeper.server.quorum");
qlogger.addAppender(appender);
// test the most likely situation only: server is stated as observer in
// servers list, but there's no "peerType=observer" token in config
try {
final int CLIENT_PORT_QP1 = PortAssignment.unique();
final int CLIENT_PORT_QP2 = PortAssignment.unique();
final int CLIENT_PORT_QP3 = PortAssignment.unique();
String quorumCfgSection =
"server.1=127.0.0.1:" + PortAssignment.unique()
+ ":" + PortAssignment.unique() + ";" + CLIENT_PORT_QP1
+ "\nserver.2=127.0.0.1:" + PortAssignment.unique()
+ ":" + PortAssignment.unique() + ";" + CLIENT_PORT_QP2
+ "\nserver.3=127.0.0.1:" + PortAssignment.unique()
+ ":" + PortAssignment.unique() + ":observer" + ";" + CLIENT_PORT_QP3;
MainThread q1 = new MainThread(1, CLIENT_PORT_QP1, quorumCfgSection);
MainThread q2 = new MainThread(2, CLIENT_PORT_QP2, quorumCfgSection);
MainThread q3 = new MainThread(3, CLIENT_PORT_QP3, quorumCfgSection);
q1.start();
q2.start();
q3.start();
Assert.assertTrue("waiting for server 1 being up",
ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP1,
CONNECTION_TIMEOUT));
Assert.assertTrue("waiting for server 2 being up",
ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP2,
CONNECTION_TIMEOUT));
Assert.assertTrue("waiting for server 3 being up",
ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP3,
CONNECTION_TIMEOUT));
q1.shutdown();
q2.shutdown();
q3.shutdown();
Assert.assertTrue("waiting for server 1 down",
ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT_QP1,
ClientBase.CONNECTION_TIMEOUT));
Assert.assertTrue("waiting for server 2 down",
ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT_QP2,
ClientBase.CONNECTION_TIMEOUT));
Assert.assertTrue("waiting for server 3 down",
ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT_QP3,
ClientBase.CONNECTION_TIMEOUT));
} finally {
qlogger.removeAppender(appender);
}
LineNumberReader r = new LineNumberReader(new StringReader(os.toString()));
String line;
boolean warningPresent = false;
boolean defaultedToObserver = false;
Pattern pWarn =
Pattern.compile(".*Peer type from servers list.* doesn't match peerType.*");
Pattern pObserve = Pattern.compile(".*OBSERVING.*");
while ((line = r.readLine()) != null) {
if (pWarn.matcher(line).matches()) {
warningPresent = true;
}
if (pObserve.matcher(line).matches()) {
defaultedToObserver = true;
}
if (warningPresent && defaultedToObserver) {
break;
}
}
Assert.assertTrue("Should warn about inconsistent peer type",
warningPresent && defaultedToObserver);
}
/**
* verify if bad packets are being handled properly
* at the quorum port
* @throws Exception
*/
@Test
public void testBadPackets() throws Exception {
ClientBase.setupTestEnv();
final int CLIENT_PORT_QP1 = PortAssignment.unique();
final int CLIENT_PORT_QP2 = PortAssignment.unique();
int electionPort1 = PortAssignment.unique();
int electionPort2 = PortAssignment.unique();
String quorumCfgSection =
"server.1=127.0.0.1:" + PortAssignment.unique()
+ ":" + electionPort1 + ";" + CLIENT_PORT_QP1
+ "\nserver.2=127.0.0.1:" + PortAssignment.unique()
+ ":" + electionPort2 + ";" + CLIENT_PORT_QP2;
MainThread q1 = new MainThread(1, CLIENT_PORT_QP1, quorumCfgSection);
MainThread q2 = new MainThread(2, CLIENT_PORT_QP2, quorumCfgSection);
q1.start();
q2.start();
Assert.assertTrue("waiting for server 1 being up",
ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP1,
CONNECTION_TIMEOUT));
Assert.assertTrue("waiting for server 2 being up",
ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP2,
CONNECTION_TIMEOUT));
byte[] b = new byte[4];
int length = 1024 * 1024 * 1024;
ByteBuffer buff = ByteBuffer.wrap(b);
buff.putInt(length);
buff.position(0);
SocketChannel s = SocketChannel.open(new InetSocketAddress("127.0.0.1", electionPort1));
s.write(buff);
s.close();
buff.position(0);
s = SocketChannel.open(new InetSocketAddress("127.0.0.1", electionPort2));
s.write(buff);
s.close();
ZooKeeper zk = new ZooKeeper("127.0.0.1:" + CLIENT_PORT_QP1,
ClientBase.CONNECTION_TIMEOUT, this);
waitForOne(zk, States.CONNECTED);
zk.create("/foo_q1", "foobar1".getBytes(), Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT);
Assert.assertEquals(new String(zk.getData("/foo_q1", null, null)), "foobar1");
zk.close();
q1.shutdown();
q2.shutdown();
}
/**
* Verify handling of quorum defaults
* * default electionAlg is fast leader election
*/
@Test
public void testQuorumDefaults() throws Exception {
ClientBase.setupTestEnv();
// setup the logger to capture all logs
ByteArrayOutputStream os = new ByteArrayOutputStream();
WriterAppender appender = getConsoleAppender(os, Level.INFO);
appender.setImmediateFlush(true);
Logger zlogger = Logger.getLogger("org.apache.zookeeper");
zlogger.addAppender(appender);
try {
final int CLIENT_PORT_QP1 = PortAssignment.unique();
final int CLIENT_PORT_QP2 = PortAssignment.unique();
String quorumCfgSection =
"server.1=127.0.0.1:" + PortAssignment.unique()
+ ":" + PortAssignment.unique() + ";" + CLIENT_PORT_QP1
+ "\nserver.2=127.0.0.1:" + PortAssignment.unique()
+ ":" + PortAssignment.unique() + ";" + CLIENT_PORT_QP2;
MainThread q1 = new MainThread(1, CLIENT_PORT_QP1, quorumCfgSection);
MainThread q2 = new MainThread(2, CLIENT_PORT_QP2, quorumCfgSection);
q1.start();
q2.start();
Assert.assertTrue("waiting for server 1 being up",
ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP1,
CONNECTION_TIMEOUT));
Assert.assertTrue("waiting for server 2 being up",
ClientBase.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP2,
CONNECTION_TIMEOUT));
q1.shutdown();
q2.shutdown();
Assert.assertTrue("waiting for server 1 down",
ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT_QP1,
ClientBase.CONNECTION_TIMEOUT));
Assert.assertTrue("waiting for server 2 down",
ClientBase.waitForServerDown("127.0.0.1:" + CLIENT_PORT_QP2,
ClientBase.CONNECTION_TIMEOUT));
} finally {
zlogger.removeAppender(appender);
}
os.close();
LineNumberReader r = new LineNumberReader(new StringReader(os.toString()));
String line;
boolean found = false;
Pattern p =
Pattern.compile(".*FastLeaderElection.*");
while ((line = r.readLine()) != null) {
found = p.matcher(line).matches();
if (found) {
break;
}
}
Assert.assertTrue("fastleaderelection used", found);
}
/**
* Verifies that QuorumPeer exits immediately
*/
@Test
public void testQuorumPeerExitTime() throws Exception {
long maxwait = 3000;
final int CLIENT_PORT_QP1 = PortAssignment.unique();
String quorumCfgSection =
"server.1=127.0.0.1:" + PortAssignment.unique()
+ ":" + PortAssignment.unique() + ";" + CLIENT_PORT_QP1
+ "\nserver.2=127.0.0.1:" + PortAssignment.unique()
+ ":" + PortAssignment.unique() + ";" + PortAssignment.unique();
MainThread q1 = new MainThread(1, CLIENT_PORT_QP1, quorumCfgSection);
q1.start();
// Let the notifications timeout
Thread.sleep(30000);
long start = Time.currentElapsedTime();
q1.shutdown();
long end = Time.currentElapsedTime();
if ((end - start) > maxwait) {
Assert.fail("QuorumPeer took " + (end - start) +
" to shutdown, expected " + maxwait);
}
}
/**
* Test verifies that the server is able to redefine the min/max session
* timeouts
*/
@Test
public void testMinMaxSessionTimeOut() throws Exception {
ClientBase.setupTestEnv();
final int CLIENT_PORT_QP1 = PortAssignment.unique();
final int CLIENT_PORT_QP2 = PortAssignment.unique();
String quorumCfgSection = "server.1=127.0.0.1:"
+ PortAssignment.unique() + ":" + PortAssignment.unique()
+ "\nserver.2=127.0.0.1:" + PortAssignment.unique() + ":"
+ PortAssignment.unique();
final int minSessionTimeOut = 10000;
final int maxSessionTimeOut = 15000;
final String configs = "maxSessionTimeout=" + maxSessionTimeOut + "\n"
+ "minSessionTimeout=" + minSessionTimeOut + "\n";
MainThread q1 = new MainThread(1, CLIENT_PORT_QP1, quorumCfgSection,
configs);
MainThread q2 = new MainThread(2, CLIENT_PORT_QP2, quorumCfgSection,
configs);
q1.start();
q2.start();
Assert.assertTrue("waiting for server 1 being up", ClientBase
.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP1,
CONNECTION_TIMEOUT));
Assert.assertTrue("waiting for server 2 being up", ClientBase
.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP2,
CONNECTION_TIMEOUT));
QuorumPeer quorumPeer = q1.main.quorumPeer;
Assert.assertEquals("minimumSessionTimeOut is not considered",
minSessionTimeOut, quorumPeer.getMinSessionTimeout());
Assert.assertEquals("maximumSessionTimeOut is not considered",
maxSessionTimeOut, quorumPeer.getMaxSessionTimeout());
}
/**
* Test verifies that the server is able to redefine if user configured only
* minSessionTimeout limit
*/
@Test
public void testWithOnlyMinSessionTimeout() throws Exception {
ClientBase.setupTestEnv();
final int CLIENT_PORT_QP1 = PortAssignment.unique();
final int CLIENT_PORT_QP2 = PortAssignment.unique();
String quorumCfgSection = "server.1=127.0.0.1:"
+ PortAssignment.unique() + ":" + PortAssignment.unique()
+ "\nserver.2=127.0.0.1:" + PortAssignment.unique() + ":"
+ PortAssignment.unique();
final int minSessionTimeOut = 15000;
final String configs = "minSessionTimeout=" + minSessionTimeOut + "\n";
MainThread q1 = new MainThread(1, CLIENT_PORT_QP1, quorumCfgSection,
configs);
MainThread q2 = new MainThread(2, CLIENT_PORT_QP2, quorumCfgSection,
configs);
q1.start();
q2.start();
Assert.assertTrue("waiting for server 1 being up", ClientBase
.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP1,
CONNECTION_TIMEOUT));
Assert.assertTrue("waiting for server 2 being up", ClientBase
.waitForServerUp("127.0.0.1:" + CLIENT_PORT_QP2,
CONNECTION_TIMEOUT));
QuorumPeer quorumPeer = q1.main.quorumPeer;
final int maxSessionTimeOut = quorumPeer.tickTime * 20;
Assert.assertEquals("minimumSessionTimeOut is not considered",
minSessionTimeOut, quorumPeer.getMinSessionTimeout());
Assert.assertEquals("maximumSessionTimeOut is wrong",
maxSessionTimeOut, quorumPeer.getMaxSessionTimeout());
}
@Test
public void testFailedTxnAsPartOfQuorumLoss() throws Exception {
final int LEADER_TIMEOUT_MS = 10_000;
// 1. start up server and wait for leader election to finish
ClientBase.setupTestEnv();
final int SERVER_COUNT = 3;
servers = LaunchServers(SERVER_COUNT);
waitForAll(servers, States.CONNECTED);
// we need to shutdown and start back up to make sure that the create session isn't the first transaction since
// that is rather innocuous.
servers.shutDownAllServers();
waitForAll(servers, States.CONNECTING);
servers.restartAllServersAndClients(this);
waitForAll(servers, States.CONNECTED);
// 2. kill all followers
int leader = servers.findLeader();
Map<Long, Proposal> outstanding = servers.mt[leader].main.quorumPeer.leader.outstandingProposals;
// increase the tick time to delay the leader going to looking
int previousTick = servers.mt[leader].main.quorumPeer.tickTime;
servers.mt[leader].main.quorumPeer.tickTime = LEADER_TIMEOUT_MS;
// let the previous tick on the leader exhaust itself so the new tick time takes effect
Thread.sleep(previousTick);
LOG.warn("LEADER {}", leader);
for (int i = 0; i < SERVER_COUNT; i++) {
if (i != leader) {
servers.mt[i].shutdown();
}
}
// 3. start up the followers to form a new quorum
for (int i = 0; i < SERVER_COUNT; i++) {
if (i != leader) {
servers.mt[i].start();
}
}
// 4. wait one of the follower to be the new leader
for (int i = 0; i < SERVER_COUNT; i++) {
if (i != leader) {
// Recreate a client session since the previous session was not persisted.
servers.restartClient(i, this);
waitForOne(servers.zk[i], States.CONNECTED);
}
}
// 5. send a create request to old leader and make sure it's synced to disk,
// which means it acked from itself
try {
servers.zk[leader].create("/zk" + leader, "zk".getBytes(), Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT);
Assert.fail("create /zk" + leader + " should have failed");
} catch (KeeperException e) {
}
// just make sure that we actually did get it in process at the
// leader
// there can be extra sessionClose proposals
Assert.assertTrue(outstanding.size() > 0);
Proposal p = findProposalOfType(outstanding, OpCode.create);
LOG.info(String.format("Old leader id: %d. All proposals: %s", leader, outstanding));
Assert.assertNotNull("Old leader doesn't have 'create' proposal", p);
// make sure it has a chance to write it to disk
int sleepTime = 0;
Long longLeader = Long.valueOf(leader);
while (!p.qvAcksetPairs.get(0).getAckset().contains(longLeader)) {
if (sleepTime > 2000) {
Assert.fail("Transaction not synced to disk within 1 second " + p.qvAcksetPairs.get(0).getAckset()
+ " expected " + leader);
}
Thread.sleep(100);
sleepTime += 100;
}
// 6. wait for the leader to quit due to not enough followers and come back up as a part of the new quorum
LOG.info("Waiting for leader {} to timeout followers", leader);
sleepTime = 0;
Follower f = servers.mt[leader].main.quorumPeer.follower;
while (f == null || !f.isRunning()) {
if (sleepTime > LEADER_TIMEOUT_MS * 2) {
Assert.fail("Took too long for old leader to time out " + servers.mt[leader].main.quorumPeer.getPeerState());
}
Thread.sleep(100);
sleepTime += 100;
f = servers.mt[leader].main.quorumPeer.follower;
}
int newLeader = servers.findLeader();
// make sure a different leader was elected
Assert.assertNotEquals(leader, newLeader);
// 7. restart the previous leader to force it to replay the edits and possibly come up in a bad state
servers.mt[leader].shutdown();
servers.mt[leader].start();
// old client session can expire, restart it
servers.restartClient(leader, this);
waitForAll(servers, States.CONNECTED);
// 8. check the node exist in previous leader but not others
// make sure everything is consistent
for (int i = 0; i < SERVER_COUNT; i++) {
Assert.assertNull("server " + i + " should not have /zk" + leader, servers.zk[i].exists("/zk" + leader, false));
}
}
/**
* Verify that a node without the leader in its view will not attempt to connect to the leader.
*/
@Test
public void testLeaderOutOfView() throws Exception {
ClientBase.setupTestEnv();
int numServers = 3;
// used for assertions later
boolean foundLeading = false;
boolean foundFollowing = false;
// capture QuorumPeer logging
ByteArrayOutputStream os = new ByteArrayOutputStream();
WriterAppender appender = getConsoleAppender(os, Level.DEBUG);
Logger qlogger = Logger.getLogger("org.apache.zookeeper.server.quorum");
qlogger.addAppender(appender);
try {
Servers svrs = new Servers();
svrs.clientPorts = new int[numServers];
for (int i = 0; i < numServers; i++) {
svrs.clientPorts[i] = PortAssignment.unique();
}
String quorumCfgIncomplete = getUniquePortCfgForId(1) + "\n" + getUniquePortCfgForId(2);
String quorumCfgComplete = quorumCfgIncomplete + "\n" + getUniquePortCfgForId(3);
svrs.mt = new MainThread[3];
// Node 1 is started without the leader (3) in its config view
svrs.mt[0] = new MainThread(1, svrs.clientPorts[0], quorumCfgIncomplete);
for (int i = 1; i < numServers; i++) {
svrs.mt[i] = new MainThread(i + 1, svrs.clientPorts[i], quorumCfgComplete);
}
// Node 1 must be started first, before quorum is formed, to trigger the attempted invalid connection to 3
svrs.mt[0].start();
QuorumPeer quorumPeer1 = waitForQuorumPeer(svrs.mt[0], CONNECTION_TIMEOUT);
Assert.assertTrue(quorumPeer1.getPeerState() == QuorumPeer.ServerState.LOOKING);
// Node 3 started second to avoid 1 and 2 forming a quorum before 3 starts up
int highestServerIndex = numServers - 1;
svrs.mt[highestServerIndex].start();
QuorumPeer quorumPeer3 = waitForQuorumPeer(svrs.mt[highestServerIndex], CONNECTION_TIMEOUT);
Assert.assertTrue(quorumPeer3.getPeerState() == QuorumPeer.ServerState.LOOKING);
// Node 2 started last, kicks off leader election
for (int i = 1; i < highestServerIndex; i++) {
svrs.mt[i].start();
}
// Nodes 2 and 3 now form quorum and fully start. 1 attempts to vote for 3, fails, returns to LOOKING state
for (int i = 1; i < numServers; i++) {
Assert.assertTrue("waiting for server to start",
ClientBase.waitForServerUp("127.0.0.1:" + svrs.clientPorts[i], CONNECTION_TIMEOUT));
}
Assert.assertTrue(svrs.mt[0].getQuorumPeer().getPeerState() == QuorumPeer.ServerState.LOOKING);
Assert.assertTrue(svrs.mt[highestServerIndex].getQuorumPeer().getPeerState() == QuorumPeer.ServerState.LEADING);
for (int i = 1; i < highestServerIndex; i++) {
Assert.assertTrue(svrs.mt[i].getQuorumPeer().getPeerState() == QuorumPeer.ServerState.FOLLOWING);
}
// Look through the logs for output that indicates Node 1 is LEADING or FOLLOWING
LineNumberReader r = new LineNumberReader(new StringReader(os.toString()));
Pattern leading = Pattern.compile(".*myid=1.*QuorumPeer.*LEADING.*");
Pattern following = Pattern.compile(".*myid=1.*QuorumPeer.*FOLLOWING.*");
String line;
while ((line = r.readLine()) != null && !foundLeading && !foundFollowing) {
foundLeading = leading.matcher(line).matches();
foundFollowing = following.matcher(line).matches();
}
} finally {
qlogger.removeAppender(appender);
}
Assert.assertFalse("Corrupt peer should never become leader", foundLeading);
Assert.assertFalse("Corrupt peer should not attempt connection to out of view leader", foundFollowing);
}
@Test
public void testDataDirAndDataLogDir() throws Exception {